config_test.py 160 KB

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