config_test.py 135 KB

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