config_test.py 126 KB

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