config_test.py 154 KB

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