config_test.py 164 KB

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