config_test.py 153 KB

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