config_test.py 157 KB

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