config_test.py 125 KB

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