config_test.py 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970
  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_heterogeneous_volumes(self):
  1468. base = {
  1469. 'volumes': ['/a:/b', '/x:/z'],
  1470. }
  1471. override = {
  1472. 'image': 'alpine:edge',
  1473. 'volumes': [
  1474. {'source': '/e', 'target': '/b', 'type': 'bind'},
  1475. {'source': '/c', 'target': '/d', 'type': 'bind'}
  1476. ]
  1477. }
  1478. actual = config.merge_service_dicts_from_files(
  1479. base, override, V3_2
  1480. )
  1481. assert actual['volumes'] == [
  1482. {'source': '/e', 'target': '/b', 'type': 'bind'},
  1483. {'source': '/c', 'target': '/d', 'type': 'bind'},
  1484. '/x:/z'
  1485. ]
  1486. def test_merge_logging_v1(self):
  1487. base = {
  1488. 'image': 'alpine:edge',
  1489. 'log_driver': 'something',
  1490. 'log_opt': {'foo': 'three'},
  1491. }
  1492. override = {
  1493. 'image': 'alpine:edge',
  1494. 'command': 'true',
  1495. }
  1496. actual = config.merge_service_dicts(base, override, V1)
  1497. assert actual == {
  1498. 'image': 'alpine:edge',
  1499. 'log_driver': 'something',
  1500. 'log_opt': {'foo': 'three'},
  1501. 'command': 'true',
  1502. }
  1503. def test_merge_logging_v2(self):
  1504. base = {
  1505. 'image': 'alpine:edge',
  1506. 'logging': {
  1507. 'driver': 'json-file',
  1508. 'options': {
  1509. 'frequency': '2000',
  1510. 'timeout': '23'
  1511. }
  1512. }
  1513. }
  1514. override = {
  1515. 'logging': {
  1516. 'options': {
  1517. 'timeout': '360',
  1518. 'pretty-print': 'on'
  1519. }
  1520. }
  1521. }
  1522. actual = config.merge_service_dicts(base, override, V2_0)
  1523. assert actual == {
  1524. 'image': 'alpine:edge',
  1525. 'logging': {
  1526. 'driver': 'json-file',
  1527. 'options': {
  1528. 'frequency': '2000',
  1529. 'timeout': '360',
  1530. 'pretty-print': 'on'
  1531. }
  1532. }
  1533. }
  1534. def test_merge_logging_v2_override_driver(self):
  1535. base = {
  1536. 'image': 'alpine:edge',
  1537. 'logging': {
  1538. 'driver': 'json-file',
  1539. 'options': {
  1540. 'frequency': '2000',
  1541. 'timeout': '23'
  1542. }
  1543. }
  1544. }
  1545. override = {
  1546. 'logging': {
  1547. 'driver': 'syslog',
  1548. 'options': {
  1549. 'timeout': '360',
  1550. 'pretty-print': 'on'
  1551. }
  1552. }
  1553. }
  1554. actual = config.merge_service_dicts(base, override, V2_0)
  1555. assert actual == {
  1556. 'image': 'alpine:edge',
  1557. 'logging': {
  1558. 'driver': 'syslog',
  1559. 'options': {
  1560. 'timeout': '360',
  1561. 'pretty-print': 'on'
  1562. }
  1563. }
  1564. }
  1565. def test_merge_logging_v2_no_base_driver(self):
  1566. base = {
  1567. 'image': 'alpine:edge',
  1568. 'logging': {
  1569. 'options': {
  1570. 'frequency': '2000',
  1571. 'timeout': '23'
  1572. }
  1573. }
  1574. }
  1575. override = {
  1576. 'logging': {
  1577. 'driver': 'json-file',
  1578. 'options': {
  1579. 'timeout': '360',
  1580. 'pretty-print': 'on'
  1581. }
  1582. }
  1583. }
  1584. actual = config.merge_service_dicts(base, override, V2_0)
  1585. assert actual == {
  1586. 'image': 'alpine:edge',
  1587. 'logging': {
  1588. 'driver': 'json-file',
  1589. 'options': {
  1590. 'frequency': '2000',
  1591. 'timeout': '360',
  1592. 'pretty-print': 'on'
  1593. }
  1594. }
  1595. }
  1596. def test_merge_logging_v2_no_drivers(self):
  1597. base = {
  1598. 'image': 'alpine:edge',
  1599. 'logging': {
  1600. 'options': {
  1601. 'frequency': '2000',
  1602. 'timeout': '23'
  1603. }
  1604. }
  1605. }
  1606. override = {
  1607. 'logging': {
  1608. 'options': {
  1609. 'timeout': '360',
  1610. 'pretty-print': 'on'
  1611. }
  1612. }
  1613. }
  1614. actual = config.merge_service_dicts(base, override, V2_0)
  1615. assert actual == {
  1616. 'image': 'alpine:edge',
  1617. 'logging': {
  1618. 'options': {
  1619. 'frequency': '2000',
  1620. 'timeout': '360',
  1621. 'pretty-print': 'on'
  1622. }
  1623. }
  1624. }
  1625. def test_merge_logging_v2_no_override_options(self):
  1626. base = {
  1627. 'image': 'alpine:edge',
  1628. 'logging': {
  1629. 'driver': 'json-file',
  1630. 'options': {
  1631. 'frequency': '2000',
  1632. 'timeout': '23'
  1633. }
  1634. }
  1635. }
  1636. override = {
  1637. 'logging': {
  1638. 'driver': 'syslog'
  1639. }
  1640. }
  1641. actual = config.merge_service_dicts(base, override, V2_0)
  1642. assert actual == {
  1643. 'image': 'alpine:edge',
  1644. 'logging': {
  1645. 'driver': 'syslog',
  1646. 'options': None
  1647. }
  1648. }
  1649. def test_merge_logging_v2_no_base(self):
  1650. base = {
  1651. 'image': 'alpine:edge'
  1652. }
  1653. override = {
  1654. 'logging': {
  1655. 'driver': 'json-file',
  1656. 'options': {
  1657. 'frequency': '2000'
  1658. }
  1659. }
  1660. }
  1661. actual = config.merge_service_dicts(base, override, V2_0)
  1662. assert actual == {
  1663. 'image': 'alpine:edge',
  1664. 'logging': {
  1665. 'driver': 'json-file',
  1666. 'options': {
  1667. 'frequency': '2000'
  1668. }
  1669. }
  1670. }
  1671. def test_merge_logging_v2_no_override(self):
  1672. base = {
  1673. 'image': 'alpine:edge',
  1674. 'logging': {
  1675. 'driver': 'syslog',
  1676. 'options': {
  1677. 'frequency': '2000'
  1678. }
  1679. }
  1680. }
  1681. override = {}
  1682. actual = config.merge_service_dicts(base, override, V2_0)
  1683. assert actual == {
  1684. 'image': 'alpine:edge',
  1685. 'logging': {
  1686. 'driver': 'syslog',
  1687. 'options': {
  1688. 'frequency': '2000'
  1689. }
  1690. }
  1691. }
  1692. def test_merge_mixed_ports(self):
  1693. base = {
  1694. 'image': 'busybox:latest',
  1695. 'command': 'top',
  1696. 'ports': [
  1697. {
  1698. 'target': '1245',
  1699. 'published': '1245',
  1700. 'protocol': 'tcp',
  1701. }
  1702. ]
  1703. }
  1704. override = {
  1705. 'ports': ['1245:1245/udp']
  1706. }
  1707. actual = config.merge_service_dicts(base, override, V3_1)
  1708. assert actual == {
  1709. 'image': 'busybox:latest',
  1710. 'command': 'top',
  1711. 'ports': [types.ServicePort('1245', '1245', 'udp', None, None)]
  1712. }
  1713. def test_merge_depends_on_no_override(self):
  1714. base = {
  1715. 'image': 'busybox',
  1716. 'depends_on': {
  1717. 'app1': {'condition': 'service_started'},
  1718. 'app2': {'condition': 'service_healthy'}
  1719. }
  1720. }
  1721. override = {}
  1722. actual = config.merge_service_dicts(base, override, V2_1)
  1723. assert actual == base
  1724. def test_merge_depends_on_mixed_syntax(self):
  1725. base = {
  1726. 'image': 'busybox',
  1727. 'depends_on': {
  1728. 'app1': {'condition': 'service_started'},
  1729. 'app2': {'condition': 'service_healthy'}
  1730. }
  1731. }
  1732. override = {
  1733. 'depends_on': ['app3']
  1734. }
  1735. actual = config.merge_service_dicts(base, override, V2_1)
  1736. assert actual == {
  1737. 'image': 'busybox',
  1738. 'depends_on': {
  1739. 'app1': {'condition': 'service_started'},
  1740. 'app2': {'condition': 'service_healthy'},
  1741. 'app3': {'condition': 'service_started'}
  1742. }
  1743. }
  1744. def test_empty_environment_key_allowed(self):
  1745. service_dict = config.load(
  1746. build_config_details(
  1747. {
  1748. 'web': {
  1749. 'build': '.',
  1750. 'environment': {
  1751. 'POSTGRES_PASSWORD': ''
  1752. },
  1753. },
  1754. },
  1755. '.',
  1756. None,
  1757. )
  1758. ).services[0]
  1759. self.assertEqual(service_dict['environment']['POSTGRES_PASSWORD'], '')
  1760. def test_merge_pid(self):
  1761. # Regression: https://github.com/docker/compose/issues/4184
  1762. base = {
  1763. 'image': 'busybox',
  1764. 'pid': 'host'
  1765. }
  1766. override = {
  1767. 'labels': {'com.docker.compose.test': 'yes'}
  1768. }
  1769. actual = config.merge_service_dicts(base, override, V2_0)
  1770. assert actual == {
  1771. 'image': 'busybox',
  1772. 'pid': 'host',
  1773. 'labels': {'com.docker.compose.test': 'yes'}
  1774. }
  1775. def test_merge_different_secrets(self):
  1776. base = {
  1777. 'image': 'busybox',
  1778. 'secrets': [
  1779. {'source': 'src.txt'}
  1780. ]
  1781. }
  1782. override = {'secrets': ['other-src.txt']}
  1783. actual = config.merge_service_dicts(base, override, V3_1)
  1784. assert secret_sort(actual['secrets']) == secret_sort([
  1785. {'source': 'src.txt'},
  1786. {'source': 'other-src.txt'}
  1787. ])
  1788. def test_merge_secrets_override(self):
  1789. base = {
  1790. 'image': 'busybox',
  1791. 'secrets': ['src.txt'],
  1792. }
  1793. override = {
  1794. 'secrets': [
  1795. {
  1796. 'source': 'src.txt',
  1797. 'target': 'data.txt',
  1798. 'mode': 0o400
  1799. }
  1800. ]
  1801. }
  1802. actual = config.merge_service_dicts(base, override, V3_1)
  1803. assert actual['secrets'] == override['secrets']
  1804. def test_merge_deploy(self):
  1805. base = {
  1806. 'image': 'busybox',
  1807. }
  1808. override = {
  1809. 'deploy': {
  1810. 'mode': 'global',
  1811. 'restart_policy': {
  1812. 'condition': 'on-failure'
  1813. }
  1814. }
  1815. }
  1816. actual = config.merge_service_dicts(base, override, V3_0)
  1817. assert actual['deploy'] == override['deploy']
  1818. def test_merge_deploy_override(self):
  1819. base = {
  1820. 'image': 'busybox',
  1821. 'deploy': {
  1822. 'mode': 'global',
  1823. 'restart_policy': {
  1824. 'condition': 'on-failure'
  1825. },
  1826. 'placement': {
  1827. 'constraints': [
  1828. 'node.role == manager'
  1829. ]
  1830. }
  1831. }
  1832. }
  1833. override = {
  1834. 'deploy': {
  1835. 'mode': 'replicated',
  1836. 'restart_policy': {
  1837. 'condition': 'any'
  1838. }
  1839. }
  1840. }
  1841. actual = config.merge_service_dicts(base, override, V3_0)
  1842. assert actual['deploy'] == {
  1843. 'mode': 'replicated',
  1844. 'restart_policy': {
  1845. 'condition': 'any'
  1846. },
  1847. 'placement': {
  1848. 'constraints': [
  1849. 'node.role == manager'
  1850. ]
  1851. }
  1852. }
  1853. def test_merge_credential_spec(self):
  1854. base = {
  1855. 'image': 'bb',
  1856. 'credential_spec': {
  1857. 'file': '/hello-world',
  1858. }
  1859. }
  1860. override = {
  1861. 'credential_spec': {
  1862. 'registry': 'revolution.com',
  1863. }
  1864. }
  1865. actual = config.merge_service_dicts(base, override, V3_3)
  1866. assert actual['credential_spec'] == override['credential_spec']
  1867. def test_external_volume_config(self):
  1868. config_details = build_config_details({
  1869. 'version': '2',
  1870. 'services': {
  1871. 'bogus': {'image': 'busybox'}
  1872. },
  1873. 'volumes': {
  1874. 'ext': {'external': True},
  1875. 'ext2': {'external': {'name': 'aliased'}}
  1876. }
  1877. })
  1878. config_result = config.load(config_details)
  1879. volumes = config_result.volumes
  1880. assert 'ext' in volumes
  1881. assert volumes['ext']['external'] is True
  1882. assert 'ext2' in volumes
  1883. assert volumes['ext2']['external']['name'] == 'aliased'
  1884. def test_external_volume_invalid_config(self):
  1885. config_details = build_config_details({
  1886. 'version': '2',
  1887. 'services': {
  1888. 'bogus': {'image': 'busybox'}
  1889. },
  1890. 'volumes': {
  1891. 'ext': {'external': True, 'driver': 'foo'}
  1892. }
  1893. })
  1894. with pytest.raises(ConfigurationError):
  1895. config.load(config_details)
  1896. def test_depends_on_orders_services(self):
  1897. config_details = build_config_details({
  1898. 'version': '2',
  1899. 'services': {
  1900. 'one': {'image': 'busybox', 'depends_on': ['three', 'two']},
  1901. 'two': {'image': 'busybox', 'depends_on': ['three']},
  1902. 'three': {'image': 'busybox'},
  1903. },
  1904. })
  1905. actual = config.load(config_details)
  1906. assert (
  1907. [service['name'] for service in actual.services] ==
  1908. ['three', 'two', 'one']
  1909. )
  1910. def test_depends_on_unknown_service_errors(self):
  1911. config_details = build_config_details({
  1912. 'version': '2',
  1913. 'services': {
  1914. 'one': {'image': 'busybox', 'depends_on': ['three']},
  1915. },
  1916. })
  1917. with pytest.raises(ConfigurationError) as exc:
  1918. config.load(config_details)
  1919. assert "Service 'one' depends on service 'three'" in exc.exconly()
  1920. def test_linked_service_is_undefined(self):
  1921. with self.assertRaises(ConfigurationError):
  1922. config.load(
  1923. build_config_details({
  1924. 'version': '2',
  1925. 'services': {
  1926. 'web': {'image': 'busybox', 'links': ['db:db']},
  1927. },
  1928. })
  1929. )
  1930. def test_load_dockerfile_without_context(self):
  1931. config_details = build_config_details({
  1932. 'version': '2',
  1933. 'services': {
  1934. 'one': {'build': {'dockerfile': 'Dockerfile.foo'}},
  1935. },
  1936. })
  1937. with pytest.raises(ConfigurationError) as exc:
  1938. config.load(config_details)
  1939. assert 'has neither an image nor a build context' in exc.exconly()
  1940. def test_load_secrets(self):
  1941. base_file = config.ConfigFile(
  1942. 'base.yaml',
  1943. {
  1944. 'version': '3.1',
  1945. 'services': {
  1946. 'web': {
  1947. 'image': 'example/web',
  1948. 'secrets': [
  1949. 'one',
  1950. {
  1951. 'source': 'source',
  1952. 'target': 'target',
  1953. 'uid': '100',
  1954. 'gid': '200',
  1955. 'mode': 0o777,
  1956. },
  1957. ],
  1958. },
  1959. },
  1960. 'secrets': {
  1961. 'one': {'file': 'secret.txt'},
  1962. },
  1963. })
  1964. details = config.ConfigDetails('.', [base_file])
  1965. service_dicts = config.load(details).services
  1966. expected = [
  1967. {
  1968. 'name': 'web',
  1969. 'image': 'example/web',
  1970. 'secrets': [
  1971. types.ServiceSecret('one', None, None, None, None),
  1972. types.ServiceSecret('source', 'target', '100', '200', 0o777),
  1973. ],
  1974. },
  1975. ]
  1976. assert service_sort(service_dicts) == service_sort(expected)
  1977. def test_load_secrets_multi_file(self):
  1978. base_file = config.ConfigFile(
  1979. 'base.yaml',
  1980. {
  1981. 'version': '3.1',
  1982. 'services': {
  1983. 'web': {
  1984. 'image': 'example/web',
  1985. 'secrets': ['one'],
  1986. },
  1987. },
  1988. 'secrets': {
  1989. 'one': {'file': 'secret.txt'},
  1990. },
  1991. })
  1992. override_file = config.ConfigFile(
  1993. 'base.yaml',
  1994. {
  1995. 'version': '3.1',
  1996. 'services': {
  1997. 'web': {
  1998. 'secrets': [
  1999. {
  2000. 'source': 'source',
  2001. 'target': 'target',
  2002. 'uid': '100',
  2003. 'gid': '200',
  2004. 'mode': 0o777,
  2005. },
  2006. ],
  2007. },
  2008. },
  2009. })
  2010. details = config.ConfigDetails('.', [base_file, override_file])
  2011. service_dicts = config.load(details).services
  2012. expected = [
  2013. {
  2014. 'name': 'web',
  2015. 'image': 'example/web',
  2016. 'secrets': [
  2017. types.ServiceSecret('one', None, None, None, None),
  2018. types.ServiceSecret('source', 'target', '100', '200', 0o777),
  2019. ],
  2020. },
  2021. ]
  2022. assert service_sort(service_dicts) == service_sort(expected)
  2023. class NetworkModeTest(unittest.TestCase):
  2024. def test_network_mode_standard(self):
  2025. config_data = config.load(build_config_details({
  2026. 'version': '2',
  2027. 'services': {
  2028. 'web': {
  2029. 'image': 'busybox',
  2030. 'command': "top",
  2031. 'network_mode': 'bridge',
  2032. },
  2033. },
  2034. }))
  2035. assert config_data.services[0]['network_mode'] == 'bridge'
  2036. def test_network_mode_standard_v1(self):
  2037. config_data = config.load(build_config_details({
  2038. 'web': {
  2039. 'image': 'busybox',
  2040. 'command': "top",
  2041. 'net': 'bridge',
  2042. },
  2043. }))
  2044. assert config_data.services[0]['network_mode'] == 'bridge'
  2045. assert 'net' not in config_data.services[0]
  2046. def test_network_mode_container(self):
  2047. config_data = config.load(build_config_details({
  2048. 'version': '2',
  2049. 'services': {
  2050. 'web': {
  2051. 'image': 'busybox',
  2052. 'command': "top",
  2053. 'network_mode': 'container:foo',
  2054. },
  2055. },
  2056. }))
  2057. assert config_data.services[0]['network_mode'] == 'container:foo'
  2058. def test_network_mode_container_v1(self):
  2059. config_data = config.load(build_config_details({
  2060. 'web': {
  2061. 'image': 'busybox',
  2062. 'command': "top",
  2063. 'net': 'container:foo',
  2064. },
  2065. }))
  2066. assert config_data.services[0]['network_mode'] == 'container:foo'
  2067. def test_network_mode_service(self):
  2068. config_data = config.load(build_config_details({
  2069. 'version': '2',
  2070. 'services': {
  2071. 'web': {
  2072. 'image': 'busybox',
  2073. 'command': "top",
  2074. 'network_mode': 'service:foo',
  2075. },
  2076. 'foo': {
  2077. 'image': 'busybox',
  2078. 'command': "top",
  2079. },
  2080. },
  2081. }))
  2082. assert config_data.services[1]['network_mode'] == 'service:foo'
  2083. def test_network_mode_service_v1(self):
  2084. config_data = config.load(build_config_details({
  2085. 'web': {
  2086. 'image': 'busybox',
  2087. 'command': "top",
  2088. 'net': 'container:foo',
  2089. },
  2090. 'foo': {
  2091. 'image': 'busybox',
  2092. 'command': "top",
  2093. },
  2094. }))
  2095. assert config_data.services[1]['network_mode'] == 'service:foo'
  2096. def test_network_mode_service_nonexistent(self):
  2097. with pytest.raises(ConfigurationError) as excinfo:
  2098. config.load(build_config_details({
  2099. 'version': '2',
  2100. 'services': {
  2101. 'web': {
  2102. 'image': 'busybox',
  2103. 'command': "top",
  2104. 'network_mode': 'service:foo',
  2105. },
  2106. },
  2107. }))
  2108. assert "service 'foo' which is undefined" in excinfo.exconly()
  2109. def test_network_mode_plus_networks_is_invalid(self):
  2110. with pytest.raises(ConfigurationError) as excinfo:
  2111. config.load(build_config_details({
  2112. 'version': '2',
  2113. 'services': {
  2114. 'web': {
  2115. 'image': 'busybox',
  2116. 'command': "top",
  2117. 'network_mode': 'bridge',
  2118. 'networks': ['front'],
  2119. },
  2120. },
  2121. 'networks': {
  2122. 'front': None,
  2123. }
  2124. }))
  2125. assert "'network_mode' and 'networks' cannot be combined" in excinfo.exconly()
  2126. class PortsTest(unittest.TestCase):
  2127. INVALID_PORTS_TYPES = [
  2128. {"1": "8000"},
  2129. False,
  2130. "8000",
  2131. 8000,
  2132. ]
  2133. NON_UNIQUE_SINGLE_PORTS = [
  2134. ["8000", "8000"],
  2135. ]
  2136. INVALID_PORT_MAPPINGS = [
  2137. ["8000-8004:8000-8002"],
  2138. ["4242:4242-4244"],
  2139. ]
  2140. VALID_SINGLE_PORTS = [
  2141. ["8000"],
  2142. ["8000/tcp"],
  2143. ["8000", "9000"],
  2144. [8000],
  2145. [8000, 9000],
  2146. ]
  2147. VALID_PORT_MAPPINGS = [
  2148. ["8000:8050"],
  2149. ["49153-49154:3002-3003"],
  2150. ]
  2151. def test_config_invalid_ports_type_validation(self):
  2152. for invalid_ports in self.INVALID_PORTS_TYPES:
  2153. with pytest.raises(ConfigurationError) as exc:
  2154. self.check_config({'ports': invalid_ports})
  2155. assert "contains an invalid type" in exc.value.msg
  2156. def test_config_non_unique_ports_validation(self):
  2157. for invalid_ports in self.NON_UNIQUE_SINGLE_PORTS:
  2158. with pytest.raises(ConfigurationError) as exc:
  2159. self.check_config({'ports': invalid_ports})
  2160. assert "non-unique" in exc.value.msg
  2161. def test_config_invalid_ports_format_validation(self):
  2162. for invalid_ports in self.INVALID_PORT_MAPPINGS:
  2163. with pytest.raises(ConfigurationError) as exc:
  2164. self.check_config({'ports': invalid_ports})
  2165. assert "Port ranges don't match in length" in exc.value.msg
  2166. def test_config_valid_ports_format_validation(self):
  2167. for valid_ports in self.VALID_SINGLE_PORTS + self.VALID_PORT_MAPPINGS:
  2168. self.check_config({'ports': valid_ports})
  2169. def test_config_invalid_expose_type_validation(self):
  2170. for invalid_expose in self.INVALID_PORTS_TYPES:
  2171. with pytest.raises(ConfigurationError) as exc:
  2172. self.check_config({'expose': invalid_expose})
  2173. assert "contains an invalid type" in exc.value.msg
  2174. def test_config_non_unique_expose_validation(self):
  2175. for invalid_expose in self.NON_UNIQUE_SINGLE_PORTS:
  2176. with pytest.raises(ConfigurationError) as exc:
  2177. self.check_config({'expose': invalid_expose})
  2178. assert "non-unique" in exc.value.msg
  2179. def test_config_invalid_expose_format_validation(self):
  2180. # Valid port mappings ARE NOT valid 'expose' entries
  2181. for invalid_expose in self.INVALID_PORT_MAPPINGS + self.VALID_PORT_MAPPINGS:
  2182. with pytest.raises(ConfigurationError) as exc:
  2183. self.check_config({'expose': invalid_expose})
  2184. assert "should be of the format" in exc.value.msg
  2185. def test_config_valid_expose_format_validation(self):
  2186. # Valid single ports ARE valid 'expose' entries
  2187. for valid_expose in self.VALID_SINGLE_PORTS:
  2188. self.check_config({'expose': valid_expose})
  2189. def check_config(self, cfg):
  2190. config.load(
  2191. build_config_details(
  2192. {'web': dict(image='busybox', **cfg)},
  2193. 'working_dir',
  2194. 'filename.yml'
  2195. )
  2196. )
  2197. class InterpolationTest(unittest.TestCase):
  2198. @mock.patch.dict(os.environ)
  2199. def test_config_file_with_environment_file(self):
  2200. project_dir = 'tests/fixtures/default-env-file'
  2201. service_dicts = config.load(
  2202. config.find(
  2203. project_dir, None, Environment.from_env_file(project_dir)
  2204. )
  2205. ).services
  2206. self.assertEqual(service_dicts[0], {
  2207. 'name': 'web',
  2208. 'image': 'alpine:latest',
  2209. 'ports': [
  2210. types.ServicePort.parse('5643')[0],
  2211. types.ServicePort.parse('9999')[0]
  2212. ],
  2213. 'command': 'true'
  2214. })
  2215. @mock.patch.dict(os.environ)
  2216. def test_config_file_with_environment_variable(self):
  2217. project_dir = 'tests/fixtures/environment-interpolation'
  2218. os.environ.update(
  2219. IMAGE="busybox",
  2220. HOST_PORT="80",
  2221. LABEL_VALUE="myvalue",
  2222. )
  2223. service_dicts = config.load(
  2224. config.find(
  2225. project_dir, None, Environment.from_env_file(project_dir)
  2226. )
  2227. ).services
  2228. self.assertEqual(service_dicts, [
  2229. {
  2230. 'name': 'web',
  2231. 'image': 'busybox',
  2232. 'ports': types.ServicePort.parse('80:8000'),
  2233. 'labels': {'mylabel': 'myvalue'},
  2234. 'hostname': 'host-',
  2235. 'command': '${ESCAPED}',
  2236. }
  2237. ])
  2238. @mock.patch.dict(os.environ)
  2239. def test_unset_variable_produces_warning(self):
  2240. os.environ.pop('FOO', None)
  2241. os.environ.pop('BAR', None)
  2242. config_details = build_config_details(
  2243. {
  2244. 'web': {
  2245. 'image': '${FOO}',
  2246. 'command': '${BAR}',
  2247. 'container_name': '${BAR}',
  2248. },
  2249. },
  2250. '.',
  2251. None,
  2252. )
  2253. with mock.patch('compose.config.environment.log') as log:
  2254. config.load(config_details)
  2255. self.assertEqual(2, log.warn.call_count)
  2256. warnings = sorted(args[0][0] for args in log.warn.call_args_list)
  2257. self.assertIn('BAR', warnings[0])
  2258. self.assertIn('FOO', warnings[1])
  2259. @mock.patch.dict(os.environ)
  2260. def test_invalid_interpolation(self):
  2261. with self.assertRaises(config.ConfigurationError) as cm:
  2262. config.load(
  2263. build_config_details(
  2264. {'web': {'image': '${'}},
  2265. 'working_dir',
  2266. 'filename.yml'
  2267. )
  2268. )
  2269. self.assertIn('Invalid', cm.exception.msg)
  2270. self.assertIn('for "image" option', cm.exception.msg)
  2271. self.assertIn('in service "web"', cm.exception.msg)
  2272. self.assertIn('"${"', cm.exception.msg)
  2273. @mock.patch.dict(os.environ)
  2274. def test_interpolation_secrets_section(self):
  2275. os.environ['FOO'] = 'baz.bar'
  2276. config_dict = config.load(build_config_details({
  2277. 'version': '3.1',
  2278. 'secrets': {
  2279. 'secretdata': {
  2280. 'external': {'name': '$FOO'}
  2281. }
  2282. }
  2283. }))
  2284. assert config_dict.secrets == {
  2285. 'secretdata': {
  2286. 'external': {'name': 'baz.bar'},
  2287. 'external_name': 'baz.bar'
  2288. }
  2289. }
  2290. class VolumeConfigTest(unittest.TestCase):
  2291. def test_no_binding(self):
  2292. d = make_service_dict('foo', {'build': '.', 'volumes': ['/data']}, working_dir='.')
  2293. self.assertEqual(d['volumes'], ['/data'])
  2294. @mock.patch.dict(os.environ)
  2295. def test_volume_binding_with_environment_variable(self):
  2296. os.environ['VOLUME_PATH'] = '/host/path'
  2297. d = config.load(
  2298. build_config_details(
  2299. {'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
  2300. '.',
  2301. None,
  2302. )
  2303. ).services[0]
  2304. self.assertEqual(d['volumes'], [VolumeSpec.parse('/host/path:/container/path')])
  2305. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  2306. @mock.patch.dict(os.environ)
  2307. def test_volume_binding_with_home(self):
  2308. os.environ['HOME'] = '/home/user'
  2309. d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
  2310. self.assertEqual(d['volumes'], ['/home/user:/container/path'])
  2311. def test_name_does_not_expand(self):
  2312. d = make_service_dict('foo', {'build': '.', 'volumes': ['mydatavolume:/data']}, working_dir='.')
  2313. self.assertEqual(d['volumes'], ['mydatavolume:/data'])
  2314. def test_absolute_posix_path_does_not_expand(self):
  2315. d = make_service_dict('foo', {'build': '.', 'volumes': ['/var/lib/data:/data']}, working_dir='.')
  2316. self.assertEqual(d['volumes'], ['/var/lib/data:/data'])
  2317. def test_absolute_windows_path_does_not_expand(self):
  2318. d = make_service_dict('foo', {'build': '.', 'volumes': ['c:\\data:/data']}, working_dir='.')
  2319. self.assertEqual(d['volumes'], ['c:\\data:/data'])
  2320. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  2321. def test_relative_path_does_expand_posix(self):
  2322. d = make_service_dict(
  2323. 'foo',
  2324. {'build': '.', 'volumes': ['./data:/data']},
  2325. working_dir='/home/me/myproject')
  2326. self.assertEqual(d['volumes'], ['/home/me/myproject/data:/data'])
  2327. d = make_service_dict(
  2328. 'foo',
  2329. {'build': '.', 'volumes': ['.:/data']},
  2330. working_dir='/home/me/myproject')
  2331. self.assertEqual(d['volumes'], ['/home/me/myproject:/data'])
  2332. d = make_service_dict(
  2333. 'foo',
  2334. {'build': '.', 'volumes': ['../otherproject:/data']},
  2335. working_dir='/home/me/myproject')
  2336. self.assertEqual(d['volumes'], ['/home/me/otherproject:/data'])
  2337. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='windows paths')
  2338. def test_relative_path_does_expand_windows(self):
  2339. d = make_service_dict(
  2340. 'foo',
  2341. {'build': '.', 'volumes': ['./data:/data']},
  2342. working_dir='c:\\Users\\me\\myproject')
  2343. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject\\data:/data'])
  2344. d = make_service_dict(
  2345. 'foo',
  2346. {'build': '.', 'volumes': ['.:/data']},
  2347. working_dir='c:\\Users\\me\\myproject')
  2348. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject:/data'])
  2349. d = make_service_dict(
  2350. 'foo',
  2351. {'build': '.', 'volumes': ['../otherproject:/data']},
  2352. working_dir='c:\\Users\\me\\myproject')
  2353. self.assertEqual(d['volumes'], ['c:\\Users\\me\\otherproject:/data'])
  2354. @mock.patch.dict(os.environ)
  2355. def test_home_directory_with_driver_does_not_expand(self):
  2356. os.environ['NAME'] = 'surprise!'
  2357. d = make_service_dict('foo', {
  2358. 'build': '.',
  2359. 'volumes': ['~:/data'],
  2360. 'volume_driver': 'foodriver',
  2361. }, working_dir='.')
  2362. self.assertEqual(d['volumes'], ['~:/data'])
  2363. def test_volume_path_with_non_ascii_directory(self):
  2364. volume = u'/Füü/data:/data'
  2365. container_path = config.resolve_volume_path(".", volume)
  2366. self.assertEqual(container_path, volume)
  2367. class MergePathMappingTest(object):
  2368. config_name = ""
  2369. def test_empty(self):
  2370. service_dict = config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  2371. assert self.config_name not in service_dict
  2372. def test_no_override(self):
  2373. service_dict = config.merge_service_dicts(
  2374. {self.config_name: ['/foo:/code', '/data']},
  2375. {},
  2376. DEFAULT_VERSION)
  2377. assert set(service_dict[self.config_name]) == set(['/foo:/code', '/data'])
  2378. def test_no_base(self):
  2379. service_dict = config.merge_service_dicts(
  2380. {},
  2381. {self.config_name: ['/bar:/code']},
  2382. DEFAULT_VERSION)
  2383. assert set(service_dict[self.config_name]) == set(['/bar:/code'])
  2384. def test_override_explicit_path(self):
  2385. service_dict = config.merge_service_dicts(
  2386. {self.config_name: ['/foo:/code', '/data']},
  2387. {self.config_name: ['/bar:/code']},
  2388. DEFAULT_VERSION)
  2389. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  2390. def test_add_explicit_path(self):
  2391. service_dict = config.merge_service_dicts(
  2392. {self.config_name: ['/foo:/code', '/data']},
  2393. {self.config_name: ['/bar:/code', '/quux:/data']},
  2394. DEFAULT_VERSION)
  2395. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/quux:/data'])
  2396. def test_remove_explicit_path(self):
  2397. service_dict = config.merge_service_dicts(
  2398. {self.config_name: ['/foo:/code', '/quux:/data']},
  2399. {self.config_name: ['/bar:/code', '/data']},
  2400. DEFAULT_VERSION)
  2401. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  2402. class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
  2403. config_name = 'volumes'
  2404. class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
  2405. config_name = 'devices'
  2406. class BuildOrImageMergeTest(unittest.TestCase):
  2407. def test_merge_build_or_image_no_override(self):
  2408. self.assertEqual(
  2409. config.merge_service_dicts({'build': '.'}, {}, V1),
  2410. {'build': '.'},
  2411. )
  2412. self.assertEqual(
  2413. config.merge_service_dicts({'image': 'redis'}, {}, V1),
  2414. {'image': 'redis'},
  2415. )
  2416. def test_merge_build_or_image_override_with_same(self):
  2417. self.assertEqual(
  2418. config.merge_service_dicts({'build': '.'}, {'build': './web'}, V1),
  2419. {'build': './web'},
  2420. )
  2421. self.assertEqual(
  2422. config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}, V1),
  2423. {'image': 'postgres'},
  2424. )
  2425. def test_merge_build_or_image_override_with_other(self):
  2426. self.assertEqual(
  2427. config.merge_service_dicts({'build': '.'}, {'image': 'redis'}, V1),
  2428. {'image': 'redis'},
  2429. )
  2430. self.assertEqual(
  2431. config.merge_service_dicts({'image': 'redis'}, {'build': '.'}, V1),
  2432. {'build': '.'}
  2433. )
  2434. class MergeListsTest(object):
  2435. config_name = ""
  2436. base_config = []
  2437. override_config = []
  2438. def merged_config(self):
  2439. return set(self.base_config) | set(self.override_config)
  2440. def test_empty(self):
  2441. assert self.config_name not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  2442. def test_no_override(self):
  2443. service_dict = config.merge_service_dicts(
  2444. {self.config_name: self.base_config},
  2445. {},
  2446. DEFAULT_VERSION)
  2447. assert set(service_dict[self.config_name]) == set(self.base_config)
  2448. def test_no_base(self):
  2449. service_dict = config.merge_service_dicts(
  2450. {},
  2451. {self.config_name: self.base_config},
  2452. DEFAULT_VERSION)
  2453. assert set(service_dict[self.config_name]) == set(self.base_config)
  2454. def test_add_item(self):
  2455. service_dict = config.merge_service_dicts(
  2456. {self.config_name: self.base_config},
  2457. {self.config_name: self.override_config},
  2458. DEFAULT_VERSION)
  2459. assert set(service_dict[self.config_name]) == set(self.merged_config())
  2460. class MergePortsTest(unittest.TestCase, MergeListsTest):
  2461. config_name = 'ports'
  2462. base_config = ['10:8000', '9000']
  2463. override_config = ['20:8000']
  2464. def merged_config(self):
  2465. return self.convert(self.base_config) | self.convert(self.override_config)
  2466. def convert(self, port_config):
  2467. return set(config.merge_service_dicts(
  2468. {self.config_name: port_config},
  2469. {self.config_name: []},
  2470. DEFAULT_VERSION
  2471. )[self.config_name])
  2472. def test_duplicate_port_mappings(self):
  2473. service_dict = config.merge_service_dicts(
  2474. {self.config_name: self.base_config},
  2475. {self.config_name: self.base_config},
  2476. DEFAULT_VERSION
  2477. )
  2478. assert set(service_dict[self.config_name]) == self.convert(self.base_config)
  2479. def test_no_override(self):
  2480. service_dict = config.merge_service_dicts(
  2481. {self.config_name: self.base_config},
  2482. {},
  2483. DEFAULT_VERSION)
  2484. assert set(service_dict[self.config_name]) == self.convert(self.base_config)
  2485. def test_no_base(self):
  2486. service_dict = config.merge_service_dicts(
  2487. {},
  2488. {self.config_name: self.base_config},
  2489. DEFAULT_VERSION)
  2490. assert set(service_dict[self.config_name]) == self.convert(self.base_config)
  2491. class MergeNetworksTest(unittest.TestCase, MergeListsTest):
  2492. config_name = 'networks'
  2493. base_config = ['frontend', 'backend']
  2494. override_config = ['monitoring']
  2495. class MergeStringsOrListsTest(unittest.TestCase):
  2496. def test_no_override(self):
  2497. service_dict = config.merge_service_dicts(
  2498. {'dns': '8.8.8.8'},
  2499. {},
  2500. DEFAULT_VERSION)
  2501. assert set(service_dict['dns']) == set(['8.8.8.8'])
  2502. def test_no_base(self):
  2503. service_dict = config.merge_service_dicts(
  2504. {},
  2505. {'dns': '8.8.8.8'},
  2506. DEFAULT_VERSION)
  2507. assert set(service_dict['dns']) == set(['8.8.8.8'])
  2508. def test_add_string(self):
  2509. service_dict = config.merge_service_dicts(
  2510. {'dns': ['8.8.8.8']},
  2511. {'dns': '9.9.9.9'},
  2512. DEFAULT_VERSION)
  2513. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  2514. def test_add_list(self):
  2515. service_dict = config.merge_service_dicts(
  2516. {'dns': '8.8.8.8'},
  2517. {'dns': ['9.9.9.9']},
  2518. DEFAULT_VERSION)
  2519. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  2520. class MergeLabelsTest(unittest.TestCase):
  2521. def test_empty(self):
  2522. assert 'labels' not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  2523. def test_no_override(self):
  2524. service_dict = config.merge_service_dicts(
  2525. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2526. make_service_dict('foo', {'build': '.'}, 'tests/'),
  2527. DEFAULT_VERSION)
  2528. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  2529. def test_no_base(self):
  2530. service_dict = config.merge_service_dicts(
  2531. make_service_dict('foo', {'build': '.'}, 'tests/'),
  2532. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  2533. DEFAULT_VERSION)
  2534. assert service_dict['labels'] == {'foo': '2'}
  2535. def test_override_explicit_value(self):
  2536. service_dict = config.merge_service_dicts(
  2537. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2538. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  2539. DEFAULT_VERSION)
  2540. assert service_dict['labels'] == {'foo': '2', 'bar': ''}
  2541. def test_add_explicit_value(self):
  2542. service_dict = config.merge_service_dicts(
  2543. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2544. make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
  2545. DEFAULT_VERSION)
  2546. assert service_dict['labels'] == {'foo': '1', 'bar': '2'}
  2547. def test_remove_explicit_value(self):
  2548. service_dict = config.merge_service_dicts(
  2549. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
  2550. make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
  2551. DEFAULT_VERSION)
  2552. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  2553. class MergeBuildTest(unittest.TestCase):
  2554. def test_full(self):
  2555. base = {
  2556. 'context': '.',
  2557. 'dockerfile': 'Dockerfile',
  2558. 'args': {
  2559. 'x': '1',
  2560. 'y': '2',
  2561. },
  2562. 'cache_from': ['ubuntu'],
  2563. 'labels': ['com.docker.compose.test=true']
  2564. }
  2565. override = {
  2566. 'context': './prod',
  2567. 'dockerfile': 'Dockerfile.prod',
  2568. 'args': ['x=12'],
  2569. 'cache_from': ['debian'],
  2570. 'labels': {
  2571. 'com.docker.compose.test': 'false',
  2572. 'com.docker.compose.prod': 'true',
  2573. }
  2574. }
  2575. result = config.merge_build(None, {'build': base}, {'build': override})
  2576. assert result['context'] == override['context']
  2577. assert result['dockerfile'] == override['dockerfile']
  2578. assert result['args'] == {'x': '12', 'y': '2'}
  2579. assert set(result['cache_from']) == set(['ubuntu', 'debian'])
  2580. assert result['labels'] == override['labels']
  2581. def test_empty_override(self):
  2582. base = {
  2583. 'context': '.',
  2584. 'dockerfile': 'Dockerfile',
  2585. 'args': {
  2586. 'x': '1',
  2587. 'y': '2',
  2588. },
  2589. 'cache_from': ['ubuntu'],
  2590. 'labels': {
  2591. 'com.docker.compose.test': 'true'
  2592. }
  2593. }
  2594. override = {}
  2595. result = config.merge_build(None, {'build': base}, {'build': override})
  2596. assert result == base
  2597. def test_empty_base(self):
  2598. base = {}
  2599. override = {
  2600. 'context': './prod',
  2601. 'dockerfile': 'Dockerfile.prod',
  2602. 'args': {'x': '12'},
  2603. 'cache_from': ['debian'],
  2604. 'labels': {
  2605. 'com.docker.compose.test': 'false',
  2606. 'com.docker.compose.prod': 'true',
  2607. }
  2608. }
  2609. result = config.merge_build(None, {'build': base}, {'build': override})
  2610. assert result == override
  2611. class MemoryOptionsTest(unittest.TestCase):
  2612. def test_validation_fails_with_just_memswap_limit(self):
  2613. """
  2614. When you set a 'memswap_limit' it is invalid config unless you also set
  2615. a mem_limit
  2616. """
  2617. with pytest.raises(ConfigurationError) as excinfo:
  2618. config.load(
  2619. build_config_details(
  2620. {
  2621. 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
  2622. },
  2623. 'tests/fixtures/extends',
  2624. 'filename.yml'
  2625. )
  2626. )
  2627. assert "foo.memswap_limit is invalid: when defining " \
  2628. "'memswap_limit' you must set 'mem_limit' as well" \
  2629. in excinfo.exconly()
  2630. def test_validation_with_correct_memswap_values(self):
  2631. service_dict = config.load(
  2632. build_config_details(
  2633. {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
  2634. 'tests/fixtures/extends',
  2635. 'common.yml'
  2636. )
  2637. ).services
  2638. self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
  2639. def test_memswap_can_be_a_string(self):
  2640. service_dict = config.load(
  2641. build_config_details(
  2642. {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
  2643. 'tests/fixtures/extends',
  2644. 'common.yml'
  2645. )
  2646. ).services
  2647. self.assertEqual(service_dict[0]['memswap_limit'], "512M")
  2648. class EnvTest(unittest.TestCase):
  2649. def test_parse_environment_as_list(self):
  2650. environment = [
  2651. 'NORMAL=F1',
  2652. 'CONTAINS_EQUALS=F=2',
  2653. 'TRAILING_EQUALS=',
  2654. ]
  2655. self.assertEqual(
  2656. config.parse_environment(environment),
  2657. {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
  2658. )
  2659. def test_parse_environment_as_dict(self):
  2660. environment = {
  2661. 'NORMAL': 'F1',
  2662. 'CONTAINS_EQUALS': 'F=2',
  2663. 'TRAILING_EQUALS': None,
  2664. }
  2665. self.assertEqual(config.parse_environment(environment), environment)
  2666. def test_parse_environment_invalid(self):
  2667. with self.assertRaises(ConfigurationError):
  2668. config.parse_environment('a=b')
  2669. def test_parse_environment_empty(self):
  2670. self.assertEqual(config.parse_environment(None), {})
  2671. @mock.patch.dict(os.environ)
  2672. def test_resolve_environment(self):
  2673. os.environ['FILE_DEF'] = 'E1'
  2674. os.environ['FILE_DEF_EMPTY'] = 'E2'
  2675. os.environ['ENV_DEF'] = 'E3'
  2676. service_dict = {
  2677. 'build': '.',
  2678. 'environment': {
  2679. 'FILE_DEF': 'F1',
  2680. 'FILE_DEF_EMPTY': '',
  2681. 'ENV_DEF': None,
  2682. 'NO_DEF': None
  2683. },
  2684. }
  2685. self.assertEqual(
  2686. resolve_environment(
  2687. service_dict, Environment.from_env_file(None)
  2688. ),
  2689. {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None},
  2690. )
  2691. def test_resolve_environment_from_env_file(self):
  2692. self.assertEqual(
  2693. resolve_environment({'env_file': ['tests/fixtures/env/one.env']}),
  2694. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
  2695. )
  2696. def test_environment_overrides_env_file(self):
  2697. self.assertEqual(
  2698. resolve_environment({
  2699. 'environment': {'FOO': 'baz'},
  2700. 'env_file': ['tests/fixtures/env/one.env'],
  2701. }),
  2702. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz'},
  2703. )
  2704. def test_resolve_environment_with_multiple_env_files(self):
  2705. service_dict = {
  2706. 'env_file': [
  2707. 'tests/fixtures/env/one.env',
  2708. 'tests/fixtures/env/two.env'
  2709. ]
  2710. }
  2711. self.assertEqual(
  2712. resolve_environment(service_dict),
  2713. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
  2714. )
  2715. def test_resolve_environment_nonexistent_file(self):
  2716. with pytest.raises(ConfigurationError) as exc:
  2717. config.load(build_config_details(
  2718. {'foo': {'image': 'example', 'env_file': 'nonexistent.env'}},
  2719. working_dir='tests/fixtures/env'))
  2720. assert 'Couldn\'t find env file' in exc.exconly()
  2721. assert 'nonexistent.env' in exc.exconly()
  2722. @mock.patch.dict(os.environ)
  2723. def test_resolve_environment_from_env_file_with_empty_values(self):
  2724. os.environ['FILE_DEF'] = 'E1'
  2725. os.environ['FILE_DEF_EMPTY'] = 'E2'
  2726. os.environ['ENV_DEF'] = 'E3'
  2727. self.assertEqual(
  2728. resolve_environment(
  2729. {'env_file': ['tests/fixtures/env/resolve.env']},
  2730. Environment.from_env_file(None)
  2731. ),
  2732. {
  2733. 'FILE_DEF': u'bär',
  2734. 'FILE_DEF_EMPTY': '',
  2735. 'ENV_DEF': 'E3',
  2736. 'NO_DEF': None
  2737. },
  2738. )
  2739. @mock.patch.dict(os.environ)
  2740. def test_resolve_build_args(self):
  2741. os.environ['env_arg'] = 'value2'
  2742. build = {
  2743. 'context': '.',
  2744. 'args': {
  2745. 'arg1': 'value1',
  2746. 'empty_arg': '',
  2747. 'env_arg': None,
  2748. 'no_env': None
  2749. }
  2750. }
  2751. self.assertEqual(
  2752. resolve_build_args(build['args'], Environment.from_env_file(build['context'])),
  2753. {'arg1': 'value1', 'empty_arg': '', 'env_arg': 'value2', 'no_env': None},
  2754. )
  2755. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2756. @mock.patch.dict(os.environ)
  2757. def test_resolve_path(self):
  2758. os.environ['HOSTENV'] = '/tmp'
  2759. os.environ['CONTAINERENV'] = '/host/tmp'
  2760. service_dict = config.load(
  2761. build_config_details(
  2762. {'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
  2763. "tests/fixtures/env",
  2764. )
  2765. ).services[0]
  2766. self.assertEqual(
  2767. set(service_dict['volumes']),
  2768. set([VolumeSpec.parse('/tmp:/host/tmp')]))
  2769. service_dict = config.load(
  2770. build_config_details(
  2771. {'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
  2772. "tests/fixtures/env",
  2773. )
  2774. ).services[0]
  2775. self.assertEqual(
  2776. set(service_dict['volumes']),
  2777. set([VolumeSpec.parse('/opt/tmp:/opt/host/tmp')]))
  2778. def load_from_filename(filename, override_dir=None):
  2779. return config.load(
  2780. config.find('.', [filename], Environment.from_env_file('.'), override_dir=override_dir)
  2781. ).services
  2782. class ExtendsTest(unittest.TestCase):
  2783. def test_extends(self):
  2784. service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
  2785. self.assertEqual(service_sort(service_dicts), service_sort([
  2786. {
  2787. 'name': 'mydb',
  2788. 'image': 'busybox',
  2789. 'command': 'top',
  2790. },
  2791. {
  2792. 'name': 'myweb',
  2793. 'image': 'busybox',
  2794. 'command': 'top',
  2795. 'network_mode': 'bridge',
  2796. 'links': ['mydb:db'],
  2797. 'environment': {
  2798. "FOO": "1",
  2799. "BAR": "2",
  2800. "BAZ": "2",
  2801. },
  2802. }
  2803. ]))
  2804. def test_merging_env_labels_ulimits(self):
  2805. service_dicts = load_from_filename('tests/fixtures/extends/common-env-labels-ulimits.yml')
  2806. self.assertEqual(service_sort(service_dicts), service_sort([
  2807. {
  2808. 'name': 'web',
  2809. 'image': 'busybox',
  2810. 'command': '/bin/true',
  2811. 'network_mode': 'host',
  2812. 'environment': {
  2813. "FOO": "2",
  2814. "BAR": "1",
  2815. "BAZ": "3",
  2816. },
  2817. 'labels': {'label': 'one'},
  2818. 'ulimits': {'nproc': 65535, 'memlock': {'soft': 1024, 'hard': 2048}}
  2819. }
  2820. ]))
  2821. def test_nested(self):
  2822. service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
  2823. self.assertEqual(service_dicts, [
  2824. {
  2825. 'name': 'myweb',
  2826. 'image': 'busybox',
  2827. 'command': '/bin/true',
  2828. 'network_mode': 'host',
  2829. 'environment': {
  2830. "FOO": "2",
  2831. "BAR": "2",
  2832. },
  2833. },
  2834. ])
  2835. def test_self_referencing_file(self):
  2836. """
  2837. We specify a 'file' key that is the filename we're already in.
  2838. """
  2839. service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
  2840. self.assertEqual(service_sort(service_dicts), service_sort([
  2841. {
  2842. 'environment':
  2843. {
  2844. 'YEP': '1', 'BAR': '1', 'BAZ': '3'
  2845. },
  2846. 'image': 'busybox',
  2847. 'name': 'myweb'
  2848. },
  2849. {
  2850. 'environment':
  2851. {'YEP': '1'},
  2852. 'image': 'busybox',
  2853. 'name': 'otherweb'
  2854. },
  2855. {
  2856. 'environment':
  2857. {'YEP': '1', 'BAZ': '3'},
  2858. 'image': 'busybox',
  2859. 'name': 'web'
  2860. }
  2861. ]))
  2862. def test_circular(self):
  2863. with pytest.raises(config.CircularReference) as exc:
  2864. load_from_filename('tests/fixtures/extends/circle-1.yml')
  2865. path = [
  2866. (os.path.basename(filename), service_name)
  2867. for (filename, service_name) in exc.value.trail
  2868. ]
  2869. expected = [
  2870. ('circle-1.yml', 'web'),
  2871. ('circle-2.yml', 'other'),
  2872. ('circle-1.yml', 'web'),
  2873. ]
  2874. self.assertEqual(path, expected)
  2875. def test_extends_validation_empty_dictionary(self):
  2876. with pytest.raises(ConfigurationError) as excinfo:
  2877. config.load(
  2878. build_config_details(
  2879. {
  2880. 'web': {'image': 'busybox', 'extends': {}},
  2881. },
  2882. 'tests/fixtures/extends',
  2883. 'filename.yml'
  2884. )
  2885. )
  2886. assert 'service' in excinfo.exconly()
  2887. def test_extends_validation_missing_service_key(self):
  2888. with pytest.raises(ConfigurationError) as excinfo:
  2889. config.load(
  2890. build_config_details(
  2891. {
  2892. 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
  2893. },
  2894. 'tests/fixtures/extends',
  2895. 'filename.yml'
  2896. )
  2897. )
  2898. assert "'service' is a required property" in excinfo.exconly()
  2899. def test_extends_validation_invalid_key(self):
  2900. with pytest.raises(ConfigurationError) as excinfo:
  2901. config.load(
  2902. build_config_details(
  2903. {
  2904. 'web': {
  2905. 'image': 'busybox',
  2906. 'extends': {
  2907. 'file': 'common.yml',
  2908. 'service': 'web',
  2909. 'rogue_key': 'is not allowed'
  2910. }
  2911. },
  2912. },
  2913. 'tests/fixtures/extends',
  2914. 'filename.yml'
  2915. )
  2916. )
  2917. assert "web.extends contains unsupported option: 'rogue_key'" \
  2918. in excinfo.exconly()
  2919. def test_extends_validation_sub_property_key(self):
  2920. with pytest.raises(ConfigurationError) as excinfo:
  2921. config.load(
  2922. build_config_details(
  2923. {
  2924. 'web': {
  2925. 'image': 'busybox',
  2926. 'extends': {
  2927. 'file': 1,
  2928. 'service': 'web',
  2929. }
  2930. },
  2931. },
  2932. 'tests/fixtures/extends',
  2933. 'filename.yml'
  2934. )
  2935. )
  2936. assert "web.extends.file contains 1, which is an invalid type, it should be a string" \
  2937. in excinfo.exconly()
  2938. def test_extends_validation_no_file_key_no_filename_set(self):
  2939. dictionary = {'extends': {'service': 'web'}}
  2940. with pytest.raises(ConfigurationError) as excinfo:
  2941. make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
  2942. assert 'file' in excinfo.exconly()
  2943. def test_extends_validation_valid_config(self):
  2944. service = config.load(
  2945. build_config_details(
  2946. {
  2947. 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
  2948. },
  2949. 'tests/fixtures/extends',
  2950. 'common.yml'
  2951. )
  2952. ).services
  2953. self.assertEqual(len(service), 1)
  2954. self.assertIsInstance(service[0], dict)
  2955. self.assertEqual(service[0]['command'], "/bin/true")
  2956. def test_extended_service_with_invalid_config(self):
  2957. with pytest.raises(ConfigurationError) as exc:
  2958. load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
  2959. assert (
  2960. "myweb has neither an image nor a build context specified" in
  2961. exc.exconly()
  2962. )
  2963. def test_extended_service_with_valid_config(self):
  2964. service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
  2965. self.assertEqual(service[0]['command'], "top")
  2966. def test_extends_file_defaults_to_self(self):
  2967. """
  2968. Test not specifying a file in our extends options that the
  2969. config is valid and correctly extends from itself.
  2970. """
  2971. service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
  2972. self.assertEqual(service_sort(service_dicts), service_sort([
  2973. {
  2974. 'name': 'myweb',
  2975. 'image': 'busybox',
  2976. 'environment': {
  2977. "BAR": "1",
  2978. "BAZ": "3",
  2979. }
  2980. },
  2981. {
  2982. 'name': 'web',
  2983. 'image': 'busybox',
  2984. 'environment': {
  2985. "BAZ": "3",
  2986. }
  2987. }
  2988. ]))
  2989. def test_invalid_links_in_extended_service(self):
  2990. with pytest.raises(ConfigurationError) as excinfo:
  2991. load_from_filename('tests/fixtures/extends/invalid-links.yml')
  2992. assert "services with 'links' cannot be extended" in excinfo.exconly()
  2993. def test_invalid_volumes_from_in_extended_service(self):
  2994. with pytest.raises(ConfigurationError) as excinfo:
  2995. load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
  2996. assert "services with 'volumes_from' cannot be extended" in excinfo.exconly()
  2997. def test_invalid_net_in_extended_service(self):
  2998. with pytest.raises(ConfigurationError) as excinfo:
  2999. load_from_filename('tests/fixtures/extends/invalid-net-v2.yml')
  3000. assert 'network_mode: service' in excinfo.exconly()
  3001. assert 'cannot be extended' in excinfo.exconly()
  3002. with pytest.raises(ConfigurationError) as excinfo:
  3003. load_from_filename('tests/fixtures/extends/invalid-net.yml')
  3004. assert 'net: container' in excinfo.exconly()
  3005. assert 'cannot be extended' in excinfo.exconly()
  3006. @mock.patch.dict(os.environ)
  3007. def test_load_config_runs_interpolation_in_extended_service(self):
  3008. os.environ.update(HOSTNAME_VALUE="penguin")
  3009. expected_interpolated_value = "host-penguin"
  3010. service_dicts = load_from_filename(
  3011. 'tests/fixtures/extends/valid-interpolation.yml')
  3012. for service in service_dicts:
  3013. assert service['hostname'] == expected_interpolated_value
  3014. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  3015. def test_volume_path(self):
  3016. dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
  3017. paths = [
  3018. VolumeSpec(
  3019. os.path.abspath('tests/fixtures/volume-path/common/foo'),
  3020. '/foo',
  3021. 'rw'),
  3022. VolumeSpec(
  3023. os.path.abspath('tests/fixtures/volume-path/bar'),
  3024. '/bar',
  3025. 'rw')
  3026. ]
  3027. self.assertEqual(set(dicts[0]['volumes']), set(paths))
  3028. def test_parent_build_path_dne(self):
  3029. child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
  3030. self.assertEqual(child, [
  3031. {
  3032. 'name': 'dnechild',
  3033. 'image': 'busybox',
  3034. 'command': '/bin/true',
  3035. 'environment': {
  3036. "FOO": "1",
  3037. "BAR": "2",
  3038. },
  3039. },
  3040. ])
  3041. def test_load_throws_error_when_base_service_does_not_exist(self):
  3042. with pytest.raises(ConfigurationError) as excinfo:
  3043. load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
  3044. assert "Cannot extend service 'foo'" in excinfo.exconly()
  3045. assert "Service not found" in excinfo.exconly()
  3046. def test_partial_service_config_in_extends_is_still_valid(self):
  3047. dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
  3048. self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
  3049. def test_extended_service_with_verbose_and_shorthand_way(self):
  3050. services = load_from_filename('tests/fixtures/extends/verbose-and-shorthand.yml')
  3051. self.assertEqual(service_sort(services), service_sort([
  3052. {
  3053. 'name': 'base',
  3054. 'image': 'busybox',
  3055. 'environment': {'BAR': '1'},
  3056. },
  3057. {
  3058. 'name': 'verbose',
  3059. 'image': 'busybox',
  3060. 'environment': {'BAR': '1', 'FOO': '1'},
  3061. },
  3062. {
  3063. 'name': 'shorthand',
  3064. 'image': 'busybox',
  3065. 'environment': {'BAR': '1', 'FOO': '2'},
  3066. },
  3067. ]))
  3068. @mock.patch.dict(os.environ)
  3069. def test_extends_with_environment_and_env_files(self):
  3070. tmpdir = py.test.ensuretemp('test_extends_with_environment')
  3071. self.addCleanup(tmpdir.remove)
  3072. commondir = tmpdir.mkdir('common')
  3073. commondir.join('base.yml').write("""
  3074. app:
  3075. image: 'example/app'
  3076. env_file:
  3077. - 'envs'
  3078. environment:
  3079. - SECRET
  3080. - TEST_ONE=common
  3081. - TEST_TWO=common
  3082. """)
  3083. tmpdir.join('docker-compose.yml').write("""
  3084. ext:
  3085. extends:
  3086. file: common/base.yml
  3087. service: app
  3088. env_file:
  3089. - 'envs'
  3090. environment:
  3091. - THING
  3092. - TEST_ONE=top
  3093. """)
  3094. commondir.join('envs').write("""
  3095. COMMON_ENV_FILE
  3096. TEST_ONE=common-env-file
  3097. TEST_TWO=common-env-file
  3098. TEST_THREE=common-env-file
  3099. TEST_FOUR=common-env-file
  3100. """)
  3101. tmpdir.join('envs').write("""
  3102. TOP_ENV_FILE
  3103. TEST_ONE=top-env-file
  3104. TEST_TWO=top-env-file
  3105. TEST_THREE=top-env-file
  3106. """)
  3107. expected = [
  3108. {
  3109. 'name': 'ext',
  3110. 'image': 'example/app',
  3111. 'environment': {
  3112. 'SECRET': 'secret',
  3113. 'TOP_ENV_FILE': 'secret',
  3114. 'COMMON_ENV_FILE': 'secret',
  3115. 'THING': 'thing',
  3116. 'TEST_ONE': 'top',
  3117. 'TEST_TWO': 'common',
  3118. 'TEST_THREE': 'top-env-file',
  3119. 'TEST_FOUR': 'common-env-file',
  3120. },
  3121. },
  3122. ]
  3123. os.environ['SECRET'] = 'secret'
  3124. os.environ['THING'] = 'thing'
  3125. os.environ['COMMON_ENV_FILE'] = 'secret'
  3126. os.environ['TOP_ENV_FILE'] = 'secret'
  3127. config = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  3128. assert config == expected
  3129. def test_extends_with_mixed_versions_is_error(self):
  3130. tmpdir = py.test.ensuretemp('test_extends_with_mixed_version')
  3131. self.addCleanup(tmpdir.remove)
  3132. tmpdir.join('docker-compose.yml').write("""
  3133. version: "2"
  3134. services:
  3135. web:
  3136. extends:
  3137. file: base.yml
  3138. service: base
  3139. image: busybox
  3140. """)
  3141. tmpdir.join('base.yml').write("""
  3142. base:
  3143. volumes: ['/foo']
  3144. ports: ['3000:3000']
  3145. """)
  3146. with pytest.raises(ConfigurationError) as exc:
  3147. load_from_filename(str(tmpdir.join('docker-compose.yml')))
  3148. assert 'Version mismatch' in exc.exconly()
  3149. def test_extends_with_defined_version_passes(self):
  3150. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  3151. self.addCleanup(tmpdir.remove)
  3152. tmpdir.join('docker-compose.yml').write("""
  3153. version: "2"
  3154. services:
  3155. web:
  3156. extends:
  3157. file: base.yml
  3158. service: base
  3159. image: busybox
  3160. """)
  3161. tmpdir.join('base.yml').write("""
  3162. version: "2"
  3163. services:
  3164. base:
  3165. volumes: ['/foo']
  3166. ports: ['3000:3000']
  3167. command: top
  3168. """)
  3169. service = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  3170. self.assertEqual(service[0]['command'], "top")
  3171. def test_extends_with_depends_on(self):
  3172. tmpdir = py.test.ensuretemp('test_extends_with_depends_on')
  3173. self.addCleanup(tmpdir.remove)
  3174. tmpdir.join('docker-compose.yml').write("""
  3175. version: "2"
  3176. services:
  3177. base:
  3178. image: example
  3179. web:
  3180. extends: base
  3181. image: busybox
  3182. depends_on: ['other']
  3183. other:
  3184. image: example
  3185. """)
  3186. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  3187. assert service_sort(services)[2]['depends_on'] == {
  3188. 'other': {'condition': 'service_started'}
  3189. }
  3190. def test_extends_with_healthcheck(self):
  3191. service_dicts = load_from_filename('tests/fixtures/extends/healthcheck-2.yml')
  3192. assert service_sort(service_dicts) == [{
  3193. 'name': 'demo',
  3194. 'image': 'foobar:latest',
  3195. 'healthcheck': {
  3196. 'test': ['CMD', '/health.sh'],
  3197. 'interval': 10000000000,
  3198. 'timeout': 5000000000,
  3199. 'retries': 36,
  3200. }
  3201. }]
  3202. def test_extends_with_ports(self):
  3203. tmpdir = py.test.ensuretemp('test_extends_with_ports')
  3204. self.addCleanup(tmpdir.remove)
  3205. tmpdir.join('docker-compose.yml').write("""
  3206. version: '2'
  3207. services:
  3208. a:
  3209. image: nginx
  3210. ports:
  3211. - 80
  3212. b:
  3213. extends:
  3214. service: a
  3215. """)
  3216. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  3217. assert len(services) == 2
  3218. for svc in services:
  3219. assert svc['ports'] == [types.ServicePort('80', None, None, None, None)]
  3220. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  3221. class ExpandPathTest(unittest.TestCase):
  3222. working_dir = '/home/user/somedir'
  3223. def test_expand_path_normal(self):
  3224. result = config.expand_path(self.working_dir, 'myfile')
  3225. self.assertEqual(result, self.working_dir + '/' + 'myfile')
  3226. def test_expand_path_absolute(self):
  3227. abs_path = '/home/user/otherdir/somefile'
  3228. result = config.expand_path(self.working_dir, abs_path)
  3229. self.assertEqual(result, abs_path)
  3230. def test_expand_path_with_tilde(self):
  3231. test_path = '~/otherdir/somefile'
  3232. with mock.patch.dict(os.environ):
  3233. os.environ['HOME'] = user_path = '/home/user/'
  3234. result = config.expand_path(self.working_dir, test_path)
  3235. self.assertEqual(result, user_path + 'otherdir/somefile')
  3236. class VolumePathTest(unittest.TestCase):
  3237. def test_split_path_mapping_with_windows_path(self):
  3238. host_path = "c:\\Users\\msamblanet\\Documents\\anvil\\connect\\config"
  3239. windows_volume_path = host_path + ":/opt/connect/config:ro"
  3240. expected_mapping = ("/opt/connect/config:ro", host_path)
  3241. mapping = config.split_path_mapping(windows_volume_path)
  3242. assert mapping == expected_mapping
  3243. def test_split_path_mapping_with_windows_path_in_container(self):
  3244. host_path = 'c:\\Users\\remilia\\data'
  3245. container_path = 'c:\\scarletdevil\\data'
  3246. expected_mapping = (container_path, host_path)
  3247. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  3248. assert mapping == expected_mapping
  3249. def test_split_path_mapping_with_root_mount(self):
  3250. host_path = '/'
  3251. container_path = '/var/hostroot'
  3252. expected_mapping = (container_path, host_path)
  3253. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  3254. assert mapping == expected_mapping
  3255. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  3256. class BuildPathTest(unittest.TestCase):
  3257. def setUp(self):
  3258. self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
  3259. def test_nonexistent_path(self):
  3260. with self.assertRaises(ConfigurationError):
  3261. config.load(
  3262. build_config_details(
  3263. {
  3264. 'foo': {'build': 'nonexistent.path'},
  3265. },
  3266. 'working_dir',
  3267. 'filename.yml'
  3268. )
  3269. )
  3270. def test_relative_path(self):
  3271. relative_build_path = '../build-ctx/'
  3272. service_dict = make_service_dict(
  3273. 'relpath',
  3274. {'build': relative_build_path},
  3275. working_dir='tests/fixtures/build-path'
  3276. )
  3277. self.assertEqual(service_dict['build'], self.abs_context_path)
  3278. def test_absolute_path(self):
  3279. service_dict = make_service_dict(
  3280. 'abspath',
  3281. {'build': self.abs_context_path},
  3282. working_dir='tests/fixtures/build-path'
  3283. )
  3284. self.assertEqual(service_dict['build'], self.abs_context_path)
  3285. def test_from_file(self):
  3286. service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
  3287. self.assertEqual(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  3288. def test_from_file_override_dir(self):
  3289. override_dir = os.path.join(os.getcwd(), 'tests/fixtures/')
  3290. service_dict = load_from_filename(
  3291. 'tests/fixtures/build-path-override-dir/docker-compose.yml', override_dir=override_dir)
  3292. self.assertEquals(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  3293. def test_valid_url_in_build_path(self):
  3294. valid_urls = [
  3295. 'git://github.com/docker/docker',
  3296. '[email protected]:docker/docker.git',
  3297. '[email protected]:atlassianlabs/atlassian-docker.git',
  3298. 'https://github.com/docker/docker.git',
  3299. 'http://github.com/docker/docker.git',
  3300. 'github.com/docker/docker.git',
  3301. ]
  3302. for valid_url in valid_urls:
  3303. service_dict = config.load(build_config_details({
  3304. 'validurl': {'build': valid_url},
  3305. }, '.', None)).services
  3306. assert service_dict[0]['build'] == {'context': valid_url}
  3307. def test_invalid_url_in_build_path(self):
  3308. invalid_urls = [
  3309. 'example.com/bogus',
  3310. 'ftp://example.com/',
  3311. '/path/does/not/exist',
  3312. ]
  3313. for invalid_url in invalid_urls:
  3314. with pytest.raises(ConfigurationError) as exc:
  3315. config.load(build_config_details({
  3316. 'invalidurl': {'build': invalid_url},
  3317. }, '.', None))
  3318. assert 'build path' in exc.exconly()
  3319. class HealthcheckTest(unittest.TestCase):
  3320. def test_healthcheck(self):
  3321. service_dict = make_service_dict(
  3322. 'test',
  3323. {'healthcheck': {
  3324. 'test': ['CMD', 'true'],
  3325. 'interval': '1s',
  3326. 'timeout': '1m',
  3327. 'retries': 3,
  3328. }},
  3329. '.',
  3330. )
  3331. assert service_dict['healthcheck'] == {
  3332. 'test': ['CMD', 'true'],
  3333. 'interval': nanoseconds_from_time_seconds(1),
  3334. 'timeout': nanoseconds_from_time_seconds(60),
  3335. 'retries': 3,
  3336. }
  3337. def test_disable(self):
  3338. service_dict = make_service_dict(
  3339. 'test',
  3340. {'healthcheck': {
  3341. 'disable': True,
  3342. }},
  3343. '.',
  3344. )
  3345. assert service_dict['healthcheck'] == {
  3346. 'test': ['NONE'],
  3347. }
  3348. def test_disable_with_other_config_is_invalid(self):
  3349. with pytest.raises(ConfigurationError) as excinfo:
  3350. make_service_dict(
  3351. 'invalid-healthcheck',
  3352. {'healthcheck': {
  3353. 'disable': True,
  3354. 'interval': '1s',
  3355. }},
  3356. '.',
  3357. )
  3358. assert 'invalid-healthcheck' in excinfo.exconly()
  3359. assert 'disable' in excinfo.exconly()
  3360. class GetDefaultConfigFilesTestCase(unittest.TestCase):
  3361. files = [
  3362. 'docker-compose.yml',
  3363. 'docker-compose.yaml',
  3364. ]
  3365. def test_get_config_path_default_file_in_basedir(self):
  3366. for index, filename in enumerate(self.files):
  3367. self.assertEqual(
  3368. filename,
  3369. get_config_filename_for_files(self.files[index:]))
  3370. with self.assertRaises(config.ComposeFileNotFound):
  3371. get_config_filename_for_files([])
  3372. def test_get_config_path_default_file_in_parent_dir(self):
  3373. """Test with files placed in the subdir"""
  3374. def get_config_in_subdir(files):
  3375. return get_config_filename_for_files(files, subdir=True)
  3376. for index, filename in enumerate(self.files):
  3377. self.assertEqual(filename, get_config_in_subdir(self.files[index:]))
  3378. with self.assertRaises(config.ComposeFileNotFound):
  3379. get_config_in_subdir([])
  3380. def get_config_filename_for_files(filenames, subdir=None):
  3381. def make_files(dirname, filenames):
  3382. for fname in filenames:
  3383. with open(os.path.join(dirname, fname), 'w') as f:
  3384. f.write('')
  3385. project_dir = tempfile.mkdtemp()
  3386. try:
  3387. make_files(project_dir, filenames)
  3388. if subdir:
  3389. base_dir = tempfile.mkdtemp(dir=project_dir)
  3390. else:
  3391. base_dir = project_dir
  3392. filename, = config.get_default_config_files(base_dir)
  3393. return os.path.basename(filename)
  3394. finally:
  3395. shutil.rmtree(project_dir)
  3396. class SerializeTest(unittest.TestCase):
  3397. def test_denormalize_depends_on_v3(self):
  3398. service_dict = {
  3399. 'image': 'busybox',
  3400. 'command': 'true',
  3401. 'depends_on': {
  3402. 'service2': {'condition': 'service_started'},
  3403. 'service3': {'condition': 'service_started'},
  3404. }
  3405. }
  3406. assert denormalize_service_dict(service_dict, V3_0) == {
  3407. 'image': 'busybox',
  3408. 'command': 'true',
  3409. 'depends_on': ['service2', 'service3']
  3410. }
  3411. def test_denormalize_depends_on_v2_1(self):
  3412. service_dict = {
  3413. 'image': 'busybox',
  3414. 'command': 'true',
  3415. 'depends_on': {
  3416. 'service2': {'condition': 'service_started'},
  3417. 'service3': {'condition': 'service_started'},
  3418. }
  3419. }
  3420. assert denormalize_service_dict(service_dict, V2_1) == service_dict
  3421. def test_serialize_time(self):
  3422. data = {
  3423. 9: '9ns',
  3424. 9000: '9us',
  3425. 9000000: '9ms',
  3426. 90000000: '90ms',
  3427. 900000000: '900ms',
  3428. 999999999: '999999999ns',
  3429. 1000000000: '1s',
  3430. 60000000000: '1m',
  3431. 60000000001: '60000000001ns',
  3432. 9000000000000: '150m',
  3433. 90000000000000: '25h',
  3434. }
  3435. for k, v in data.items():
  3436. assert serialize_ns_time_value(k) == v
  3437. def test_denormalize_healthcheck(self):
  3438. service_dict = {
  3439. 'image': 'test',
  3440. 'healthcheck': {
  3441. 'test': 'exit 1',
  3442. 'interval': '1m40s',
  3443. 'timeout': '30s',
  3444. 'retries': 5
  3445. }
  3446. }
  3447. processed_service = config.process_service(config.ServiceConfig(
  3448. '.', 'test', 'test', service_dict
  3449. ))
  3450. denormalized_service = denormalize_service_dict(processed_service, V2_1)
  3451. assert denormalized_service['healthcheck']['interval'] == '100s'
  3452. assert denormalized_service['healthcheck']['timeout'] == '30s'
  3453. def test_denormalize_image_has_digest(self):
  3454. service_dict = {
  3455. 'image': 'busybox'
  3456. }
  3457. image_digest = 'busybox@sha256:abcde'
  3458. assert denormalize_service_dict(service_dict, V3_0, image_digest) == {
  3459. 'image': 'busybox@sha256:abcde'
  3460. }
  3461. def test_denormalize_image_no_digest(self):
  3462. service_dict = {
  3463. 'image': 'busybox'
  3464. }
  3465. assert denormalize_service_dict(service_dict, V3_0) == {
  3466. 'image': 'busybox'
  3467. }
  3468. def test_serialize_secrets(self):
  3469. service_dict = {
  3470. 'image': 'example/web',
  3471. 'secrets': [
  3472. {'source': 'one'},
  3473. {
  3474. 'source': 'source',
  3475. 'target': 'target',
  3476. 'uid': '100',
  3477. 'gid': '200',
  3478. 'mode': 0o777,
  3479. }
  3480. ]
  3481. }
  3482. secrets_dict = {
  3483. 'one': {'file': '/one.txt'},
  3484. 'source': {'file': '/source.pem'},
  3485. 'two': {'external': True},
  3486. }
  3487. config_dict = config.load(build_config_details({
  3488. 'version': '3.1',
  3489. 'services': {'web': service_dict},
  3490. 'secrets': secrets_dict
  3491. }))
  3492. serialized_config = yaml.load(serialize_config(config_dict))
  3493. serialized_service = serialized_config['services']['web']
  3494. assert secret_sort(serialized_service['secrets']) == secret_sort(service_dict['secrets'])
  3495. assert 'secrets' in serialized_config
  3496. assert serialized_config['secrets']['two'] == secrets_dict['two']
  3497. def test_serialize_ports(self):
  3498. config_dict = config.Config(version='2.0', services=[
  3499. {
  3500. 'ports': [types.ServicePort('80', '8080', None, None, None)],
  3501. 'image': 'alpine',
  3502. 'name': 'web'
  3503. }
  3504. ], volumes={}, networks={}, secrets={})
  3505. serialized_config = yaml.load(serialize_config(config_dict))
  3506. assert '8080:80/tcp' in serialized_config['services']['web']['ports']