config_test.py 150 KB

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