config_test.py 118 KB

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