config_test.py 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687
  1. # encoding: utf-8
  2. from __future__ import absolute_import
  3. from __future__ import print_function
  4. from __future__ import unicode_literals
  5. import os
  6. import shutil
  7. import tempfile
  8. from operator import itemgetter
  9. import py
  10. import pytest
  11. import yaml
  12. from ...helpers import build_config_details
  13. from compose.config import config
  14. from compose.config import types
  15. from compose.config.config import resolve_build_args
  16. from compose.config.config import resolve_environment
  17. from compose.config.config import V1
  18. from compose.config.config import V2_0
  19. from compose.config.config import V2_1
  20. from compose.config.config import V3_0
  21. from compose.config.config import V3_1
  22. from compose.config.environment import Environment
  23. from compose.config.errors import ConfigurationError
  24. from compose.config.errors import VERSION_EXPLANATION
  25. from compose.config.serialize import denormalize_service_dict
  26. from compose.config.serialize import serialize_config
  27. from compose.config.serialize import serialize_ns_time_value
  28. from compose.config.types import VolumeSpec
  29. from compose.const import IS_WINDOWS_PLATFORM
  30. from compose.utils import nanoseconds_from_time_seconds
  31. from tests import mock
  32. from tests import unittest
  33. DEFAULT_VERSION = V2_0
  34. def make_service_dict(name, service_dict, working_dir, filename=None):
  35. """Test helper function to construct a ServiceExtendsResolver
  36. """
  37. resolver = config.ServiceExtendsResolver(
  38. config.ServiceConfig(
  39. working_dir=working_dir,
  40. filename=filename,
  41. name=name,
  42. config=service_dict),
  43. config.ConfigFile(filename=filename, config={}),
  44. environment=Environment.from_env_file(working_dir)
  45. )
  46. return config.process_service(resolver.run())
  47. def service_sort(services):
  48. return sorted(services, key=itemgetter('name'))
  49. def secret_sort(secrets):
  50. return sorted(secrets, key=itemgetter('source'))
  51. class ConfigTest(unittest.TestCase):
  52. def test_load(self):
  53. service_dicts = config.load(
  54. build_config_details(
  55. {
  56. 'foo': {'image': 'busybox'},
  57. 'bar': {'image': 'busybox', 'environment': ['FOO=1']},
  58. },
  59. 'tests/fixtures/extends',
  60. 'common.yml'
  61. )
  62. ).services
  63. self.assertEqual(
  64. service_sort(service_dicts),
  65. service_sort([
  66. {
  67. 'name': 'bar',
  68. 'image': 'busybox',
  69. 'environment': {'FOO': '1'},
  70. },
  71. {
  72. 'name': 'foo',
  73. 'image': 'busybox',
  74. }
  75. ])
  76. )
  77. def test_load_v2(self):
  78. config_data = config.load(
  79. build_config_details({
  80. 'version': '2',
  81. 'services': {
  82. 'foo': {'image': 'busybox'},
  83. 'bar': {'image': 'busybox', 'environment': ['FOO=1']},
  84. },
  85. 'volumes': {
  86. 'hello': {
  87. 'driver': 'default',
  88. 'driver_opts': {'beep': 'boop'}
  89. }
  90. },
  91. 'networks': {
  92. 'default': {
  93. 'driver': 'bridge',
  94. 'driver_opts': {'beep': 'boop'}
  95. },
  96. 'with_ipam': {
  97. 'ipam': {
  98. 'driver': 'default',
  99. 'config': [
  100. {'subnet': '172.28.0.0/16'}
  101. ]
  102. }
  103. },
  104. 'internal': {
  105. 'driver': 'bridge',
  106. 'internal': True
  107. }
  108. }
  109. }, 'working_dir', 'filename.yml')
  110. )
  111. service_dicts = config_data.services
  112. volume_dict = config_data.volumes
  113. networks_dict = config_data.networks
  114. self.assertEqual(
  115. service_sort(service_dicts),
  116. service_sort([
  117. {
  118. 'name': 'bar',
  119. 'image': 'busybox',
  120. 'environment': {'FOO': '1'},
  121. },
  122. {
  123. 'name': 'foo',
  124. 'image': 'busybox',
  125. }
  126. ])
  127. )
  128. self.assertEqual(volume_dict, {
  129. 'hello': {
  130. 'driver': 'default',
  131. 'driver_opts': {'beep': 'boop'}
  132. }
  133. })
  134. self.assertEqual(networks_dict, {
  135. 'default': {
  136. 'driver': 'bridge',
  137. 'driver_opts': {'beep': 'boop'}
  138. },
  139. 'with_ipam': {
  140. 'ipam': {
  141. 'driver': 'default',
  142. 'config': [
  143. {'subnet': '172.28.0.0/16'}
  144. ]
  145. }
  146. },
  147. 'internal': {
  148. 'driver': 'bridge',
  149. 'internal': True
  150. }
  151. })
  152. def test_valid_versions(self):
  153. for version in ['2', '2.0']:
  154. cfg = config.load(build_config_details({'version': version}))
  155. assert cfg.version == V2_0
  156. cfg = config.load(build_config_details({'version': '2.1'}))
  157. assert cfg.version == V2_1
  158. for version in ['3', '3.0']:
  159. cfg = config.load(build_config_details({'version': version}))
  160. assert cfg.version == V3_0
  161. cfg = config.load(build_config_details({'version': '3.1'}))
  162. assert cfg.version == V3_1
  163. def test_v1_file_version(self):
  164. cfg = config.load(build_config_details({'web': {'image': 'busybox'}}))
  165. assert cfg.version == V1
  166. assert list(s['name'] for s in cfg.services) == ['web']
  167. cfg = config.load(build_config_details({'version': {'image': 'busybox'}}))
  168. assert cfg.version == V1
  169. assert list(s['name'] for s in cfg.services) == ['version']
  170. def test_wrong_version_type(self):
  171. for version in [None, 1, 2, 2.0]:
  172. with pytest.raises(ConfigurationError) as excinfo:
  173. config.load(
  174. build_config_details(
  175. {'version': version},
  176. filename='filename.yml',
  177. )
  178. )
  179. assert 'Version in "filename.yml" is invalid - it should be a string.' \
  180. in excinfo.exconly()
  181. def test_unsupported_version(self):
  182. with pytest.raises(ConfigurationError) as excinfo:
  183. config.load(
  184. build_config_details(
  185. {'version': '2.18'},
  186. filename='filename.yml',
  187. )
  188. )
  189. assert 'Version in "filename.yml" is unsupported' in excinfo.exconly()
  190. assert VERSION_EXPLANATION in excinfo.exconly()
  191. def test_version_1_is_invalid(self):
  192. with pytest.raises(ConfigurationError) as excinfo:
  193. config.load(
  194. build_config_details(
  195. {
  196. 'version': '1',
  197. 'web': {'image': 'busybox'},
  198. },
  199. filename='filename.yml',
  200. )
  201. )
  202. assert 'Version in "filename.yml" is invalid' in excinfo.exconly()
  203. assert VERSION_EXPLANATION in excinfo.exconly()
  204. def test_v1_file_with_version_is_invalid(self):
  205. with pytest.raises(ConfigurationError) as excinfo:
  206. config.load(
  207. build_config_details(
  208. {
  209. 'version': '2',
  210. 'web': {'image': 'busybox'},
  211. },
  212. filename='filename.yml',
  213. )
  214. )
  215. assert 'Additional properties are not allowed' in excinfo.exconly()
  216. assert VERSION_EXPLANATION in excinfo.exconly()
  217. def test_named_volume_config_empty(self):
  218. config_details = build_config_details({
  219. 'version': '2',
  220. 'services': {
  221. 'simple': {'image': 'busybox'}
  222. },
  223. 'volumes': {
  224. 'simple': None,
  225. 'other': {},
  226. }
  227. })
  228. config_result = config.load(config_details)
  229. volumes = config_result.volumes
  230. assert 'simple' in volumes
  231. assert volumes['simple'] == {}
  232. assert volumes['other'] == {}
  233. def test_named_volume_numeric_driver_opt(self):
  234. config_details = build_config_details({
  235. 'version': '2',
  236. 'services': {
  237. 'simple': {'image': 'busybox'}
  238. },
  239. 'volumes': {
  240. 'simple': {'driver_opts': {'size': 42}},
  241. }
  242. })
  243. cfg = config.load(config_details)
  244. assert cfg.volumes['simple']['driver_opts']['size'] == '42'
  245. def test_volume_invalid_driver_opt(self):
  246. config_details = build_config_details({
  247. 'version': '2',
  248. 'services': {
  249. 'simple': {'image': 'busybox'}
  250. },
  251. 'volumes': {
  252. 'simple': {'driver_opts': {'size': True}},
  253. }
  254. })
  255. with pytest.raises(ConfigurationError) as exc:
  256. config.load(config_details)
  257. assert 'driver_opts.size contains an invalid type' in exc.exconly()
  258. def test_named_volume_invalid_type_list(self):
  259. config_details = build_config_details({
  260. 'version': '2',
  261. 'services': {
  262. 'simple': {'image': 'busybox'}
  263. },
  264. 'volumes': []
  265. })
  266. with pytest.raises(ConfigurationError) as exc:
  267. config.load(config_details)
  268. assert "volume must be a mapping, not an array" in exc.exconly()
  269. def test_networks_invalid_type_list(self):
  270. config_details = build_config_details({
  271. 'version': '2',
  272. 'services': {
  273. 'simple': {'image': 'busybox'}
  274. },
  275. 'networks': []
  276. })
  277. with pytest.raises(ConfigurationError) as exc:
  278. config.load(config_details)
  279. assert "network must be a mapping, not an array" in exc.exconly()
  280. def test_load_service_with_name_version(self):
  281. with mock.patch('compose.config.config.log') as mock_logging:
  282. config_data = config.load(
  283. build_config_details({
  284. 'version': {
  285. 'image': 'busybox'
  286. }
  287. }, 'working_dir', 'filename.yml')
  288. )
  289. assert 'Unexpected type for "version" key in "filename.yml"' \
  290. in mock_logging.warn.call_args[0][0]
  291. service_dicts = config_data.services
  292. self.assertEqual(
  293. service_sort(service_dicts),
  294. service_sort([
  295. {
  296. 'name': 'version',
  297. 'image': 'busybox',
  298. }
  299. ])
  300. )
  301. def test_load_throws_error_when_not_dict(self):
  302. with self.assertRaises(ConfigurationError):
  303. config.load(
  304. build_config_details(
  305. {'web': 'busybox:latest'},
  306. 'working_dir',
  307. 'filename.yml'
  308. )
  309. )
  310. def test_load_throws_error_when_not_dict_v2(self):
  311. with self.assertRaises(ConfigurationError):
  312. config.load(
  313. build_config_details(
  314. {'version': '2', 'services': {'web': 'busybox:latest'}},
  315. 'working_dir',
  316. 'filename.yml'
  317. )
  318. )
  319. def test_load_throws_error_with_invalid_network_fields(self):
  320. with self.assertRaises(ConfigurationError):
  321. config.load(
  322. build_config_details({
  323. 'version': '2',
  324. 'services': {'web': 'busybox:latest'},
  325. 'networks': {
  326. 'invalid': {'foo', 'bar'}
  327. }
  328. }, 'working_dir', 'filename.yml')
  329. )
  330. def test_load_config_link_local_ips_network(self):
  331. base_file = config.ConfigFile(
  332. 'base.yaml',
  333. {
  334. 'version': V2_1,
  335. 'services': {
  336. 'web': {
  337. 'image': 'example/web',
  338. 'networks': {
  339. 'foobar': {
  340. 'aliases': ['foo', 'bar'],
  341. 'link_local_ips': ['169.254.8.8']
  342. }
  343. }
  344. }
  345. },
  346. 'networks': {'foobar': {}}
  347. }
  348. )
  349. details = config.ConfigDetails('.', [base_file])
  350. web_service = config.load(details).services[0]
  351. assert web_service['networks'] == {
  352. 'foobar': {
  353. 'aliases': ['foo', 'bar'],
  354. 'link_local_ips': ['169.254.8.8']
  355. }
  356. }
  357. def test_load_config_volume_and_network_labels(self):
  358. base_file = config.ConfigFile(
  359. 'base.yaml',
  360. {
  361. 'version': '2.1',
  362. 'services': {
  363. 'web': {
  364. 'image': 'example/web',
  365. },
  366. },
  367. 'networks': {
  368. 'with_label': {
  369. 'labels': {
  370. 'label_key': 'label_val'
  371. }
  372. }
  373. },
  374. 'volumes': {
  375. 'with_label': {
  376. 'labels': {
  377. 'label_key': 'label_val'
  378. }
  379. }
  380. }
  381. }
  382. )
  383. details = config.ConfigDetails('.', [base_file])
  384. network_dict = config.load(details).networks
  385. volume_dict = config.load(details).volumes
  386. self.assertEqual(
  387. network_dict,
  388. {
  389. 'with_label': {
  390. 'labels': {
  391. 'label_key': 'label_val'
  392. }
  393. }
  394. }
  395. )
  396. self.assertEqual(
  397. volume_dict,
  398. {
  399. 'with_label': {
  400. 'labels': {
  401. 'label_key': 'label_val'
  402. }
  403. }
  404. }
  405. )
  406. def test_load_config_invalid_service_names(self):
  407. for invalid_name in ['?not?allowed', ' ', '', '!', '/', '\xe2']:
  408. with pytest.raises(ConfigurationError) as exc:
  409. config.load(build_config_details(
  410. {invalid_name: {'image': 'busybox'}}))
  411. assert 'Invalid service name \'%s\'' % invalid_name in exc.exconly()
  412. def test_load_config_invalid_service_names_v2(self):
  413. for invalid_name in ['?not?allowed', ' ', '', '!', '/', '\xe2']:
  414. with pytest.raises(ConfigurationError) as exc:
  415. config.load(build_config_details(
  416. {
  417. 'version': '2',
  418. 'services': {invalid_name: {'image': 'busybox'}},
  419. }))
  420. assert 'Invalid service name \'%s\'' % invalid_name in exc.exconly()
  421. def test_load_with_invalid_field_name(self):
  422. with pytest.raises(ConfigurationError) as exc:
  423. config.load(build_config_details(
  424. {
  425. 'version': '2',
  426. 'services': {
  427. 'web': {'image': 'busybox', 'name': 'bogus'},
  428. }
  429. },
  430. 'working_dir',
  431. 'filename.yml',
  432. ))
  433. assert "Unsupported config option for services.web: 'name'" in exc.exconly()
  434. def test_load_with_invalid_field_name_v1(self):
  435. with pytest.raises(ConfigurationError) as exc:
  436. config.load(build_config_details(
  437. {
  438. 'web': {'image': 'busybox', 'name': 'bogus'},
  439. },
  440. 'working_dir',
  441. 'filename.yml',
  442. ))
  443. assert "Unsupported config option for web: 'name'" in exc.exconly()
  444. def test_load_invalid_service_definition(self):
  445. config_details = build_config_details(
  446. {'web': 'wrong'},
  447. 'working_dir',
  448. 'filename.yml')
  449. with pytest.raises(ConfigurationError) as exc:
  450. config.load(config_details)
  451. assert "service 'web' must be a mapping not a string." in exc.exconly()
  452. def test_load_with_empty_build_args(self):
  453. config_details = build_config_details(
  454. {
  455. 'version': '2',
  456. 'services': {
  457. 'web': {
  458. 'build': {
  459. 'context': '.',
  460. 'args': None,
  461. },
  462. },
  463. },
  464. }
  465. )
  466. with pytest.raises(ConfigurationError) as exc:
  467. config.load(config_details)
  468. assert (
  469. "services.web.build.args contains an invalid type, it should be an "
  470. "object, or an array" in exc.exconly()
  471. )
  472. def test_config_integer_service_name_raise_validation_error(self):
  473. with pytest.raises(ConfigurationError) as excinfo:
  474. config.load(
  475. build_config_details(
  476. {1: {'image': 'busybox'}},
  477. 'working_dir',
  478. 'filename.yml'
  479. )
  480. )
  481. assert (
  482. "In file 'filename.yml', the service name 1 must be a quoted string, i.e. '1'" in
  483. excinfo.exconly()
  484. )
  485. def test_config_integer_service_name_raise_validation_error_v2(self):
  486. with pytest.raises(ConfigurationError) as excinfo:
  487. config.load(
  488. build_config_details(
  489. {
  490. 'version': '2',
  491. 'services': {1: {'image': 'busybox'}}
  492. },
  493. 'working_dir',
  494. 'filename.yml'
  495. )
  496. )
  497. assert (
  498. "In file 'filename.yml', the service name 1 must be a quoted string, i.e. '1'." in
  499. excinfo.exconly()
  500. )
  501. def test_config_invalid_service_name_raise_validation_error(self):
  502. with pytest.raises(ConfigurationError) as excinfo:
  503. config.load(
  504. build_config_details({
  505. 'version': '2',
  506. 'services': {
  507. 'test_app': {'build': '.'},
  508. 'mong\\o': {'image': 'mongo'},
  509. }
  510. })
  511. )
  512. assert 'Invalid service name \'mong\\o\'' in excinfo.exconly()
  513. def test_load_with_multiple_files_v1(self):
  514. base_file = config.ConfigFile(
  515. 'base.yaml',
  516. {
  517. 'web': {
  518. 'image': 'example/web',
  519. 'links': ['db'],
  520. },
  521. 'db': {
  522. 'image': 'example/db',
  523. },
  524. })
  525. override_file = config.ConfigFile(
  526. 'override.yaml',
  527. {
  528. 'web': {
  529. 'build': '/',
  530. 'volumes': ['/home/user/project:/code'],
  531. },
  532. })
  533. details = config.ConfigDetails('.', [base_file, override_file])
  534. service_dicts = config.load(details).services
  535. expected = [
  536. {
  537. 'name': 'web',
  538. 'build': {'context': os.path.abspath('/')},
  539. 'volumes': [VolumeSpec.parse('/home/user/project:/code')],
  540. 'links': ['db'],
  541. },
  542. {
  543. 'name': 'db',
  544. 'image': 'example/db',
  545. },
  546. ]
  547. assert service_sort(service_dicts) == service_sort(expected)
  548. def test_load_with_multiple_files_and_empty_override(self):
  549. base_file = config.ConfigFile(
  550. 'base.yml',
  551. {'web': {'image': 'example/web'}})
  552. override_file = config.ConfigFile('override.yml', None)
  553. details = config.ConfigDetails('.', [base_file, override_file])
  554. with pytest.raises(ConfigurationError) as exc:
  555. config.load(details)
  556. error_msg = "Top level object in 'override.yml' needs to be an object"
  557. assert error_msg in exc.exconly()
  558. def test_load_with_multiple_files_and_empty_override_v2(self):
  559. base_file = config.ConfigFile(
  560. 'base.yml',
  561. {'version': '2', 'services': {'web': {'image': 'example/web'}}})
  562. override_file = config.ConfigFile('override.yml', None)
  563. details = config.ConfigDetails('.', [base_file, override_file])
  564. with pytest.raises(ConfigurationError) as exc:
  565. config.load(details)
  566. error_msg = "Top level object in 'override.yml' needs to be an object"
  567. assert error_msg in exc.exconly()
  568. def test_load_with_multiple_files_and_empty_base(self):
  569. base_file = config.ConfigFile('base.yml', None)
  570. override_file = config.ConfigFile(
  571. 'override.yml',
  572. {'web': {'image': 'example/web'}})
  573. details = config.ConfigDetails('.', [base_file, override_file])
  574. with pytest.raises(ConfigurationError) as exc:
  575. config.load(details)
  576. assert "Top level object in 'base.yml' needs to be an object" in exc.exconly()
  577. def test_load_with_multiple_files_and_empty_base_v2(self):
  578. base_file = config.ConfigFile('base.yml', None)
  579. override_file = config.ConfigFile(
  580. 'override.tml',
  581. {'version': '2', 'services': {'web': {'image': 'example/web'}}}
  582. )
  583. details = config.ConfigDetails('.', [base_file, override_file])
  584. with pytest.raises(ConfigurationError) as exc:
  585. config.load(details)
  586. assert "Top level object in 'base.yml' needs to be an object" in exc.exconly()
  587. def test_load_with_multiple_files_and_extends_in_override_file(self):
  588. base_file = config.ConfigFile(
  589. 'base.yaml',
  590. {
  591. 'web': {'image': 'example/web'},
  592. })
  593. override_file = config.ConfigFile(
  594. 'override.yaml',
  595. {
  596. 'web': {
  597. 'extends': {
  598. 'file': 'common.yml',
  599. 'service': 'base',
  600. },
  601. 'volumes': ['/home/user/project:/code'],
  602. },
  603. })
  604. details = config.ConfigDetails('.', [base_file, override_file])
  605. tmpdir = py.test.ensuretemp('config_test')
  606. self.addCleanup(tmpdir.remove)
  607. tmpdir.join('common.yml').write("""
  608. base:
  609. labels: ['label=one']
  610. """)
  611. with tmpdir.as_cwd():
  612. service_dicts = config.load(details).services
  613. expected = [
  614. {
  615. 'name': 'web',
  616. 'image': 'example/web',
  617. 'volumes': [VolumeSpec.parse('/home/user/project:/code')],
  618. 'labels': {'label': 'one'},
  619. },
  620. ]
  621. self.assertEqual(service_sort(service_dicts), service_sort(expected))
  622. def test_load_with_multiple_files_and_invalid_override(self):
  623. base_file = config.ConfigFile(
  624. 'base.yaml',
  625. {'web': {'image': 'example/web'}})
  626. override_file = config.ConfigFile(
  627. 'override.yaml',
  628. {'bogus': 'thing'})
  629. details = config.ConfigDetails('.', [base_file, override_file])
  630. with pytest.raises(ConfigurationError) as exc:
  631. config.load(details)
  632. assert "service 'bogus' must be a mapping not a string." in exc.exconly()
  633. assert "In file 'override.yaml'" in exc.exconly()
  634. def test_load_sorts_in_dependency_order(self):
  635. config_details = build_config_details({
  636. 'web': {
  637. 'image': 'busybox:latest',
  638. 'links': ['db'],
  639. },
  640. 'db': {
  641. 'image': 'busybox:latest',
  642. 'volumes_from': ['volume:ro']
  643. },
  644. 'volume': {
  645. 'image': 'busybox:latest',
  646. 'volumes': ['/tmp'],
  647. }
  648. })
  649. services = config.load(config_details).services
  650. assert services[0]['name'] == 'volume'
  651. assert services[1]['name'] == 'db'
  652. assert services[2]['name'] == 'web'
  653. def test_config_build_configuration(self):
  654. service = config.load(
  655. build_config_details(
  656. {'web': {
  657. 'build': '.',
  658. 'dockerfile': 'Dockerfile-alt'
  659. }},
  660. 'tests/fixtures/extends',
  661. 'filename.yml'
  662. )
  663. ).services
  664. self.assertTrue('context' in service[0]['build'])
  665. self.assertEqual(service[0]['build']['dockerfile'], 'Dockerfile-alt')
  666. def test_config_build_configuration_v2(self):
  667. # service.dockerfile is invalid in v2
  668. with self.assertRaises(ConfigurationError):
  669. config.load(
  670. build_config_details(
  671. {
  672. 'version': '2',
  673. 'services': {
  674. 'web': {
  675. 'build': '.',
  676. 'dockerfile': 'Dockerfile-alt'
  677. }
  678. }
  679. },
  680. 'tests/fixtures/extends',
  681. 'filename.yml'
  682. )
  683. )
  684. service = config.load(
  685. build_config_details({
  686. 'version': '2',
  687. 'services': {
  688. 'web': {
  689. 'build': '.'
  690. }
  691. }
  692. }, 'tests/fixtures/extends', 'filename.yml')
  693. ).services[0]
  694. self.assertTrue('context' in service['build'])
  695. service = config.load(
  696. build_config_details(
  697. {
  698. 'version': '2',
  699. 'services': {
  700. 'web': {
  701. 'build': {
  702. 'context': '.',
  703. 'dockerfile': 'Dockerfile-alt'
  704. }
  705. }
  706. }
  707. },
  708. 'tests/fixtures/extends',
  709. 'filename.yml'
  710. )
  711. ).services
  712. self.assertTrue('context' in service[0]['build'])
  713. self.assertEqual(service[0]['build']['dockerfile'], 'Dockerfile-alt')
  714. def test_load_with_buildargs(self):
  715. service = config.load(
  716. build_config_details(
  717. {
  718. 'version': '2',
  719. 'services': {
  720. 'web': {
  721. 'build': {
  722. 'context': '.',
  723. 'dockerfile': 'Dockerfile-alt',
  724. 'args': {
  725. 'opt1': 42,
  726. 'opt2': 'foobar'
  727. }
  728. }
  729. }
  730. }
  731. },
  732. 'tests/fixtures/extends',
  733. 'filename.yml'
  734. )
  735. ).services[0]
  736. assert 'args' in service['build']
  737. assert 'opt1' in service['build']['args']
  738. assert isinstance(service['build']['args']['opt1'], str)
  739. assert service['build']['args']['opt1'] == '42'
  740. assert service['build']['args']['opt2'] == 'foobar'
  741. def test_build_args_allow_empty_properties(self):
  742. service = config.load(
  743. build_config_details(
  744. {
  745. 'version': '2',
  746. 'services': {
  747. 'web': {
  748. 'build': {
  749. 'context': '.',
  750. 'dockerfile': 'Dockerfile-alt',
  751. 'args': {
  752. 'foo': None
  753. }
  754. }
  755. }
  756. }
  757. },
  758. 'tests/fixtures/extends',
  759. 'filename.yml'
  760. )
  761. ).services[0]
  762. assert 'args' in service['build']
  763. assert 'foo' in service['build']['args']
  764. assert service['build']['args']['foo'] == ''
  765. # If build argument is None then it will be converted to the empty
  766. # string. Make sure that int zero kept as it is, i.e. not converted to
  767. # the empty string
  768. def test_build_args_check_zero_preserved(self):
  769. service = config.load(
  770. build_config_details(
  771. {
  772. 'version': '2',
  773. 'services': {
  774. 'web': {
  775. 'build': {
  776. 'context': '.',
  777. 'dockerfile': 'Dockerfile-alt',
  778. 'args': {
  779. 'foo': 0
  780. }
  781. }
  782. }
  783. }
  784. },
  785. 'tests/fixtures/extends',
  786. 'filename.yml'
  787. )
  788. ).services[0]
  789. assert 'args' in service['build']
  790. assert 'foo' in service['build']['args']
  791. assert service['build']['args']['foo'] == '0'
  792. def test_load_with_multiple_files_mismatched_networks_format(self):
  793. base_file = config.ConfigFile(
  794. 'base.yaml',
  795. {
  796. 'version': '2',
  797. 'services': {
  798. 'web': {
  799. 'image': 'example/web',
  800. 'networks': {
  801. 'foobar': {'aliases': ['foo', 'bar']}
  802. }
  803. }
  804. },
  805. 'networks': {'foobar': {}, 'baz': {}}
  806. }
  807. )
  808. override_file = config.ConfigFile(
  809. 'override.yaml',
  810. {
  811. 'version': '2',
  812. 'services': {
  813. 'web': {
  814. 'networks': ['baz']
  815. }
  816. }
  817. }
  818. )
  819. details = config.ConfigDetails('.', [base_file, override_file])
  820. web_service = config.load(details).services[0]
  821. assert web_service['networks'] == {
  822. 'foobar': {'aliases': ['foo', 'bar']},
  823. 'baz': None
  824. }
  825. def test_load_with_multiple_files_v2(self):
  826. base_file = config.ConfigFile(
  827. 'base.yaml',
  828. {
  829. 'version': '2',
  830. 'services': {
  831. 'web': {
  832. 'image': 'example/web',
  833. 'depends_on': ['db'],
  834. },
  835. 'db': {
  836. 'image': 'example/db',
  837. }
  838. },
  839. })
  840. override_file = config.ConfigFile(
  841. 'override.yaml',
  842. {
  843. 'version': '2',
  844. 'services': {
  845. 'web': {
  846. 'build': '/',
  847. 'volumes': ['/home/user/project:/code'],
  848. 'depends_on': ['other'],
  849. },
  850. 'other': {
  851. 'image': 'example/other',
  852. }
  853. }
  854. })
  855. details = config.ConfigDetails('.', [base_file, override_file])
  856. service_dicts = config.load(details).services
  857. expected = [
  858. {
  859. 'name': 'web',
  860. 'build': {'context': os.path.abspath('/')},
  861. 'image': 'example/web',
  862. 'volumes': [VolumeSpec.parse('/home/user/project:/code')],
  863. 'depends_on': {
  864. 'db': {'condition': 'service_started'},
  865. 'other': {'condition': 'service_started'},
  866. },
  867. },
  868. {
  869. 'name': 'db',
  870. 'image': 'example/db',
  871. },
  872. {
  873. 'name': 'other',
  874. 'image': 'example/other',
  875. },
  876. ]
  877. assert service_sort(service_dicts) == service_sort(expected)
  878. def test_undeclared_volume_v2(self):
  879. base_file = config.ConfigFile(
  880. 'base.yaml',
  881. {
  882. 'version': '2',
  883. 'services': {
  884. 'web': {
  885. 'image': 'busybox:latest',
  886. 'volumes': ['data0028:/data:ro'],
  887. },
  888. },
  889. }
  890. )
  891. details = config.ConfigDetails('.', [base_file])
  892. with self.assertRaises(ConfigurationError):
  893. config.load(details)
  894. base_file = config.ConfigFile(
  895. 'base.yaml',
  896. {
  897. 'version': '2',
  898. 'services': {
  899. 'web': {
  900. 'image': 'busybox:latest',
  901. 'volumes': ['./data0028:/data:ro'],
  902. },
  903. },
  904. }
  905. )
  906. details = config.ConfigDetails('.', [base_file])
  907. config_data = config.load(details)
  908. volume = config_data.services[0].get('volumes')[0]
  909. assert not volume.is_named_volume
  910. def test_undeclared_volume_v1(self):
  911. base_file = config.ConfigFile(
  912. 'base.yaml',
  913. {
  914. 'web': {
  915. 'image': 'busybox:latest',
  916. 'volumes': ['data0028:/data:ro'],
  917. },
  918. }
  919. )
  920. details = config.ConfigDetails('.', [base_file])
  921. config_data = config.load(details)
  922. volume = config_data.services[0].get('volumes')[0]
  923. assert volume.external == 'data0028'
  924. assert volume.is_named_volume
  925. def test_config_valid_service_names(self):
  926. for valid_name in ['_', '-', '.__.', '_what-up.', 'what_.up----', 'whatup']:
  927. services = config.load(
  928. build_config_details(
  929. {valid_name: {'image': 'busybox'}},
  930. 'tests/fixtures/extends',
  931. 'common.yml')).services
  932. assert services[0]['name'] == valid_name
  933. def test_config_hint(self):
  934. with pytest.raises(ConfigurationError) as excinfo:
  935. config.load(
  936. build_config_details(
  937. {
  938. 'foo': {'image': 'busybox', 'privilige': 'something'},
  939. },
  940. 'tests/fixtures/extends',
  941. 'filename.yml'
  942. )
  943. )
  944. assert "(did you mean 'privileged'?)" in excinfo.exconly()
  945. def test_load_errors_on_uppercase_with_no_image(self):
  946. with pytest.raises(ConfigurationError) as exc:
  947. config.load(build_config_details({
  948. 'Foo': {'build': '.'},
  949. }, 'tests/fixtures/build-ctx'))
  950. assert "Service 'Foo' contains uppercase characters" in exc.exconly()
  951. def test_invalid_config_v1(self):
  952. with pytest.raises(ConfigurationError) as excinfo:
  953. config.load(
  954. build_config_details(
  955. {
  956. 'foo': {'image': 1},
  957. },
  958. 'tests/fixtures/extends',
  959. 'filename.yml'
  960. )
  961. )
  962. assert "foo.image contains an invalid type, it should be a string" \
  963. in excinfo.exconly()
  964. def test_invalid_config_v2(self):
  965. with pytest.raises(ConfigurationError) as excinfo:
  966. config.load(
  967. build_config_details(
  968. {
  969. 'version': '2',
  970. 'services': {
  971. 'foo': {'image': 1},
  972. },
  973. },
  974. 'tests/fixtures/extends',
  975. 'filename.yml'
  976. )
  977. )
  978. assert "services.foo.image contains an invalid type, it should be a string" \
  979. in excinfo.exconly()
  980. def test_invalid_config_build_and_image_specified_v1(self):
  981. with pytest.raises(ConfigurationError) as excinfo:
  982. config.load(
  983. build_config_details(
  984. {
  985. 'foo': {'image': 'busybox', 'build': '.'},
  986. },
  987. 'tests/fixtures/extends',
  988. 'filename.yml'
  989. )
  990. )
  991. assert "foo has both an image and build path specified." in excinfo.exconly()
  992. def test_invalid_config_type_should_be_an_array(self):
  993. with pytest.raises(ConfigurationError) as excinfo:
  994. config.load(
  995. build_config_details(
  996. {
  997. 'foo': {'image': 'busybox', 'links': 'an_link'},
  998. },
  999. 'tests/fixtures/extends',
  1000. 'filename.yml'
  1001. )
  1002. )
  1003. assert "foo.links contains an invalid type, it should be an array" \
  1004. in excinfo.exconly()
  1005. def test_invalid_config_not_a_dictionary(self):
  1006. with pytest.raises(ConfigurationError) as excinfo:
  1007. config.load(
  1008. build_config_details(
  1009. ['foo', 'lol'],
  1010. 'tests/fixtures/extends',
  1011. 'filename.yml'
  1012. )
  1013. )
  1014. assert "Top level object in 'filename.yml' needs to be an object" \
  1015. in excinfo.exconly()
  1016. def test_invalid_config_not_unique_items(self):
  1017. with pytest.raises(ConfigurationError) as excinfo:
  1018. config.load(
  1019. build_config_details(
  1020. {
  1021. 'web': {'build': '.', 'devices': ['/dev/foo:/dev/foo', '/dev/foo:/dev/foo']}
  1022. },
  1023. 'tests/fixtures/extends',
  1024. 'filename.yml'
  1025. )
  1026. )
  1027. assert "has non-unique elements" in excinfo.exconly()
  1028. def test_invalid_list_of_strings_format(self):
  1029. with pytest.raises(ConfigurationError) as excinfo:
  1030. config.load(
  1031. build_config_details(
  1032. {
  1033. 'web': {'build': '.', 'command': [1]}
  1034. },
  1035. 'tests/fixtures/extends',
  1036. 'filename.yml'
  1037. )
  1038. )
  1039. assert "web.command contains 1, which is an invalid type, it should be a string" \
  1040. in excinfo.exconly()
  1041. def test_load_config_dockerfile_without_build_raises_error_v1(self):
  1042. with pytest.raises(ConfigurationError) as exc:
  1043. config.load(build_config_details({
  1044. 'web': {
  1045. 'image': 'busybox',
  1046. 'dockerfile': 'Dockerfile.alt'
  1047. }
  1048. }))
  1049. assert "web has both an image and alternate Dockerfile." in exc.exconly()
  1050. def test_config_extra_hosts_string_raises_validation_error(self):
  1051. with pytest.raises(ConfigurationError) as excinfo:
  1052. config.load(
  1053. build_config_details(
  1054. {'web': {
  1055. 'image': 'busybox',
  1056. 'extra_hosts': 'somehost:162.242.195.82'
  1057. }},
  1058. 'working_dir',
  1059. 'filename.yml'
  1060. )
  1061. )
  1062. assert "web.extra_hosts contains an invalid type" \
  1063. in excinfo.exconly()
  1064. def test_config_extra_hosts_list_of_dicts_validation_error(self):
  1065. with pytest.raises(ConfigurationError) as excinfo:
  1066. config.load(
  1067. build_config_details(
  1068. {'web': {
  1069. 'image': 'busybox',
  1070. 'extra_hosts': [
  1071. {'somehost': '162.242.195.82'},
  1072. {'otherhost': '50.31.209.229'}
  1073. ]
  1074. }},
  1075. 'working_dir',
  1076. 'filename.yml'
  1077. )
  1078. )
  1079. assert "web.extra_hosts contains {\"somehost\": \"162.242.195.82\"}, " \
  1080. "which is an invalid type, it should be a string" \
  1081. in excinfo.exconly()
  1082. def test_config_ulimits_invalid_keys_validation_error(self):
  1083. with pytest.raises(ConfigurationError) as exc:
  1084. config.load(build_config_details(
  1085. {
  1086. 'web': {
  1087. 'image': 'busybox',
  1088. 'ulimits': {
  1089. 'nofile': {
  1090. "not_soft_or_hard": 100,
  1091. "soft": 10000,
  1092. "hard": 20000,
  1093. }
  1094. }
  1095. }
  1096. },
  1097. 'working_dir',
  1098. 'filename.yml'))
  1099. assert "web.ulimits.nofile contains unsupported option: 'not_soft_or_hard'" \
  1100. in exc.exconly()
  1101. def test_config_ulimits_required_keys_validation_error(self):
  1102. with pytest.raises(ConfigurationError) as exc:
  1103. config.load(build_config_details(
  1104. {
  1105. 'web': {
  1106. 'image': 'busybox',
  1107. 'ulimits': {'nofile': {"soft": 10000}}
  1108. }
  1109. },
  1110. 'working_dir',
  1111. 'filename.yml'))
  1112. assert "web.ulimits.nofile" in exc.exconly()
  1113. assert "'hard' is a required property" in exc.exconly()
  1114. def test_config_ulimits_soft_greater_than_hard_error(self):
  1115. expected = "'soft' value can not be greater than 'hard' value"
  1116. with pytest.raises(ConfigurationError) as exc:
  1117. config.load(build_config_details(
  1118. {
  1119. 'web': {
  1120. 'image': 'busybox',
  1121. 'ulimits': {
  1122. 'nofile': {"soft": 10000, "hard": 1000}
  1123. }
  1124. }
  1125. },
  1126. 'working_dir',
  1127. 'filename.yml'))
  1128. assert expected in exc.exconly()
  1129. def test_valid_config_which_allows_two_type_definitions(self):
  1130. expose_values = [["8000"], [8000]]
  1131. for expose in expose_values:
  1132. service = config.load(
  1133. build_config_details(
  1134. {'web': {
  1135. 'image': 'busybox',
  1136. 'expose': expose
  1137. }},
  1138. 'working_dir',
  1139. 'filename.yml'
  1140. )
  1141. ).services
  1142. self.assertEqual(service[0]['expose'], expose)
  1143. def test_valid_config_oneof_string_or_list(self):
  1144. entrypoint_values = [["sh"], "sh"]
  1145. for entrypoint in entrypoint_values:
  1146. service = config.load(
  1147. build_config_details(
  1148. {'web': {
  1149. 'image': 'busybox',
  1150. 'entrypoint': entrypoint
  1151. }},
  1152. 'working_dir',
  1153. 'filename.yml'
  1154. )
  1155. ).services
  1156. self.assertEqual(service[0]['entrypoint'], entrypoint)
  1157. def test_logs_warning_for_boolean_in_environment(self):
  1158. config_details = build_config_details({
  1159. 'web': {
  1160. 'image': 'busybox',
  1161. 'environment': {'SHOW_STUFF': True}
  1162. }
  1163. })
  1164. with pytest.raises(ConfigurationError) as exc:
  1165. config.load(config_details)
  1166. assert "contains true, which is an invalid type" in exc.exconly()
  1167. def test_config_valid_environment_dict_key_contains_dashes(self):
  1168. services = config.load(
  1169. build_config_details(
  1170. {'web': {
  1171. 'image': 'busybox',
  1172. 'environment': {'SPRING_JPA_HIBERNATE_DDL-AUTO': 'none'}
  1173. }},
  1174. 'working_dir',
  1175. 'filename.yml'
  1176. )
  1177. ).services
  1178. self.assertEqual(services[0]['environment']['SPRING_JPA_HIBERNATE_DDL-AUTO'], 'none')
  1179. def test_load_yaml_with_yaml_error(self):
  1180. tmpdir = py.test.ensuretemp('invalid_yaml_test')
  1181. self.addCleanup(tmpdir.remove)
  1182. invalid_yaml_file = tmpdir.join('docker-compose.yml')
  1183. invalid_yaml_file.write("""
  1184. web:
  1185. this is bogus: ok: what
  1186. """)
  1187. with pytest.raises(ConfigurationError) as exc:
  1188. config.load_yaml(str(invalid_yaml_file))
  1189. assert 'line 3, column 32' in exc.exconly()
  1190. def test_validate_extra_hosts_invalid(self):
  1191. with pytest.raises(ConfigurationError) as exc:
  1192. config.load(build_config_details({
  1193. 'web': {
  1194. 'image': 'alpine',
  1195. 'extra_hosts': "www.example.com: 192.168.0.17",
  1196. }
  1197. }))
  1198. assert "web.extra_hosts contains an invalid type" in exc.exconly()
  1199. def test_validate_extra_hosts_invalid_list(self):
  1200. with pytest.raises(ConfigurationError) as exc:
  1201. config.load(build_config_details({
  1202. 'web': {
  1203. 'image': 'alpine',
  1204. 'extra_hosts': [
  1205. {'www.example.com': '192.168.0.17'},
  1206. {'api.example.com': '192.168.0.18'}
  1207. ],
  1208. }
  1209. }))
  1210. assert "which is an invalid type" in exc.exconly()
  1211. def test_normalize_dns_options(self):
  1212. actual = config.load(build_config_details({
  1213. 'web': {
  1214. 'image': 'alpine',
  1215. 'dns': '8.8.8.8',
  1216. 'dns_search': 'domain.local',
  1217. }
  1218. }))
  1219. assert actual.services == [
  1220. {
  1221. 'name': 'web',
  1222. 'image': 'alpine',
  1223. 'dns': ['8.8.8.8'],
  1224. 'dns_search': ['domain.local'],
  1225. }
  1226. ]
  1227. def test_tmpfs_option(self):
  1228. actual = config.load(build_config_details({
  1229. 'version': '2',
  1230. 'services': {
  1231. 'web': {
  1232. 'image': 'alpine',
  1233. 'tmpfs': '/run',
  1234. }
  1235. }
  1236. }))
  1237. assert actual.services == [
  1238. {
  1239. 'name': 'web',
  1240. 'image': 'alpine',
  1241. 'tmpfs': ['/run'],
  1242. }
  1243. ]
  1244. def test_oom_score_adj_option(self):
  1245. actual = config.load(build_config_details({
  1246. 'version': '2',
  1247. 'services': {
  1248. 'web': {
  1249. 'image': 'alpine',
  1250. 'oom_score_adj': 500
  1251. }
  1252. }
  1253. }))
  1254. assert actual.services == [
  1255. {
  1256. 'name': 'web',
  1257. 'image': 'alpine',
  1258. 'oom_score_adj': 500
  1259. }
  1260. ]
  1261. def test_swappiness_option(self):
  1262. actual = config.load(build_config_details({
  1263. 'version': '2',
  1264. 'services': {
  1265. 'web': {
  1266. 'image': 'alpine',
  1267. 'mem_swappiness': 10,
  1268. }
  1269. }
  1270. }))
  1271. assert actual.services == [
  1272. {
  1273. 'name': 'web',
  1274. 'image': 'alpine',
  1275. 'mem_swappiness': 10,
  1276. }
  1277. ]
  1278. def test_group_add_option(self):
  1279. actual = config.load(build_config_details({
  1280. 'version': '2',
  1281. 'services': {
  1282. 'web': {
  1283. 'image': 'alpine',
  1284. 'group_add': ["docker", 777]
  1285. }
  1286. }
  1287. }))
  1288. assert actual.services == [
  1289. {
  1290. 'name': 'web',
  1291. 'image': 'alpine',
  1292. 'group_add': ["docker", 777]
  1293. }
  1294. ]
  1295. def test_dns_opt_option(self):
  1296. actual = config.load(build_config_details({
  1297. 'version': '2',
  1298. 'services': {
  1299. 'web': {
  1300. 'image': 'alpine',
  1301. 'dns_opt': ["use-vc", "no-tld-query"]
  1302. }
  1303. }
  1304. }))
  1305. assert actual.services == [
  1306. {
  1307. 'name': 'web',
  1308. 'image': 'alpine',
  1309. 'dns_opt': ["use-vc", "no-tld-query"]
  1310. }
  1311. ]
  1312. def test_isolation_option(self):
  1313. actual = config.load(build_config_details({
  1314. 'version': V2_1,
  1315. 'services': {
  1316. 'web': {
  1317. 'image': 'win10',
  1318. 'isolation': 'hyperv'
  1319. }
  1320. }
  1321. }))
  1322. assert actual.services == [
  1323. {
  1324. 'name': 'web',
  1325. 'image': 'win10',
  1326. 'isolation': 'hyperv',
  1327. }
  1328. ]
  1329. def test_merge_service_dicts_from_files_with_extends_in_base(self):
  1330. base = {
  1331. 'volumes': ['.:/app'],
  1332. 'extends': {'service': 'app'}
  1333. }
  1334. override = {
  1335. 'image': 'alpine:edge',
  1336. }
  1337. actual = config.merge_service_dicts_from_files(
  1338. base,
  1339. override,
  1340. DEFAULT_VERSION)
  1341. assert actual == {
  1342. 'image': 'alpine:edge',
  1343. 'volumes': ['.:/app'],
  1344. 'extends': {'service': 'app'}
  1345. }
  1346. def test_merge_service_dicts_from_files_with_extends_in_override(self):
  1347. base = {
  1348. 'volumes': ['.:/app'],
  1349. 'extends': {'service': 'app'}
  1350. }
  1351. override = {
  1352. 'image': 'alpine:edge',
  1353. 'extends': {'service': 'foo'}
  1354. }
  1355. actual = config.merge_service_dicts_from_files(
  1356. base,
  1357. override,
  1358. DEFAULT_VERSION)
  1359. assert actual == {
  1360. 'image': 'alpine:edge',
  1361. 'volumes': ['.:/app'],
  1362. 'extends': {'service': 'foo'}
  1363. }
  1364. def test_merge_service_dicts_heterogeneous(self):
  1365. base = {
  1366. 'volumes': ['.:/app'],
  1367. 'ports': ['5432']
  1368. }
  1369. override = {
  1370. 'image': 'alpine:edge',
  1371. 'ports': [5432]
  1372. }
  1373. actual = config.merge_service_dicts_from_files(
  1374. base,
  1375. override,
  1376. DEFAULT_VERSION)
  1377. assert actual == {
  1378. 'image': 'alpine:edge',
  1379. 'volumes': ['.:/app'],
  1380. 'ports': ['5432']
  1381. }
  1382. def test_merge_service_dicts_heterogeneous_2(self):
  1383. base = {
  1384. 'volumes': ['.:/app'],
  1385. 'ports': [5432]
  1386. }
  1387. override = {
  1388. 'image': 'alpine:edge',
  1389. 'ports': ['5432']
  1390. }
  1391. actual = config.merge_service_dicts_from_files(
  1392. base,
  1393. override,
  1394. DEFAULT_VERSION)
  1395. assert actual == {
  1396. 'image': 'alpine:edge',
  1397. 'volumes': ['.:/app'],
  1398. 'ports': ['5432']
  1399. }
  1400. def test_merge_build_args(self):
  1401. base = {
  1402. 'build': {
  1403. 'context': '.',
  1404. 'args': {
  1405. 'ONE': '1',
  1406. 'TWO': '2',
  1407. },
  1408. }
  1409. }
  1410. override = {
  1411. 'build': {
  1412. 'args': {
  1413. 'TWO': 'dos',
  1414. 'THREE': '3',
  1415. },
  1416. }
  1417. }
  1418. actual = config.merge_service_dicts(
  1419. base,
  1420. override,
  1421. DEFAULT_VERSION)
  1422. assert actual == {
  1423. 'build': {
  1424. 'context': '.',
  1425. 'args': {
  1426. 'ONE': '1',
  1427. 'TWO': 'dos',
  1428. 'THREE': '3',
  1429. },
  1430. }
  1431. }
  1432. def test_merge_logging_v1(self):
  1433. base = {
  1434. 'image': 'alpine:edge',
  1435. 'log_driver': 'something',
  1436. 'log_opt': {'foo': 'three'},
  1437. }
  1438. override = {
  1439. 'image': 'alpine:edge',
  1440. 'command': 'true',
  1441. }
  1442. actual = config.merge_service_dicts(base, override, V1)
  1443. assert actual == {
  1444. 'image': 'alpine:edge',
  1445. 'log_driver': 'something',
  1446. 'log_opt': {'foo': 'three'},
  1447. 'command': 'true',
  1448. }
  1449. def test_merge_logging_v2(self):
  1450. base = {
  1451. 'image': 'alpine:edge',
  1452. 'logging': {
  1453. 'driver': 'json-file',
  1454. 'options': {
  1455. 'frequency': '2000',
  1456. 'timeout': '23'
  1457. }
  1458. }
  1459. }
  1460. override = {
  1461. 'logging': {
  1462. 'options': {
  1463. 'timeout': '360',
  1464. 'pretty-print': 'on'
  1465. }
  1466. }
  1467. }
  1468. actual = config.merge_service_dicts(base, override, V2_0)
  1469. assert actual == {
  1470. 'image': 'alpine:edge',
  1471. 'logging': {
  1472. 'driver': 'json-file',
  1473. 'options': {
  1474. 'frequency': '2000',
  1475. 'timeout': '360',
  1476. 'pretty-print': 'on'
  1477. }
  1478. }
  1479. }
  1480. def test_merge_logging_v2_override_driver(self):
  1481. base = {
  1482. 'image': 'alpine:edge',
  1483. 'logging': {
  1484. 'driver': 'json-file',
  1485. 'options': {
  1486. 'frequency': '2000',
  1487. 'timeout': '23'
  1488. }
  1489. }
  1490. }
  1491. override = {
  1492. 'logging': {
  1493. 'driver': 'syslog',
  1494. 'options': {
  1495. 'timeout': '360',
  1496. 'pretty-print': 'on'
  1497. }
  1498. }
  1499. }
  1500. actual = config.merge_service_dicts(base, override, V2_0)
  1501. assert actual == {
  1502. 'image': 'alpine:edge',
  1503. 'logging': {
  1504. 'driver': 'syslog',
  1505. 'options': {
  1506. 'timeout': '360',
  1507. 'pretty-print': 'on'
  1508. }
  1509. }
  1510. }
  1511. def test_merge_logging_v2_no_base_driver(self):
  1512. base = {
  1513. 'image': 'alpine:edge',
  1514. 'logging': {
  1515. 'options': {
  1516. 'frequency': '2000',
  1517. 'timeout': '23'
  1518. }
  1519. }
  1520. }
  1521. override = {
  1522. 'logging': {
  1523. 'driver': 'json-file',
  1524. 'options': {
  1525. 'timeout': '360',
  1526. 'pretty-print': 'on'
  1527. }
  1528. }
  1529. }
  1530. actual = config.merge_service_dicts(base, override, V2_0)
  1531. assert actual == {
  1532. 'image': 'alpine:edge',
  1533. 'logging': {
  1534. 'driver': 'json-file',
  1535. 'options': {
  1536. 'frequency': '2000',
  1537. 'timeout': '360',
  1538. 'pretty-print': 'on'
  1539. }
  1540. }
  1541. }
  1542. def test_merge_logging_v2_no_drivers(self):
  1543. base = {
  1544. 'image': 'alpine:edge',
  1545. 'logging': {
  1546. 'options': {
  1547. 'frequency': '2000',
  1548. 'timeout': '23'
  1549. }
  1550. }
  1551. }
  1552. override = {
  1553. 'logging': {
  1554. 'options': {
  1555. 'timeout': '360',
  1556. 'pretty-print': 'on'
  1557. }
  1558. }
  1559. }
  1560. actual = config.merge_service_dicts(base, override, V2_0)
  1561. assert actual == {
  1562. 'image': 'alpine:edge',
  1563. 'logging': {
  1564. 'options': {
  1565. 'frequency': '2000',
  1566. 'timeout': '360',
  1567. 'pretty-print': 'on'
  1568. }
  1569. }
  1570. }
  1571. def test_merge_logging_v2_no_override_options(self):
  1572. base = {
  1573. 'image': 'alpine:edge',
  1574. 'logging': {
  1575. 'driver': 'json-file',
  1576. 'options': {
  1577. 'frequency': '2000',
  1578. 'timeout': '23'
  1579. }
  1580. }
  1581. }
  1582. override = {
  1583. 'logging': {
  1584. 'driver': 'syslog'
  1585. }
  1586. }
  1587. actual = config.merge_service_dicts(base, override, V2_0)
  1588. assert actual == {
  1589. 'image': 'alpine:edge',
  1590. 'logging': {
  1591. 'driver': 'syslog',
  1592. 'options': None
  1593. }
  1594. }
  1595. def test_merge_logging_v2_no_base(self):
  1596. base = {
  1597. 'image': 'alpine:edge'
  1598. }
  1599. override = {
  1600. 'logging': {
  1601. 'driver': 'json-file',
  1602. 'options': {
  1603. 'frequency': '2000'
  1604. }
  1605. }
  1606. }
  1607. actual = config.merge_service_dicts(base, override, V2_0)
  1608. assert actual == {
  1609. 'image': 'alpine:edge',
  1610. 'logging': {
  1611. 'driver': 'json-file',
  1612. 'options': {
  1613. 'frequency': '2000'
  1614. }
  1615. }
  1616. }
  1617. def test_merge_logging_v2_no_override(self):
  1618. base = {
  1619. 'image': 'alpine:edge',
  1620. 'logging': {
  1621. 'driver': 'syslog',
  1622. 'options': {
  1623. 'frequency': '2000'
  1624. }
  1625. }
  1626. }
  1627. override = {}
  1628. actual = config.merge_service_dicts(base, override, V2_0)
  1629. assert actual == {
  1630. 'image': 'alpine:edge',
  1631. 'logging': {
  1632. 'driver': 'syslog',
  1633. 'options': {
  1634. 'frequency': '2000'
  1635. }
  1636. }
  1637. }
  1638. def test_merge_mixed_ports(self):
  1639. base = {
  1640. 'image': 'busybox:latest',
  1641. 'command': 'top',
  1642. 'ports': [
  1643. {
  1644. 'target': '1245',
  1645. 'published': '1245',
  1646. 'protocol': 'tcp',
  1647. }
  1648. ]
  1649. }
  1650. override = {
  1651. 'ports': ['1245:1245/udp']
  1652. }
  1653. actual = config.merge_service_dicts(base, override, V3_1)
  1654. assert actual == {
  1655. 'image': 'busybox:latest',
  1656. 'command': 'top',
  1657. 'ports': [types.ServicePort('1245', '1245', 'udp', None, None)]
  1658. }
  1659. def test_merge_depends_on_no_override(self):
  1660. base = {
  1661. 'image': 'busybox',
  1662. 'depends_on': {
  1663. 'app1': {'condition': 'service_started'},
  1664. 'app2': {'condition': 'service_healthy'}
  1665. }
  1666. }
  1667. override = {}
  1668. actual = config.merge_service_dicts(base, override, V2_1)
  1669. assert actual == base
  1670. def test_merge_depends_on_mixed_syntax(self):
  1671. base = {
  1672. 'image': 'busybox',
  1673. 'depends_on': {
  1674. 'app1': {'condition': 'service_started'},
  1675. 'app2': {'condition': 'service_healthy'}
  1676. }
  1677. }
  1678. override = {
  1679. 'depends_on': ['app3']
  1680. }
  1681. actual = config.merge_service_dicts(base, override, V2_1)
  1682. assert actual == {
  1683. 'image': 'busybox',
  1684. 'depends_on': {
  1685. 'app1': {'condition': 'service_started'},
  1686. 'app2': {'condition': 'service_healthy'},
  1687. 'app3': {'condition': 'service_started'}
  1688. }
  1689. }
  1690. def test_merge_pid(self):
  1691. # Regression: https://github.com/docker/compose/issues/4184
  1692. base = {
  1693. 'image': 'busybox',
  1694. 'pid': 'host'
  1695. }
  1696. override = {
  1697. 'labels': {'com.docker.compose.test': 'yes'}
  1698. }
  1699. actual = config.merge_service_dicts(base, override, V2_0)
  1700. assert actual == {
  1701. 'image': 'busybox',
  1702. 'pid': 'host',
  1703. 'labels': {'com.docker.compose.test': 'yes'}
  1704. }
  1705. def test_merge_different_secrets(self):
  1706. base = {
  1707. 'image': 'busybox',
  1708. 'secrets': [
  1709. {'source': 'src.txt'}
  1710. ]
  1711. }
  1712. override = {'secrets': ['other-src.txt']}
  1713. actual = config.merge_service_dicts(base, override, V3_1)
  1714. assert secret_sort(actual['secrets']) == secret_sort([
  1715. {'source': 'src.txt'},
  1716. {'source': 'other-src.txt'}
  1717. ])
  1718. def test_merge_secrets_override(self):
  1719. base = {
  1720. 'image': 'busybox',
  1721. 'secrets': ['src.txt'],
  1722. }
  1723. override = {
  1724. 'secrets': [
  1725. {
  1726. 'source': 'src.txt',
  1727. 'target': 'data.txt',
  1728. 'mode': 0o400
  1729. }
  1730. ]
  1731. }
  1732. actual = config.merge_service_dicts(base, override, V3_1)
  1733. assert actual['secrets'] == override['secrets']
  1734. def test_external_volume_config(self):
  1735. config_details = build_config_details({
  1736. 'version': '2',
  1737. 'services': {
  1738. 'bogus': {'image': 'busybox'}
  1739. },
  1740. 'volumes': {
  1741. 'ext': {'external': True},
  1742. 'ext2': {'external': {'name': 'aliased'}}
  1743. }
  1744. })
  1745. config_result = config.load(config_details)
  1746. volumes = config_result.volumes
  1747. assert 'ext' in volumes
  1748. assert volumes['ext']['external'] is True
  1749. assert 'ext2' in volumes
  1750. assert volumes['ext2']['external']['name'] == 'aliased'
  1751. def test_external_volume_invalid_config(self):
  1752. config_details = build_config_details({
  1753. 'version': '2',
  1754. 'services': {
  1755. 'bogus': {'image': 'busybox'}
  1756. },
  1757. 'volumes': {
  1758. 'ext': {'external': True, 'driver': 'foo'}
  1759. }
  1760. })
  1761. with pytest.raises(ConfigurationError):
  1762. config.load(config_details)
  1763. def test_depends_on_orders_services(self):
  1764. config_details = build_config_details({
  1765. 'version': '2',
  1766. 'services': {
  1767. 'one': {'image': 'busybox', 'depends_on': ['three', 'two']},
  1768. 'two': {'image': 'busybox', 'depends_on': ['three']},
  1769. 'three': {'image': 'busybox'},
  1770. },
  1771. })
  1772. actual = config.load(config_details)
  1773. assert (
  1774. [service['name'] for service in actual.services] ==
  1775. ['three', 'two', 'one']
  1776. )
  1777. def test_depends_on_unknown_service_errors(self):
  1778. config_details = build_config_details({
  1779. 'version': '2',
  1780. 'services': {
  1781. 'one': {'image': 'busybox', 'depends_on': ['three']},
  1782. },
  1783. })
  1784. with pytest.raises(ConfigurationError) as exc:
  1785. config.load(config_details)
  1786. assert "Service 'one' depends on service 'three'" in exc.exconly()
  1787. def test_linked_service_is_undefined(self):
  1788. with self.assertRaises(ConfigurationError):
  1789. config.load(
  1790. build_config_details({
  1791. 'version': '2',
  1792. 'services': {
  1793. 'web': {'image': 'busybox', 'links': ['db:db']},
  1794. },
  1795. })
  1796. )
  1797. def test_load_dockerfile_without_context(self):
  1798. config_details = build_config_details({
  1799. 'version': '2',
  1800. 'services': {
  1801. 'one': {'build': {'dockerfile': 'Dockerfile.foo'}},
  1802. },
  1803. })
  1804. with pytest.raises(ConfigurationError) as exc:
  1805. config.load(config_details)
  1806. assert 'has neither an image nor a build context' in exc.exconly()
  1807. def test_load_secrets(self):
  1808. base_file = config.ConfigFile(
  1809. 'base.yaml',
  1810. {
  1811. 'version': '3.1',
  1812. 'services': {
  1813. 'web': {
  1814. 'image': 'example/web',
  1815. 'secrets': [
  1816. 'one',
  1817. {
  1818. 'source': 'source',
  1819. 'target': 'target',
  1820. 'uid': '100',
  1821. 'gid': '200',
  1822. 'mode': 0o777,
  1823. },
  1824. ],
  1825. },
  1826. },
  1827. 'secrets': {
  1828. 'one': {'file': 'secret.txt'},
  1829. },
  1830. })
  1831. details = config.ConfigDetails('.', [base_file])
  1832. service_dicts = config.load(details).services
  1833. expected = [
  1834. {
  1835. 'name': 'web',
  1836. 'image': 'example/web',
  1837. 'secrets': [
  1838. types.ServiceSecret('one', None, None, None, None),
  1839. types.ServiceSecret('source', 'target', '100', '200', 0o777),
  1840. ],
  1841. },
  1842. ]
  1843. assert service_sort(service_dicts) == service_sort(expected)
  1844. def test_load_secrets_multi_file(self):
  1845. base_file = config.ConfigFile(
  1846. 'base.yaml',
  1847. {
  1848. 'version': '3.1',
  1849. 'services': {
  1850. 'web': {
  1851. 'image': 'example/web',
  1852. 'secrets': ['one'],
  1853. },
  1854. },
  1855. 'secrets': {
  1856. 'one': {'file': 'secret.txt'},
  1857. },
  1858. })
  1859. override_file = config.ConfigFile(
  1860. 'base.yaml',
  1861. {
  1862. 'version': '3.1',
  1863. 'services': {
  1864. 'web': {
  1865. 'secrets': [
  1866. {
  1867. 'source': 'source',
  1868. 'target': 'target',
  1869. 'uid': '100',
  1870. 'gid': '200',
  1871. 'mode': 0o777,
  1872. },
  1873. ],
  1874. },
  1875. },
  1876. })
  1877. details = config.ConfigDetails('.', [base_file, override_file])
  1878. service_dicts = config.load(details).services
  1879. expected = [
  1880. {
  1881. 'name': 'web',
  1882. 'image': 'example/web',
  1883. 'secrets': [
  1884. types.ServiceSecret('one', None, None, None, None),
  1885. types.ServiceSecret('source', 'target', '100', '200', 0o777),
  1886. ],
  1887. },
  1888. ]
  1889. assert service_sort(service_dicts) == service_sort(expected)
  1890. class NetworkModeTest(unittest.TestCase):
  1891. def test_network_mode_standard(self):
  1892. config_data = config.load(build_config_details({
  1893. 'version': '2',
  1894. 'services': {
  1895. 'web': {
  1896. 'image': 'busybox',
  1897. 'command': "top",
  1898. 'network_mode': 'bridge',
  1899. },
  1900. },
  1901. }))
  1902. assert config_data.services[0]['network_mode'] == 'bridge'
  1903. def test_network_mode_standard_v1(self):
  1904. config_data = config.load(build_config_details({
  1905. 'web': {
  1906. 'image': 'busybox',
  1907. 'command': "top",
  1908. 'net': 'bridge',
  1909. },
  1910. }))
  1911. assert config_data.services[0]['network_mode'] == 'bridge'
  1912. assert 'net' not in config_data.services[0]
  1913. def test_network_mode_container(self):
  1914. config_data = config.load(build_config_details({
  1915. 'version': '2',
  1916. 'services': {
  1917. 'web': {
  1918. 'image': 'busybox',
  1919. 'command': "top",
  1920. 'network_mode': 'container:foo',
  1921. },
  1922. },
  1923. }))
  1924. assert config_data.services[0]['network_mode'] == 'container:foo'
  1925. def test_network_mode_container_v1(self):
  1926. config_data = config.load(build_config_details({
  1927. 'web': {
  1928. 'image': 'busybox',
  1929. 'command': "top",
  1930. 'net': 'container:foo',
  1931. },
  1932. }))
  1933. assert config_data.services[0]['network_mode'] == 'container:foo'
  1934. def test_network_mode_service(self):
  1935. config_data = config.load(build_config_details({
  1936. 'version': '2',
  1937. 'services': {
  1938. 'web': {
  1939. 'image': 'busybox',
  1940. 'command': "top",
  1941. 'network_mode': 'service:foo',
  1942. },
  1943. 'foo': {
  1944. 'image': 'busybox',
  1945. 'command': "top",
  1946. },
  1947. },
  1948. }))
  1949. assert config_data.services[1]['network_mode'] == 'service:foo'
  1950. def test_network_mode_service_v1(self):
  1951. config_data = config.load(build_config_details({
  1952. 'web': {
  1953. 'image': 'busybox',
  1954. 'command': "top",
  1955. 'net': 'container:foo',
  1956. },
  1957. 'foo': {
  1958. 'image': 'busybox',
  1959. 'command': "top",
  1960. },
  1961. }))
  1962. assert config_data.services[1]['network_mode'] == 'service:foo'
  1963. def test_network_mode_service_nonexistent(self):
  1964. with pytest.raises(ConfigurationError) as excinfo:
  1965. config.load(build_config_details({
  1966. 'version': '2',
  1967. 'services': {
  1968. 'web': {
  1969. 'image': 'busybox',
  1970. 'command': "top",
  1971. 'network_mode': 'service:foo',
  1972. },
  1973. },
  1974. }))
  1975. assert "service 'foo' which is undefined" in excinfo.exconly()
  1976. def test_network_mode_plus_networks_is_invalid(self):
  1977. with pytest.raises(ConfigurationError) as excinfo:
  1978. config.load(build_config_details({
  1979. 'version': '2',
  1980. 'services': {
  1981. 'web': {
  1982. 'image': 'busybox',
  1983. 'command': "top",
  1984. 'network_mode': 'bridge',
  1985. 'networks': ['front'],
  1986. },
  1987. },
  1988. 'networks': {
  1989. 'front': None,
  1990. }
  1991. }))
  1992. assert "'network_mode' and 'networks' cannot be combined" in excinfo.exconly()
  1993. class PortsTest(unittest.TestCase):
  1994. INVALID_PORTS_TYPES = [
  1995. {"1": "8000"},
  1996. False,
  1997. "8000",
  1998. 8000,
  1999. ]
  2000. NON_UNIQUE_SINGLE_PORTS = [
  2001. ["8000", "8000"],
  2002. ]
  2003. INVALID_PORT_MAPPINGS = [
  2004. ["8000-8001:8000"],
  2005. ]
  2006. VALID_SINGLE_PORTS = [
  2007. ["8000"],
  2008. ["8000/tcp"],
  2009. ["8000", "9000"],
  2010. [8000],
  2011. [8000, 9000],
  2012. ]
  2013. VALID_PORT_MAPPINGS = [
  2014. ["8000:8050"],
  2015. ["49153-49154:3002-3003"],
  2016. ]
  2017. def test_config_invalid_ports_type_validation(self):
  2018. for invalid_ports in self.INVALID_PORTS_TYPES:
  2019. with pytest.raises(ConfigurationError) as exc:
  2020. self.check_config({'ports': invalid_ports})
  2021. assert "contains an invalid type" in exc.value.msg
  2022. def test_config_non_unique_ports_validation(self):
  2023. for invalid_ports in self.NON_UNIQUE_SINGLE_PORTS:
  2024. with pytest.raises(ConfigurationError) as exc:
  2025. self.check_config({'ports': invalid_ports})
  2026. assert "non-unique" in exc.value.msg
  2027. def test_config_invalid_ports_format_validation(self):
  2028. for invalid_ports in self.INVALID_PORT_MAPPINGS:
  2029. with pytest.raises(ConfigurationError) as exc:
  2030. self.check_config({'ports': invalid_ports})
  2031. assert "Port ranges don't match in length" in exc.value.msg
  2032. def test_config_valid_ports_format_validation(self):
  2033. for valid_ports in self.VALID_SINGLE_PORTS + self.VALID_PORT_MAPPINGS:
  2034. self.check_config({'ports': valid_ports})
  2035. def test_config_invalid_expose_type_validation(self):
  2036. for invalid_expose in self.INVALID_PORTS_TYPES:
  2037. with pytest.raises(ConfigurationError) as exc:
  2038. self.check_config({'expose': invalid_expose})
  2039. assert "contains an invalid type" in exc.value.msg
  2040. def test_config_non_unique_expose_validation(self):
  2041. for invalid_expose in self.NON_UNIQUE_SINGLE_PORTS:
  2042. with pytest.raises(ConfigurationError) as exc:
  2043. self.check_config({'expose': invalid_expose})
  2044. assert "non-unique" in exc.value.msg
  2045. def test_config_invalid_expose_format_validation(self):
  2046. # Valid port mappings ARE NOT valid 'expose' entries
  2047. for invalid_expose in self.INVALID_PORT_MAPPINGS + self.VALID_PORT_MAPPINGS:
  2048. with pytest.raises(ConfigurationError) as exc:
  2049. self.check_config({'expose': invalid_expose})
  2050. assert "should be of the format" in exc.value.msg
  2051. def test_config_valid_expose_format_validation(self):
  2052. # Valid single ports ARE valid 'expose' entries
  2053. for valid_expose in self.VALID_SINGLE_PORTS:
  2054. self.check_config({'expose': valid_expose})
  2055. def check_config(self, cfg):
  2056. config.load(
  2057. build_config_details(
  2058. {'web': dict(image='busybox', **cfg)},
  2059. 'working_dir',
  2060. 'filename.yml'
  2061. )
  2062. )
  2063. class InterpolationTest(unittest.TestCase):
  2064. @mock.patch.dict(os.environ)
  2065. def test_config_file_with_environment_file(self):
  2066. project_dir = 'tests/fixtures/default-env-file'
  2067. service_dicts = config.load(
  2068. config.find(
  2069. project_dir, None, Environment.from_env_file(project_dir)
  2070. )
  2071. ).services
  2072. self.assertEqual(service_dicts[0], {
  2073. 'name': 'web',
  2074. 'image': 'alpine:latest',
  2075. 'ports': [
  2076. types.ServicePort.parse('5643')[0],
  2077. types.ServicePort.parse('9999')[0]
  2078. ],
  2079. 'command': 'true'
  2080. })
  2081. @mock.patch.dict(os.environ)
  2082. def test_config_file_with_environment_variable(self):
  2083. project_dir = 'tests/fixtures/environment-interpolation'
  2084. os.environ.update(
  2085. IMAGE="busybox",
  2086. HOST_PORT="80",
  2087. LABEL_VALUE="myvalue",
  2088. )
  2089. service_dicts = config.load(
  2090. config.find(
  2091. project_dir, None, Environment.from_env_file(project_dir)
  2092. )
  2093. ).services
  2094. self.assertEqual(service_dicts, [
  2095. {
  2096. 'name': 'web',
  2097. 'image': 'busybox',
  2098. 'ports': types.ServicePort.parse('80:8000'),
  2099. 'labels': {'mylabel': 'myvalue'},
  2100. 'hostname': 'host-',
  2101. 'command': '${ESCAPED}',
  2102. }
  2103. ])
  2104. @mock.patch.dict(os.environ)
  2105. def test_unset_variable_produces_warning(self):
  2106. os.environ.pop('FOO', None)
  2107. os.environ.pop('BAR', None)
  2108. config_details = build_config_details(
  2109. {
  2110. 'web': {
  2111. 'image': '${FOO}',
  2112. 'command': '${BAR}',
  2113. 'container_name': '${BAR}',
  2114. },
  2115. },
  2116. '.',
  2117. None,
  2118. )
  2119. with mock.patch('compose.config.environment.log') as log:
  2120. config.load(config_details)
  2121. self.assertEqual(2, log.warn.call_count)
  2122. warnings = sorted(args[0][0] for args in log.warn.call_args_list)
  2123. self.assertIn('BAR', warnings[0])
  2124. self.assertIn('FOO', warnings[1])
  2125. @mock.patch.dict(os.environ)
  2126. def test_invalid_interpolation(self):
  2127. with self.assertRaises(config.ConfigurationError) as cm:
  2128. config.load(
  2129. build_config_details(
  2130. {'web': {'image': '${'}},
  2131. 'working_dir',
  2132. 'filename.yml'
  2133. )
  2134. )
  2135. self.assertIn('Invalid', cm.exception.msg)
  2136. self.assertIn('for "image" option', cm.exception.msg)
  2137. self.assertIn('in service "web"', cm.exception.msg)
  2138. self.assertIn('"${"', cm.exception.msg)
  2139. def test_empty_environment_key_allowed(self):
  2140. service_dict = config.load(
  2141. build_config_details(
  2142. {
  2143. 'web': {
  2144. 'build': '.',
  2145. 'environment': {
  2146. 'POSTGRES_PASSWORD': ''
  2147. },
  2148. },
  2149. },
  2150. '.',
  2151. None,
  2152. )
  2153. ).services[0]
  2154. self.assertEqual(service_dict['environment']['POSTGRES_PASSWORD'], '')
  2155. class VolumeConfigTest(unittest.TestCase):
  2156. def test_no_binding(self):
  2157. d = make_service_dict('foo', {'build': '.', 'volumes': ['/data']}, working_dir='.')
  2158. self.assertEqual(d['volumes'], ['/data'])
  2159. @mock.patch.dict(os.environ)
  2160. def test_volume_binding_with_environment_variable(self):
  2161. os.environ['VOLUME_PATH'] = '/host/path'
  2162. d = config.load(
  2163. build_config_details(
  2164. {'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
  2165. '.',
  2166. None,
  2167. )
  2168. ).services[0]
  2169. self.assertEqual(d['volumes'], [VolumeSpec.parse('/host/path:/container/path')])
  2170. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  2171. @mock.patch.dict(os.environ)
  2172. def test_volume_binding_with_home(self):
  2173. os.environ['HOME'] = '/home/user'
  2174. d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
  2175. self.assertEqual(d['volumes'], ['/home/user:/container/path'])
  2176. def test_name_does_not_expand(self):
  2177. d = make_service_dict('foo', {'build': '.', 'volumes': ['mydatavolume:/data']}, working_dir='.')
  2178. self.assertEqual(d['volumes'], ['mydatavolume:/data'])
  2179. def test_absolute_posix_path_does_not_expand(self):
  2180. d = make_service_dict('foo', {'build': '.', 'volumes': ['/var/lib/data:/data']}, working_dir='.')
  2181. self.assertEqual(d['volumes'], ['/var/lib/data:/data'])
  2182. def test_absolute_windows_path_does_not_expand(self):
  2183. d = make_service_dict('foo', {'build': '.', 'volumes': ['c:\\data:/data']}, working_dir='.')
  2184. self.assertEqual(d['volumes'], ['c:\\data:/data'])
  2185. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  2186. def test_relative_path_does_expand_posix(self):
  2187. d = make_service_dict(
  2188. 'foo',
  2189. {'build': '.', 'volumes': ['./data:/data']},
  2190. working_dir='/home/me/myproject')
  2191. self.assertEqual(d['volumes'], ['/home/me/myproject/data:/data'])
  2192. d = make_service_dict(
  2193. 'foo',
  2194. {'build': '.', 'volumes': ['.:/data']},
  2195. working_dir='/home/me/myproject')
  2196. self.assertEqual(d['volumes'], ['/home/me/myproject:/data'])
  2197. d = make_service_dict(
  2198. 'foo',
  2199. {'build': '.', 'volumes': ['../otherproject:/data']},
  2200. working_dir='/home/me/myproject')
  2201. self.assertEqual(d['volumes'], ['/home/me/otherproject:/data'])
  2202. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='windows paths')
  2203. def test_relative_path_does_expand_windows(self):
  2204. d = make_service_dict(
  2205. 'foo',
  2206. {'build': '.', 'volumes': ['./data:/data']},
  2207. working_dir='c:\\Users\\me\\myproject')
  2208. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject\\data:/data'])
  2209. d = make_service_dict(
  2210. 'foo',
  2211. {'build': '.', 'volumes': ['.:/data']},
  2212. working_dir='c:\\Users\\me\\myproject')
  2213. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject:/data'])
  2214. d = make_service_dict(
  2215. 'foo',
  2216. {'build': '.', 'volumes': ['../otherproject:/data']},
  2217. working_dir='c:\\Users\\me\\myproject')
  2218. self.assertEqual(d['volumes'], ['c:\\Users\\me\\otherproject:/data'])
  2219. @mock.patch.dict(os.environ)
  2220. def test_home_directory_with_driver_does_not_expand(self):
  2221. os.environ['NAME'] = 'surprise!'
  2222. d = make_service_dict('foo', {
  2223. 'build': '.',
  2224. 'volumes': ['~:/data'],
  2225. 'volume_driver': 'foodriver',
  2226. }, working_dir='.')
  2227. self.assertEqual(d['volumes'], ['~:/data'])
  2228. def test_volume_path_with_non_ascii_directory(self):
  2229. volume = u'/Füü/data:/data'
  2230. container_path = config.resolve_volume_path(".", volume)
  2231. self.assertEqual(container_path, volume)
  2232. class MergePathMappingTest(object):
  2233. config_name = ""
  2234. def test_empty(self):
  2235. service_dict = config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  2236. assert self.config_name not in service_dict
  2237. def test_no_override(self):
  2238. service_dict = config.merge_service_dicts(
  2239. {self.config_name: ['/foo:/code', '/data']},
  2240. {},
  2241. DEFAULT_VERSION)
  2242. assert set(service_dict[self.config_name]) == set(['/foo:/code', '/data'])
  2243. def test_no_base(self):
  2244. service_dict = config.merge_service_dicts(
  2245. {},
  2246. {self.config_name: ['/bar:/code']},
  2247. DEFAULT_VERSION)
  2248. assert set(service_dict[self.config_name]) == set(['/bar:/code'])
  2249. def test_override_explicit_path(self):
  2250. service_dict = config.merge_service_dicts(
  2251. {self.config_name: ['/foo:/code', '/data']},
  2252. {self.config_name: ['/bar:/code']},
  2253. DEFAULT_VERSION)
  2254. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  2255. def test_add_explicit_path(self):
  2256. service_dict = config.merge_service_dicts(
  2257. {self.config_name: ['/foo:/code', '/data']},
  2258. {self.config_name: ['/bar:/code', '/quux:/data']},
  2259. DEFAULT_VERSION)
  2260. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/quux:/data'])
  2261. def test_remove_explicit_path(self):
  2262. service_dict = config.merge_service_dicts(
  2263. {self.config_name: ['/foo:/code', '/quux:/data']},
  2264. {self.config_name: ['/bar:/code', '/data']},
  2265. DEFAULT_VERSION)
  2266. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  2267. class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
  2268. config_name = 'volumes'
  2269. class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
  2270. config_name = 'devices'
  2271. class BuildOrImageMergeTest(unittest.TestCase):
  2272. def test_merge_build_or_image_no_override(self):
  2273. self.assertEqual(
  2274. config.merge_service_dicts({'build': '.'}, {}, V1),
  2275. {'build': '.'},
  2276. )
  2277. self.assertEqual(
  2278. config.merge_service_dicts({'image': 'redis'}, {}, V1),
  2279. {'image': 'redis'},
  2280. )
  2281. def test_merge_build_or_image_override_with_same(self):
  2282. self.assertEqual(
  2283. config.merge_service_dicts({'build': '.'}, {'build': './web'}, V1),
  2284. {'build': './web'},
  2285. )
  2286. self.assertEqual(
  2287. config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}, V1),
  2288. {'image': 'postgres'},
  2289. )
  2290. def test_merge_build_or_image_override_with_other(self):
  2291. self.assertEqual(
  2292. config.merge_service_dicts({'build': '.'}, {'image': 'redis'}, V1),
  2293. {'image': 'redis'},
  2294. )
  2295. self.assertEqual(
  2296. config.merge_service_dicts({'image': 'redis'}, {'build': '.'}, V1),
  2297. {'build': '.'}
  2298. )
  2299. class MergeListsTest(object):
  2300. config_name = ""
  2301. base_config = []
  2302. override_config = []
  2303. def merged_config(self):
  2304. return set(self.base_config) | set(self.override_config)
  2305. def test_empty(self):
  2306. assert self.config_name not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  2307. def test_no_override(self):
  2308. service_dict = config.merge_service_dicts(
  2309. {self.config_name: self.base_config},
  2310. {},
  2311. DEFAULT_VERSION)
  2312. assert set(service_dict[self.config_name]) == set(self.base_config)
  2313. def test_no_base(self):
  2314. service_dict = config.merge_service_dicts(
  2315. {},
  2316. {self.config_name: self.base_config},
  2317. DEFAULT_VERSION)
  2318. assert set(service_dict[self.config_name]) == set(self.base_config)
  2319. def test_add_item(self):
  2320. service_dict = config.merge_service_dicts(
  2321. {self.config_name: self.base_config},
  2322. {self.config_name: self.override_config},
  2323. DEFAULT_VERSION)
  2324. assert set(service_dict[self.config_name]) == set(self.merged_config())
  2325. class MergePortsTest(unittest.TestCase, MergeListsTest):
  2326. config_name = 'ports'
  2327. base_config = ['10:8000', '9000']
  2328. override_config = ['20:8000']
  2329. def merged_config(self):
  2330. return self.convert(self.base_config) | self.convert(self.override_config)
  2331. def convert(self, port_config):
  2332. return set(config.merge_service_dicts(
  2333. {self.config_name: port_config},
  2334. {self.config_name: []},
  2335. DEFAULT_VERSION
  2336. )[self.config_name])
  2337. def test_duplicate_port_mappings(self):
  2338. service_dict = config.merge_service_dicts(
  2339. {self.config_name: self.base_config},
  2340. {self.config_name: self.base_config},
  2341. DEFAULT_VERSION
  2342. )
  2343. assert set(service_dict[self.config_name]) == self.convert(self.base_config)
  2344. def test_no_override(self):
  2345. service_dict = config.merge_service_dicts(
  2346. {self.config_name: self.base_config},
  2347. {},
  2348. DEFAULT_VERSION)
  2349. assert set(service_dict[self.config_name]) == self.convert(self.base_config)
  2350. def test_no_base(self):
  2351. service_dict = config.merge_service_dicts(
  2352. {},
  2353. {self.config_name: self.base_config},
  2354. DEFAULT_VERSION)
  2355. assert set(service_dict[self.config_name]) == self.convert(self.base_config)
  2356. class MergeNetworksTest(unittest.TestCase, MergeListsTest):
  2357. config_name = 'networks'
  2358. base_config = ['frontend', 'backend']
  2359. override_config = ['monitoring']
  2360. class MergeStringsOrListsTest(unittest.TestCase):
  2361. def test_no_override(self):
  2362. service_dict = config.merge_service_dicts(
  2363. {'dns': '8.8.8.8'},
  2364. {},
  2365. DEFAULT_VERSION)
  2366. assert set(service_dict['dns']) == set(['8.8.8.8'])
  2367. def test_no_base(self):
  2368. service_dict = config.merge_service_dicts(
  2369. {},
  2370. {'dns': '8.8.8.8'},
  2371. DEFAULT_VERSION)
  2372. assert set(service_dict['dns']) == set(['8.8.8.8'])
  2373. def test_add_string(self):
  2374. service_dict = config.merge_service_dicts(
  2375. {'dns': ['8.8.8.8']},
  2376. {'dns': '9.9.9.9'},
  2377. DEFAULT_VERSION)
  2378. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  2379. def test_add_list(self):
  2380. service_dict = config.merge_service_dicts(
  2381. {'dns': '8.8.8.8'},
  2382. {'dns': ['9.9.9.9']},
  2383. DEFAULT_VERSION)
  2384. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  2385. class MergeLabelsTest(unittest.TestCase):
  2386. def test_empty(self):
  2387. assert 'labels' not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  2388. def test_no_override(self):
  2389. service_dict = config.merge_service_dicts(
  2390. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2391. make_service_dict('foo', {'build': '.'}, 'tests/'),
  2392. DEFAULT_VERSION)
  2393. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  2394. def test_no_base(self):
  2395. service_dict = config.merge_service_dicts(
  2396. make_service_dict('foo', {'build': '.'}, 'tests/'),
  2397. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  2398. DEFAULT_VERSION)
  2399. assert service_dict['labels'] == {'foo': '2'}
  2400. def test_override_explicit_value(self):
  2401. service_dict = config.merge_service_dicts(
  2402. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2403. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  2404. DEFAULT_VERSION)
  2405. assert service_dict['labels'] == {'foo': '2', 'bar': ''}
  2406. def test_add_explicit_value(self):
  2407. service_dict = config.merge_service_dicts(
  2408. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2409. make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
  2410. DEFAULT_VERSION)
  2411. assert service_dict['labels'] == {'foo': '1', 'bar': '2'}
  2412. def test_remove_explicit_value(self):
  2413. service_dict = config.merge_service_dicts(
  2414. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
  2415. make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
  2416. DEFAULT_VERSION)
  2417. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  2418. class MemoryOptionsTest(unittest.TestCase):
  2419. def test_validation_fails_with_just_memswap_limit(self):
  2420. """
  2421. When you set a 'memswap_limit' it is invalid config unless you also set
  2422. a mem_limit
  2423. """
  2424. with pytest.raises(ConfigurationError) as excinfo:
  2425. config.load(
  2426. build_config_details(
  2427. {
  2428. 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
  2429. },
  2430. 'tests/fixtures/extends',
  2431. 'filename.yml'
  2432. )
  2433. )
  2434. assert "foo.memswap_limit is invalid: when defining " \
  2435. "'memswap_limit' you must set 'mem_limit' as well" \
  2436. in excinfo.exconly()
  2437. def test_validation_with_correct_memswap_values(self):
  2438. service_dict = config.load(
  2439. build_config_details(
  2440. {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
  2441. 'tests/fixtures/extends',
  2442. 'common.yml'
  2443. )
  2444. ).services
  2445. self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
  2446. def test_memswap_can_be_a_string(self):
  2447. service_dict = config.load(
  2448. build_config_details(
  2449. {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
  2450. 'tests/fixtures/extends',
  2451. 'common.yml'
  2452. )
  2453. ).services
  2454. self.assertEqual(service_dict[0]['memswap_limit'], "512M")
  2455. class EnvTest(unittest.TestCase):
  2456. def test_parse_environment_as_list(self):
  2457. environment = [
  2458. 'NORMAL=F1',
  2459. 'CONTAINS_EQUALS=F=2',
  2460. 'TRAILING_EQUALS=',
  2461. ]
  2462. self.assertEqual(
  2463. config.parse_environment(environment),
  2464. {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
  2465. )
  2466. def test_parse_environment_as_dict(self):
  2467. environment = {
  2468. 'NORMAL': 'F1',
  2469. 'CONTAINS_EQUALS': 'F=2',
  2470. 'TRAILING_EQUALS': None,
  2471. }
  2472. self.assertEqual(config.parse_environment(environment), environment)
  2473. def test_parse_environment_invalid(self):
  2474. with self.assertRaises(ConfigurationError):
  2475. config.parse_environment('a=b')
  2476. def test_parse_environment_empty(self):
  2477. self.assertEqual(config.parse_environment(None), {})
  2478. @mock.patch.dict(os.environ)
  2479. def test_resolve_environment(self):
  2480. os.environ['FILE_DEF'] = 'E1'
  2481. os.environ['FILE_DEF_EMPTY'] = 'E2'
  2482. os.environ['ENV_DEF'] = 'E3'
  2483. service_dict = {
  2484. 'build': '.',
  2485. 'environment': {
  2486. 'FILE_DEF': 'F1',
  2487. 'FILE_DEF_EMPTY': '',
  2488. 'ENV_DEF': None,
  2489. 'NO_DEF': None
  2490. },
  2491. }
  2492. self.assertEqual(
  2493. resolve_environment(
  2494. service_dict, Environment.from_env_file(None)
  2495. ),
  2496. {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None},
  2497. )
  2498. def test_resolve_environment_from_env_file(self):
  2499. self.assertEqual(
  2500. resolve_environment({'env_file': ['tests/fixtures/env/one.env']}),
  2501. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
  2502. )
  2503. def test_environment_overrides_env_file(self):
  2504. self.assertEqual(
  2505. resolve_environment({
  2506. 'environment': {'FOO': 'baz'},
  2507. 'env_file': ['tests/fixtures/env/one.env'],
  2508. }),
  2509. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz'},
  2510. )
  2511. def test_resolve_environment_with_multiple_env_files(self):
  2512. service_dict = {
  2513. 'env_file': [
  2514. 'tests/fixtures/env/one.env',
  2515. 'tests/fixtures/env/two.env'
  2516. ]
  2517. }
  2518. self.assertEqual(
  2519. resolve_environment(service_dict),
  2520. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
  2521. )
  2522. def test_resolve_environment_nonexistent_file(self):
  2523. with pytest.raises(ConfigurationError) as exc:
  2524. config.load(build_config_details(
  2525. {'foo': {'image': 'example', 'env_file': 'nonexistent.env'}},
  2526. working_dir='tests/fixtures/env'))
  2527. assert 'Couldn\'t find env file' in exc.exconly()
  2528. assert 'nonexistent.env' in exc.exconly()
  2529. @mock.patch.dict(os.environ)
  2530. def test_resolve_environment_from_env_file_with_empty_values(self):
  2531. os.environ['FILE_DEF'] = 'E1'
  2532. os.environ['FILE_DEF_EMPTY'] = 'E2'
  2533. os.environ['ENV_DEF'] = 'E3'
  2534. self.assertEqual(
  2535. resolve_environment(
  2536. {'env_file': ['tests/fixtures/env/resolve.env']},
  2537. Environment.from_env_file(None)
  2538. ),
  2539. {
  2540. 'FILE_DEF': u'bär',
  2541. 'FILE_DEF_EMPTY': '',
  2542. 'ENV_DEF': 'E3',
  2543. 'NO_DEF': None
  2544. },
  2545. )
  2546. @mock.patch.dict(os.environ)
  2547. def test_resolve_build_args(self):
  2548. os.environ['env_arg'] = 'value2'
  2549. build = {
  2550. 'context': '.',
  2551. 'args': {
  2552. 'arg1': 'value1',
  2553. 'empty_arg': '',
  2554. 'env_arg': None,
  2555. 'no_env': None
  2556. }
  2557. }
  2558. self.assertEqual(
  2559. resolve_build_args(build, Environment.from_env_file(build['context'])),
  2560. {'arg1': 'value1', 'empty_arg': '', 'env_arg': 'value2', 'no_env': None},
  2561. )
  2562. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2563. @mock.patch.dict(os.environ)
  2564. def test_resolve_path(self):
  2565. os.environ['HOSTENV'] = '/tmp'
  2566. os.environ['CONTAINERENV'] = '/host/tmp'
  2567. service_dict = config.load(
  2568. build_config_details(
  2569. {'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
  2570. "tests/fixtures/env",
  2571. )
  2572. ).services[0]
  2573. self.assertEqual(
  2574. set(service_dict['volumes']),
  2575. set([VolumeSpec.parse('/tmp:/host/tmp')]))
  2576. service_dict = config.load(
  2577. build_config_details(
  2578. {'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
  2579. "tests/fixtures/env",
  2580. )
  2581. ).services[0]
  2582. self.assertEqual(
  2583. set(service_dict['volumes']),
  2584. set([VolumeSpec.parse('/opt/tmp:/opt/host/tmp')]))
  2585. def load_from_filename(filename):
  2586. return config.load(
  2587. config.find('.', [filename], Environment.from_env_file('.'))
  2588. ).services
  2589. class ExtendsTest(unittest.TestCase):
  2590. def test_extends(self):
  2591. service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
  2592. self.assertEqual(service_sort(service_dicts), service_sort([
  2593. {
  2594. 'name': 'mydb',
  2595. 'image': 'busybox',
  2596. 'command': 'top',
  2597. },
  2598. {
  2599. 'name': 'myweb',
  2600. 'image': 'busybox',
  2601. 'command': 'top',
  2602. 'network_mode': 'bridge',
  2603. 'links': ['mydb:db'],
  2604. 'environment': {
  2605. "FOO": "1",
  2606. "BAR": "2",
  2607. "BAZ": "2",
  2608. },
  2609. }
  2610. ]))
  2611. def test_merging_env_labels_ulimits(self):
  2612. service_dicts = load_from_filename('tests/fixtures/extends/common-env-labels-ulimits.yml')
  2613. self.assertEqual(service_sort(service_dicts), service_sort([
  2614. {
  2615. 'name': 'web',
  2616. 'image': 'busybox',
  2617. 'command': '/bin/true',
  2618. 'network_mode': 'host',
  2619. 'environment': {
  2620. "FOO": "2",
  2621. "BAR": "1",
  2622. "BAZ": "3",
  2623. },
  2624. 'labels': {'label': 'one'},
  2625. 'ulimits': {'nproc': 65535, 'memlock': {'soft': 1024, 'hard': 2048}}
  2626. }
  2627. ]))
  2628. def test_nested(self):
  2629. service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
  2630. self.assertEqual(service_dicts, [
  2631. {
  2632. 'name': 'myweb',
  2633. 'image': 'busybox',
  2634. 'command': '/bin/true',
  2635. 'network_mode': 'host',
  2636. 'environment': {
  2637. "FOO": "2",
  2638. "BAR": "2",
  2639. },
  2640. },
  2641. ])
  2642. def test_self_referencing_file(self):
  2643. """
  2644. We specify a 'file' key that is the filename we're already in.
  2645. """
  2646. service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
  2647. self.assertEqual(service_sort(service_dicts), service_sort([
  2648. {
  2649. 'environment':
  2650. {
  2651. 'YEP': '1', 'BAR': '1', 'BAZ': '3'
  2652. },
  2653. 'image': 'busybox',
  2654. 'name': 'myweb'
  2655. },
  2656. {
  2657. 'environment':
  2658. {'YEP': '1'},
  2659. 'image': 'busybox',
  2660. 'name': 'otherweb'
  2661. },
  2662. {
  2663. 'environment':
  2664. {'YEP': '1', 'BAZ': '3'},
  2665. 'image': 'busybox',
  2666. 'name': 'web'
  2667. }
  2668. ]))
  2669. def test_circular(self):
  2670. with pytest.raises(config.CircularReference) as exc:
  2671. load_from_filename('tests/fixtures/extends/circle-1.yml')
  2672. path = [
  2673. (os.path.basename(filename), service_name)
  2674. for (filename, service_name) in exc.value.trail
  2675. ]
  2676. expected = [
  2677. ('circle-1.yml', 'web'),
  2678. ('circle-2.yml', 'other'),
  2679. ('circle-1.yml', 'web'),
  2680. ]
  2681. self.assertEqual(path, expected)
  2682. def test_extends_validation_empty_dictionary(self):
  2683. with pytest.raises(ConfigurationError) as excinfo:
  2684. config.load(
  2685. build_config_details(
  2686. {
  2687. 'web': {'image': 'busybox', 'extends': {}},
  2688. },
  2689. 'tests/fixtures/extends',
  2690. 'filename.yml'
  2691. )
  2692. )
  2693. assert 'service' in excinfo.exconly()
  2694. def test_extends_validation_missing_service_key(self):
  2695. with pytest.raises(ConfigurationError) as excinfo:
  2696. config.load(
  2697. build_config_details(
  2698. {
  2699. 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
  2700. },
  2701. 'tests/fixtures/extends',
  2702. 'filename.yml'
  2703. )
  2704. )
  2705. assert "'service' is a required property" in excinfo.exconly()
  2706. def test_extends_validation_invalid_key(self):
  2707. with pytest.raises(ConfigurationError) as excinfo:
  2708. config.load(
  2709. build_config_details(
  2710. {
  2711. 'web': {
  2712. 'image': 'busybox',
  2713. 'extends': {
  2714. 'file': 'common.yml',
  2715. 'service': 'web',
  2716. 'rogue_key': 'is not allowed'
  2717. }
  2718. },
  2719. },
  2720. 'tests/fixtures/extends',
  2721. 'filename.yml'
  2722. )
  2723. )
  2724. assert "web.extends contains unsupported option: 'rogue_key'" \
  2725. in excinfo.exconly()
  2726. def test_extends_validation_sub_property_key(self):
  2727. with pytest.raises(ConfigurationError) as excinfo:
  2728. config.load(
  2729. build_config_details(
  2730. {
  2731. 'web': {
  2732. 'image': 'busybox',
  2733. 'extends': {
  2734. 'file': 1,
  2735. 'service': 'web',
  2736. }
  2737. },
  2738. },
  2739. 'tests/fixtures/extends',
  2740. 'filename.yml'
  2741. )
  2742. )
  2743. assert "web.extends.file contains 1, which is an invalid type, it should be a string" \
  2744. in excinfo.exconly()
  2745. def test_extends_validation_no_file_key_no_filename_set(self):
  2746. dictionary = {'extends': {'service': 'web'}}
  2747. with pytest.raises(ConfigurationError) as excinfo:
  2748. make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
  2749. assert 'file' in excinfo.exconly()
  2750. def test_extends_validation_valid_config(self):
  2751. service = config.load(
  2752. build_config_details(
  2753. {
  2754. 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
  2755. },
  2756. 'tests/fixtures/extends',
  2757. 'common.yml'
  2758. )
  2759. ).services
  2760. self.assertEqual(len(service), 1)
  2761. self.assertIsInstance(service[0], dict)
  2762. self.assertEqual(service[0]['command'], "/bin/true")
  2763. def test_extended_service_with_invalid_config(self):
  2764. with pytest.raises(ConfigurationError) as exc:
  2765. load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
  2766. assert (
  2767. "myweb has neither an image nor a build context specified" in
  2768. exc.exconly()
  2769. )
  2770. def test_extended_service_with_valid_config(self):
  2771. service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
  2772. self.assertEqual(service[0]['command'], "top")
  2773. def test_extends_file_defaults_to_self(self):
  2774. """
  2775. Test not specifying a file in our extends options that the
  2776. config is valid and correctly extends from itself.
  2777. """
  2778. service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
  2779. self.assertEqual(service_sort(service_dicts), service_sort([
  2780. {
  2781. 'name': 'myweb',
  2782. 'image': 'busybox',
  2783. 'environment': {
  2784. "BAR": "1",
  2785. "BAZ": "3",
  2786. }
  2787. },
  2788. {
  2789. 'name': 'web',
  2790. 'image': 'busybox',
  2791. 'environment': {
  2792. "BAZ": "3",
  2793. }
  2794. }
  2795. ]))
  2796. def test_invalid_links_in_extended_service(self):
  2797. with pytest.raises(ConfigurationError) as excinfo:
  2798. load_from_filename('tests/fixtures/extends/invalid-links.yml')
  2799. assert "services with 'links' cannot be extended" in excinfo.exconly()
  2800. def test_invalid_volumes_from_in_extended_service(self):
  2801. with pytest.raises(ConfigurationError) as excinfo:
  2802. load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
  2803. assert "services with 'volumes_from' cannot be extended" in excinfo.exconly()
  2804. def test_invalid_net_in_extended_service(self):
  2805. with pytest.raises(ConfigurationError) as excinfo:
  2806. load_from_filename('tests/fixtures/extends/invalid-net-v2.yml')
  2807. assert 'network_mode: service' in excinfo.exconly()
  2808. assert 'cannot be extended' in excinfo.exconly()
  2809. with pytest.raises(ConfigurationError) as excinfo:
  2810. load_from_filename('tests/fixtures/extends/invalid-net.yml')
  2811. assert 'net: container' in excinfo.exconly()
  2812. assert 'cannot be extended' in excinfo.exconly()
  2813. @mock.patch.dict(os.environ)
  2814. def test_load_config_runs_interpolation_in_extended_service(self):
  2815. os.environ.update(HOSTNAME_VALUE="penguin")
  2816. expected_interpolated_value = "host-penguin"
  2817. service_dicts = load_from_filename(
  2818. 'tests/fixtures/extends/valid-interpolation.yml')
  2819. for service in service_dicts:
  2820. assert service['hostname'] == expected_interpolated_value
  2821. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2822. def test_volume_path(self):
  2823. dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
  2824. paths = [
  2825. VolumeSpec(
  2826. os.path.abspath('tests/fixtures/volume-path/common/foo'),
  2827. '/foo',
  2828. 'rw'),
  2829. VolumeSpec(
  2830. os.path.abspath('tests/fixtures/volume-path/bar'),
  2831. '/bar',
  2832. 'rw')
  2833. ]
  2834. self.assertEqual(set(dicts[0]['volumes']), set(paths))
  2835. def test_parent_build_path_dne(self):
  2836. child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
  2837. self.assertEqual(child, [
  2838. {
  2839. 'name': 'dnechild',
  2840. 'image': 'busybox',
  2841. 'command': '/bin/true',
  2842. 'environment': {
  2843. "FOO": "1",
  2844. "BAR": "2",
  2845. },
  2846. },
  2847. ])
  2848. def test_load_throws_error_when_base_service_does_not_exist(self):
  2849. with pytest.raises(ConfigurationError) as excinfo:
  2850. load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
  2851. assert "Cannot extend service 'foo'" in excinfo.exconly()
  2852. assert "Service not found" in excinfo.exconly()
  2853. def test_partial_service_config_in_extends_is_still_valid(self):
  2854. dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
  2855. self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
  2856. def test_extended_service_with_verbose_and_shorthand_way(self):
  2857. services = load_from_filename('tests/fixtures/extends/verbose-and-shorthand.yml')
  2858. self.assertEqual(service_sort(services), service_sort([
  2859. {
  2860. 'name': 'base',
  2861. 'image': 'busybox',
  2862. 'environment': {'BAR': '1'},
  2863. },
  2864. {
  2865. 'name': 'verbose',
  2866. 'image': 'busybox',
  2867. 'environment': {'BAR': '1', 'FOO': '1'},
  2868. },
  2869. {
  2870. 'name': 'shorthand',
  2871. 'image': 'busybox',
  2872. 'environment': {'BAR': '1', 'FOO': '2'},
  2873. },
  2874. ]))
  2875. @mock.patch.dict(os.environ)
  2876. def test_extends_with_environment_and_env_files(self):
  2877. tmpdir = py.test.ensuretemp('test_extends_with_environment')
  2878. self.addCleanup(tmpdir.remove)
  2879. commondir = tmpdir.mkdir('common')
  2880. commondir.join('base.yml').write("""
  2881. app:
  2882. image: 'example/app'
  2883. env_file:
  2884. - 'envs'
  2885. environment:
  2886. - SECRET
  2887. - TEST_ONE=common
  2888. - TEST_TWO=common
  2889. """)
  2890. tmpdir.join('docker-compose.yml').write("""
  2891. ext:
  2892. extends:
  2893. file: common/base.yml
  2894. service: app
  2895. env_file:
  2896. - 'envs'
  2897. environment:
  2898. - THING
  2899. - TEST_ONE=top
  2900. """)
  2901. commondir.join('envs').write("""
  2902. COMMON_ENV_FILE
  2903. TEST_ONE=common-env-file
  2904. TEST_TWO=common-env-file
  2905. TEST_THREE=common-env-file
  2906. TEST_FOUR=common-env-file
  2907. """)
  2908. tmpdir.join('envs').write("""
  2909. TOP_ENV_FILE
  2910. TEST_ONE=top-env-file
  2911. TEST_TWO=top-env-file
  2912. TEST_THREE=top-env-file
  2913. """)
  2914. expected = [
  2915. {
  2916. 'name': 'ext',
  2917. 'image': 'example/app',
  2918. 'environment': {
  2919. 'SECRET': 'secret',
  2920. 'TOP_ENV_FILE': 'secret',
  2921. 'COMMON_ENV_FILE': 'secret',
  2922. 'THING': 'thing',
  2923. 'TEST_ONE': 'top',
  2924. 'TEST_TWO': 'common',
  2925. 'TEST_THREE': 'top-env-file',
  2926. 'TEST_FOUR': 'common-env-file',
  2927. },
  2928. },
  2929. ]
  2930. os.environ['SECRET'] = 'secret'
  2931. os.environ['THING'] = 'thing'
  2932. os.environ['COMMON_ENV_FILE'] = 'secret'
  2933. os.environ['TOP_ENV_FILE'] = 'secret'
  2934. config = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2935. assert config == expected
  2936. def test_extends_with_mixed_versions_is_error(self):
  2937. tmpdir = py.test.ensuretemp('test_extends_with_mixed_version')
  2938. self.addCleanup(tmpdir.remove)
  2939. tmpdir.join('docker-compose.yml').write("""
  2940. version: "2"
  2941. services:
  2942. web:
  2943. extends:
  2944. file: base.yml
  2945. service: base
  2946. image: busybox
  2947. """)
  2948. tmpdir.join('base.yml').write("""
  2949. base:
  2950. volumes: ['/foo']
  2951. ports: ['3000:3000']
  2952. """)
  2953. with pytest.raises(ConfigurationError) as exc:
  2954. load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2955. assert 'Version mismatch' in exc.exconly()
  2956. def test_extends_with_defined_version_passes(self):
  2957. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2958. self.addCleanup(tmpdir.remove)
  2959. tmpdir.join('docker-compose.yml').write("""
  2960. version: "2"
  2961. services:
  2962. web:
  2963. extends:
  2964. file: base.yml
  2965. service: base
  2966. image: busybox
  2967. """)
  2968. tmpdir.join('base.yml').write("""
  2969. version: "2"
  2970. services:
  2971. base:
  2972. volumes: ['/foo']
  2973. ports: ['3000:3000']
  2974. command: top
  2975. """)
  2976. service = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2977. self.assertEqual(service[0]['command'], "top")
  2978. def test_extends_with_depends_on(self):
  2979. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2980. self.addCleanup(tmpdir.remove)
  2981. tmpdir.join('docker-compose.yml').write("""
  2982. version: "2"
  2983. services:
  2984. base:
  2985. image: example
  2986. web:
  2987. extends: base
  2988. image: busybox
  2989. depends_on: ['other']
  2990. other:
  2991. image: example
  2992. """)
  2993. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2994. assert service_sort(services)[2]['depends_on'] == {
  2995. 'other': {'condition': 'service_started'}
  2996. }
  2997. def test_extends_with_healthcheck(self):
  2998. service_dicts = load_from_filename('tests/fixtures/extends/healthcheck-2.yml')
  2999. assert service_sort(service_dicts) == [{
  3000. 'name': 'demo',
  3001. 'image': 'foobar:latest',
  3002. 'healthcheck': {
  3003. 'test': ['CMD', '/health.sh'],
  3004. 'interval': 10000000000,
  3005. 'timeout': 5000000000,
  3006. 'retries': 36,
  3007. }
  3008. }]
  3009. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  3010. class ExpandPathTest(unittest.TestCase):
  3011. working_dir = '/home/user/somedir'
  3012. def test_expand_path_normal(self):
  3013. result = config.expand_path(self.working_dir, 'myfile')
  3014. self.assertEqual(result, self.working_dir + '/' + 'myfile')
  3015. def test_expand_path_absolute(self):
  3016. abs_path = '/home/user/otherdir/somefile'
  3017. result = config.expand_path(self.working_dir, abs_path)
  3018. self.assertEqual(result, abs_path)
  3019. def test_expand_path_with_tilde(self):
  3020. test_path = '~/otherdir/somefile'
  3021. with mock.patch.dict(os.environ):
  3022. os.environ['HOME'] = user_path = '/home/user/'
  3023. result = config.expand_path(self.working_dir, test_path)
  3024. self.assertEqual(result, user_path + 'otherdir/somefile')
  3025. class VolumePathTest(unittest.TestCase):
  3026. def test_split_path_mapping_with_windows_path(self):
  3027. host_path = "c:\\Users\\msamblanet\\Documents\\anvil\\connect\\config"
  3028. windows_volume_path = host_path + ":/opt/connect/config:ro"
  3029. expected_mapping = ("/opt/connect/config:ro", host_path)
  3030. mapping = config.split_path_mapping(windows_volume_path)
  3031. assert mapping == expected_mapping
  3032. def test_split_path_mapping_with_windows_path_in_container(self):
  3033. host_path = 'c:\\Users\\remilia\\data'
  3034. container_path = 'c:\\scarletdevil\\data'
  3035. expected_mapping = (container_path, host_path)
  3036. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  3037. assert mapping == expected_mapping
  3038. def test_split_path_mapping_with_root_mount(self):
  3039. host_path = '/'
  3040. container_path = '/var/hostroot'
  3041. expected_mapping = (container_path, host_path)
  3042. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  3043. assert mapping == expected_mapping
  3044. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  3045. class BuildPathTest(unittest.TestCase):
  3046. def setUp(self):
  3047. self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
  3048. def test_nonexistent_path(self):
  3049. with self.assertRaises(ConfigurationError):
  3050. config.load(
  3051. build_config_details(
  3052. {
  3053. 'foo': {'build': 'nonexistent.path'},
  3054. },
  3055. 'working_dir',
  3056. 'filename.yml'
  3057. )
  3058. )
  3059. def test_relative_path(self):
  3060. relative_build_path = '../build-ctx/'
  3061. service_dict = make_service_dict(
  3062. 'relpath',
  3063. {'build': relative_build_path},
  3064. working_dir='tests/fixtures/build-path'
  3065. )
  3066. self.assertEqual(service_dict['build'], self.abs_context_path)
  3067. def test_absolute_path(self):
  3068. service_dict = make_service_dict(
  3069. 'abspath',
  3070. {'build': self.abs_context_path},
  3071. working_dir='tests/fixtures/build-path'
  3072. )
  3073. self.assertEqual(service_dict['build'], self.abs_context_path)
  3074. def test_from_file(self):
  3075. service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
  3076. self.assertEqual(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  3077. def test_valid_url_in_build_path(self):
  3078. valid_urls = [
  3079. 'git://github.com/docker/docker',
  3080. '[email protected]:docker/docker.git',
  3081. '[email protected]:atlassianlabs/atlassian-docker.git',
  3082. 'https://github.com/docker/docker.git',
  3083. 'http://github.com/docker/docker.git',
  3084. 'github.com/docker/docker.git',
  3085. ]
  3086. for valid_url in valid_urls:
  3087. service_dict = config.load(build_config_details({
  3088. 'validurl': {'build': valid_url},
  3089. }, '.', None)).services
  3090. assert service_dict[0]['build'] == {'context': valid_url}
  3091. def test_invalid_url_in_build_path(self):
  3092. invalid_urls = [
  3093. 'example.com/bogus',
  3094. 'ftp://example.com/',
  3095. '/path/does/not/exist',
  3096. ]
  3097. for invalid_url in invalid_urls:
  3098. with pytest.raises(ConfigurationError) as exc:
  3099. config.load(build_config_details({
  3100. 'invalidurl': {'build': invalid_url},
  3101. }, '.', None))
  3102. assert 'build path' in exc.exconly()
  3103. class HealthcheckTest(unittest.TestCase):
  3104. def test_healthcheck(self):
  3105. service_dict = make_service_dict(
  3106. 'test',
  3107. {'healthcheck': {
  3108. 'test': ['CMD', 'true'],
  3109. 'interval': '1s',
  3110. 'timeout': '1m',
  3111. 'retries': 3,
  3112. }},
  3113. '.',
  3114. )
  3115. assert service_dict['healthcheck'] == {
  3116. 'test': ['CMD', 'true'],
  3117. 'interval': nanoseconds_from_time_seconds(1),
  3118. 'timeout': nanoseconds_from_time_seconds(60),
  3119. 'retries': 3,
  3120. }
  3121. def test_disable(self):
  3122. service_dict = make_service_dict(
  3123. 'test',
  3124. {'healthcheck': {
  3125. 'disable': True,
  3126. }},
  3127. '.',
  3128. )
  3129. assert service_dict['healthcheck'] == {
  3130. 'test': ['NONE'],
  3131. }
  3132. def test_disable_with_other_config_is_invalid(self):
  3133. with pytest.raises(ConfigurationError) as excinfo:
  3134. make_service_dict(
  3135. 'invalid-healthcheck',
  3136. {'healthcheck': {
  3137. 'disable': True,
  3138. 'interval': '1s',
  3139. }},
  3140. '.',
  3141. )
  3142. assert 'invalid-healthcheck' in excinfo.exconly()
  3143. assert 'disable' in excinfo.exconly()
  3144. class GetDefaultConfigFilesTestCase(unittest.TestCase):
  3145. files = [
  3146. 'docker-compose.yml',
  3147. 'docker-compose.yaml',
  3148. ]
  3149. def test_get_config_path_default_file_in_basedir(self):
  3150. for index, filename in enumerate(self.files):
  3151. self.assertEqual(
  3152. filename,
  3153. get_config_filename_for_files(self.files[index:]))
  3154. with self.assertRaises(config.ComposeFileNotFound):
  3155. get_config_filename_for_files([])
  3156. def test_get_config_path_default_file_in_parent_dir(self):
  3157. """Test with files placed in the subdir"""
  3158. def get_config_in_subdir(files):
  3159. return get_config_filename_for_files(files, subdir=True)
  3160. for index, filename in enumerate(self.files):
  3161. self.assertEqual(filename, get_config_in_subdir(self.files[index:]))
  3162. with self.assertRaises(config.ComposeFileNotFound):
  3163. get_config_in_subdir([])
  3164. def get_config_filename_for_files(filenames, subdir=None):
  3165. def make_files(dirname, filenames):
  3166. for fname in filenames:
  3167. with open(os.path.join(dirname, fname), 'w') as f:
  3168. f.write('')
  3169. project_dir = tempfile.mkdtemp()
  3170. try:
  3171. make_files(project_dir, filenames)
  3172. if subdir:
  3173. base_dir = tempfile.mkdtemp(dir=project_dir)
  3174. else:
  3175. base_dir = project_dir
  3176. filename, = config.get_default_config_files(base_dir)
  3177. return os.path.basename(filename)
  3178. finally:
  3179. shutil.rmtree(project_dir)
  3180. class SerializeTest(unittest.TestCase):
  3181. def test_denormalize_depends_on_v3(self):
  3182. service_dict = {
  3183. 'image': 'busybox',
  3184. 'command': 'true',
  3185. 'depends_on': {
  3186. 'service2': {'condition': 'service_started'},
  3187. 'service3': {'condition': 'service_started'},
  3188. }
  3189. }
  3190. assert denormalize_service_dict(service_dict, V3_0) == {
  3191. 'image': 'busybox',
  3192. 'command': 'true',
  3193. 'depends_on': ['service2', 'service3']
  3194. }
  3195. def test_denormalize_depends_on_v2_1(self):
  3196. service_dict = {
  3197. 'image': 'busybox',
  3198. 'command': 'true',
  3199. 'depends_on': {
  3200. 'service2': {'condition': 'service_started'},
  3201. 'service3': {'condition': 'service_started'},
  3202. }
  3203. }
  3204. assert denormalize_service_dict(service_dict, V2_1) == service_dict
  3205. def test_serialize_time(self):
  3206. data = {
  3207. 9: '9ns',
  3208. 9000: '9us',
  3209. 9000000: '9ms',
  3210. 90000000: '90ms',
  3211. 900000000: '900ms',
  3212. 999999999: '999999999ns',
  3213. 1000000000: '1s',
  3214. 60000000000: '1m',
  3215. 60000000001: '60000000001ns',
  3216. 9000000000000: '150m',
  3217. 90000000000000: '25h',
  3218. }
  3219. for k, v in data.items():
  3220. assert serialize_ns_time_value(k) == v
  3221. def test_denormalize_healthcheck(self):
  3222. service_dict = {
  3223. 'image': 'test',
  3224. 'healthcheck': {
  3225. 'test': 'exit 1',
  3226. 'interval': '1m40s',
  3227. 'timeout': '30s',
  3228. 'retries': 5
  3229. }
  3230. }
  3231. processed_service = config.process_service(config.ServiceConfig(
  3232. '.', 'test', 'test', service_dict
  3233. ))
  3234. denormalized_service = denormalize_service_dict(processed_service, V2_1)
  3235. assert denormalized_service['healthcheck']['interval'] == '100s'
  3236. assert denormalized_service['healthcheck']['timeout'] == '30s'
  3237. def test_serialize_secrets(self):
  3238. service_dict = {
  3239. 'image': 'example/web',
  3240. 'secrets': [
  3241. {'source': 'one'},
  3242. {
  3243. 'source': 'source',
  3244. 'target': 'target',
  3245. 'uid': '100',
  3246. 'gid': '200',
  3247. 'mode': 0o777,
  3248. }
  3249. ]
  3250. }
  3251. config_dict = config.load(build_config_details({
  3252. 'version': '3.1',
  3253. 'services': {'web': service_dict}
  3254. }))
  3255. serialized_config = yaml.load(serialize_config(config_dict))
  3256. serialized_service = serialized_config['services']['web']
  3257. assert secret_sort(serialized_service['secrets']) == secret_sort(service_dict['secrets'])