config_test.py 123 KB

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