config_test.py 137 KB

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