config_test.py 154 KB

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