config_test.py 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824
  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. from ...helpers import build_config_details
  12. from compose.config import config
  13. from compose.config.config import resolve_build_args
  14. from compose.config.config import resolve_environment
  15. from compose.config.config import V1
  16. from compose.config.config import V2_0
  17. from compose.config.environment import Environment
  18. from compose.config.errors import ConfigurationError
  19. from compose.config.errors import VERSION_EXPLANATION
  20. from compose.config.types import VolumeSpec
  21. from compose.const import IS_WINDOWS_PLATFORM
  22. from tests import mock
  23. from tests import unittest
  24. DEFAULT_VERSION = V2_0
  25. def make_service_dict(name, service_dict, working_dir, filename=None):
  26. """Test helper function to construct a ServiceExtendsResolver
  27. """
  28. resolver = config.ServiceExtendsResolver(
  29. config.ServiceConfig(
  30. working_dir=working_dir,
  31. filename=filename,
  32. name=name,
  33. config=service_dict),
  34. config.ConfigFile(filename=filename, config={}),
  35. environment=Environment.from_env_file(working_dir)
  36. )
  37. return config.process_service(resolver.run())
  38. def service_sort(services):
  39. return sorted(services, key=itemgetter('name'))
  40. class ConfigTest(unittest.TestCase):
  41. def test_load(self):
  42. service_dicts = config.load(
  43. build_config_details(
  44. {
  45. 'foo': {'image': 'busybox'},
  46. 'bar': {'image': 'busybox', 'environment': ['FOO=1']},
  47. },
  48. 'tests/fixtures/extends',
  49. 'common.yml'
  50. )
  51. ).services
  52. self.assertEqual(
  53. service_sort(service_dicts),
  54. service_sort([
  55. {
  56. 'name': 'bar',
  57. 'image': 'busybox',
  58. 'environment': {'FOO': '1'},
  59. },
  60. {
  61. 'name': 'foo',
  62. 'image': 'busybox',
  63. }
  64. ])
  65. )
  66. def test_load_v2(self):
  67. config_data = config.load(
  68. build_config_details({
  69. 'version': '2',
  70. 'services': {
  71. 'foo': {'image': 'busybox'},
  72. 'bar': {'image': 'busybox', 'environment': ['FOO=1']},
  73. },
  74. 'volumes': {
  75. 'hello': {
  76. 'driver': 'default',
  77. 'driver_opts': {'beep': 'boop'}
  78. }
  79. },
  80. 'networks': {
  81. 'default': {
  82. 'driver': 'bridge',
  83. 'driver_opts': {'beep': 'boop'}
  84. },
  85. 'with_ipam': {
  86. 'ipam': {
  87. 'driver': 'default',
  88. 'config': [
  89. {'subnet': '172.28.0.0/16'}
  90. ]
  91. }
  92. }
  93. }
  94. }, 'working_dir', 'filename.yml')
  95. )
  96. service_dicts = config_data.services
  97. volume_dict = config_data.volumes
  98. networks_dict = config_data.networks
  99. self.assertEqual(
  100. service_sort(service_dicts),
  101. service_sort([
  102. {
  103. 'name': 'bar',
  104. 'image': 'busybox',
  105. 'environment': {'FOO': '1'},
  106. },
  107. {
  108. 'name': 'foo',
  109. 'image': 'busybox',
  110. }
  111. ])
  112. )
  113. self.assertEqual(volume_dict, {
  114. 'hello': {
  115. 'driver': 'default',
  116. 'driver_opts': {'beep': 'boop'}
  117. }
  118. })
  119. self.assertEqual(networks_dict, {
  120. 'default': {
  121. 'driver': 'bridge',
  122. 'driver_opts': {'beep': 'boop'}
  123. },
  124. 'with_ipam': {
  125. 'ipam': {
  126. 'driver': 'default',
  127. 'config': [
  128. {'subnet': '172.28.0.0/16'}
  129. ]
  130. }
  131. }
  132. })
  133. def test_valid_versions(self):
  134. for version in ['2', '2.0']:
  135. cfg = config.load(build_config_details({'version': version}))
  136. assert cfg.version == V2_0
  137. def test_v1_file_version(self):
  138. cfg = config.load(build_config_details({'web': {'image': 'busybox'}}))
  139. assert cfg.version == V1
  140. assert list(s['name'] for s in cfg.services) == ['web']
  141. cfg = config.load(build_config_details({'version': {'image': 'busybox'}}))
  142. assert cfg.version == V1
  143. assert list(s['name'] for s in cfg.services) == ['version']
  144. def test_wrong_version_type(self):
  145. for version in [None, 1, 2, 2.0]:
  146. with pytest.raises(ConfigurationError) as excinfo:
  147. config.load(
  148. build_config_details(
  149. {'version': version},
  150. filename='filename.yml',
  151. )
  152. )
  153. assert 'Version in "filename.yml" is invalid - it should be a string.' \
  154. in excinfo.exconly()
  155. def test_unsupported_version(self):
  156. with pytest.raises(ConfigurationError) as excinfo:
  157. config.load(
  158. build_config_details(
  159. {'version': '2.1'},
  160. filename='filename.yml',
  161. )
  162. )
  163. assert 'Version in "filename.yml" is unsupported' in excinfo.exconly()
  164. assert VERSION_EXPLANATION in excinfo.exconly()
  165. def test_version_1_is_invalid(self):
  166. with pytest.raises(ConfigurationError) as excinfo:
  167. config.load(
  168. build_config_details(
  169. {
  170. 'version': '1',
  171. 'web': {'image': 'busybox'},
  172. },
  173. filename='filename.yml',
  174. )
  175. )
  176. assert 'Version in "filename.yml" is invalid' in excinfo.exconly()
  177. assert VERSION_EXPLANATION in excinfo.exconly()
  178. def test_v1_file_with_version_is_invalid(self):
  179. with pytest.raises(ConfigurationError) as excinfo:
  180. config.load(
  181. build_config_details(
  182. {
  183. 'version': '2',
  184. 'web': {'image': 'busybox'},
  185. },
  186. filename='filename.yml',
  187. )
  188. )
  189. assert 'Additional properties are not allowed' in excinfo.exconly()
  190. assert VERSION_EXPLANATION in excinfo.exconly()
  191. def test_named_volume_config_empty(self):
  192. config_details = build_config_details({
  193. 'version': '2',
  194. 'services': {
  195. 'simple': {'image': 'busybox'}
  196. },
  197. 'volumes': {
  198. 'simple': None,
  199. 'other': {},
  200. }
  201. })
  202. config_result = config.load(config_details)
  203. volumes = config_result.volumes
  204. assert 'simple' in volumes
  205. assert volumes['simple'] == {}
  206. assert volumes['other'] == {}
  207. def test_named_volume_numeric_driver_opt(self):
  208. config_details = build_config_details({
  209. 'version': '2',
  210. 'services': {
  211. 'simple': {'image': 'busybox'}
  212. },
  213. 'volumes': {
  214. 'simple': {'driver_opts': {'size': 42}},
  215. }
  216. })
  217. cfg = config.load(config_details)
  218. assert cfg.volumes['simple']['driver_opts']['size'] == '42'
  219. def test_volume_invalid_driver_opt(self):
  220. config_details = build_config_details({
  221. 'version': '2',
  222. 'services': {
  223. 'simple': {'image': 'busybox'}
  224. },
  225. 'volumes': {
  226. 'simple': {'driver_opts': {'size': True}},
  227. }
  228. })
  229. with pytest.raises(ConfigurationError) as exc:
  230. config.load(config_details)
  231. assert 'driver_opts.size contains an invalid type' in exc.exconly()
  232. def test_named_volume_invalid_type_list(self):
  233. config_details = build_config_details({
  234. 'version': '2',
  235. 'services': {
  236. 'simple': {'image': 'busybox'}
  237. },
  238. 'volumes': []
  239. })
  240. with pytest.raises(ConfigurationError) as exc:
  241. config.load(config_details)
  242. assert "volume must be a mapping, not an array" in exc.exconly()
  243. def test_networks_invalid_type_list(self):
  244. config_details = build_config_details({
  245. 'version': '2',
  246. 'services': {
  247. 'simple': {'image': 'busybox'}
  248. },
  249. 'networks': []
  250. })
  251. with pytest.raises(ConfigurationError) as exc:
  252. config.load(config_details)
  253. assert "network must be a mapping, not an array" in exc.exconly()
  254. def test_load_service_with_name_version(self):
  255. with mock.patch('compose.config.config.log') as mock_logging:
  256. config_data = config.load(
  257. build_config_details({
  258. 'version': {
  259. 'image': 'busybox'
  260. }
  261. }, 'working_dir', 'filename.yml')
  262. )
  263. assert 'Unexpected type for "version" key in "filename.yml"' \
  264. in mock_logging.warn.call_args[0][0]
  265. service_dicts = config_data.services
  266. self.assertEqual(
  267. service_sort(service_dicts),
  268. service_sort([
  269. {
  270. 'name': 'version',
  271. 'image': 'busybox',
  272. }
  273. ])
  274. )
  275. def test_load_throws_error_when_not_dict(self):
  276. with self.assertRaises(ConfigurationError):
  277. config.load(
  278. build_config_details(
  279. {'web': 'busybox:latest'},
  280. 'working_dir',
  281. 'filename.yml'
  282. )
  283. )
  284. def test_load_throws_error_when_not_dict_v2(self):
  285. with self.assertRaises(ConfigurationError):
  286. config.load(
  287. build_config_details(
  288. {'version': '2', 'services': {'web': 'busybox:latest'}},
  289. 'working_dir',
  290. 'filename.yml'
  291. )
  292. )
  293. def test_load_throws_error_with_invalid_network_fields(self):
  294. with self.assertRaises(ConfigurationError):
  295. config.load(
  296. build_config_details({
  297. 'version': '2',
  298. 'services': {'web': 'busybox:latest'},
  299. 'networks': {
  300. 'invalid': {'foo', 'bar'}
  301. }
  302. }, 'working_dir', 'filename.yml')
  303. )
  304. def test_load_config_invalid_service_names(self):
  305. for invalid_name in ['?not?allowed', ' ', '', '!', '/', '\xe2']:
  306. with pytest.raises(ConfigurationError) as exc:
  307. config.load(build_config_details(
  308. {invalid_name: {'image': 'busybox'}}))
  309. assert 'Invalid service name \'%s\'' % invalid_name in exc.exconly()
  310. def test_load_config_invalid_service_names_v2(self):
  311. for invalid_name in ['?not?allowed', ' ', '', '!', '/', '\xe2']:
  312. with pytest.raises(ConfigurationError) as exc:
  313. config.load(build_config_details(
  314. {
  315. 'version': '2',
  316. 'services': {invalid_name: {'image': 'busybox'}},
  317. }))
  318. assert 'Invalid service name \'%s\'' % invalid_name in exc.exconly()
  319. def test_load_with_invalid_field_name(self):
  320. with pytest.raises(ConfigurationError) as exc:
  321. config.load(build_config_details(
  322. {
  323. 'version': '2',
  324. 'services': {
  325. 'web': {'image': 'busybox', 'name': 'bogus'},
  326. }
  327. },
  328. 'working_dir',
  329. 'filename.yml',
  330. ))
  331. assert "Unsupported config option for services.web: 'name'" in exc.exconly()
  332. def test_load_with_invalid_field_name_v1(self):
  333. with pytest.raises(ConfigurationError) as exc:
  334. config.load(build_config_details(
  335. {
  336. 'web': {'image': 'busybox', 'name': 'bogus'},
  337. },
  338. 'working_dir',
  339. 'filename.yml',
  340. ))
  341. assert "Unsupported config option for web: 'name'" in exc.exconly()
  342. def test_load_invalid_service_definition(self):
  343. config_details = build_config_details(
  344. {'web': 'wrong'},
  345. 'working_dir',
  346. 'filename.yml')
  347. with pytest.raises(ConfigurationError) as exc:
  348. config.load(config_details)
  349. assert "service 'web' must be a mapping not a string." in exc.exconly()
  350. def test_load_with_empty_build_args(self):
  351. config_details = build_config_details(
  352. {
  353. 'version': '2',
  354. 'services': {
  355. 'web': {
  356. 'build': {
  357. 'context': '.',
  358. 'args': None,
  359. },
  360. },
  361. },
  362. }
  363. )
  364. with pytest.raises(ConfigurationError) as exc:
  365. config.load(config_details)
  366. assert (
  367. "services.web.build.args contains an invalid type, it should be an "
  368. "object, or an array" in exc.exconly()
  369. )
  370. def test_config_integer_service_name_raise_validation_error(self):
  371. with pytest.raises(ConfigurationError) as excinfo:
  372. config.load(
  373. build_config_details(
  374. {1: {'image': 'busybox'}},
  375. 'working_dir',
  376. 'filename.yml'
  377. )
  378. )
  379. assert (
  380. "In file 'filename.yml', the service name 1 must be a quoted string, i.e. '1'" in
  381. excinfo.exconly()
  382. )
  383. def test_config_integer_service_name_raise_validation_error_v2(self):
  384. with pytest.raises(ConfigurationError) as excinfo:
  385. config.load(
  386. build_config_details(
  387. {
  388. 'version': '2',
  389. 'services': {1: {'image': 'busybox'}}
  390. },
  391. 'working_dir',
  392. 'filename.yml'
  393. )
  394. )
  395. assert (
  396. "In file 'filename.yml', the service name 1 must be a quoted string, i.e. '1'." in
  397. excinfo.exconly()
  398. )
  399. def test_load_with_multiple_files_v1(self):
  400. base_file = config.ConfigFile(
  401. 'base.yaml',
  402. {
  403. 'web': {
  404. 'image': 'example/web',
  405. 'links': ['db'],
  406. },
  407. 'db': {
  408. 'image': 'example/db',
  409. },
  410. })
  411. override_file = config.ConfigFile(
  412. 'override.yaml',
  413. {
  414. 'web': {
  415. 'build': '/',
  416. 'volumes': ['/home/user/project:/code'],
  417. },
  418. })
  419. details = config.ConfigDetails('.', [base_file, override_file])
  420. service_dicts = config.load(details).services
  421. expected = [
  422. {
  423. 'name': 'web',
  424. 'build': {'context': os.path.abspath('/')},
  425. 'volumes': [VolumeSpec.parse('/home/user/project:/code')],
  426. 'links': ['db'],
  427. },
  428. {
  429. 'name': 'db',
  430. 'image': 'example/db',
  431. },
  432. ]
  433. assert service_sort(service_dicts) == service_sort(expected)
  434. def test_load_with_multiple_files_and_empty_override(self):
  435. base_file = config.ConfigFile(
  436. 'base.yml',
  437. {'web': {'image': 'example/web'}})
  438. override_file = config.ConfigFile('override.yml', None)
  439. details = config.ConfigDetails('.', [base_file, override_file])
  440. with pytest.raises(ConfigurationError) as exc:
  441. config.load(details)
  442. error_msg = "Top level object in 'override.yml' needs to be an object"
  443. assert error_msg in exc.exconly()
  444. def test_load_with_multiple_files_and_empty_override_v2(self):
  445. base_file = config.ConfigFile(
  446. 'base.yml',
  447. {'version': '2', 'services': {'web': {'image': 'example/web'}}})
  448. override_file = config.ConfigFile('override.yml', None)
  449. details = config.ConfigDetails('.', [base_file, override_file])
  450. with pytest.raises(ConfigurationError) as exc:
  451. config.load(details)
  452. error_msg = "Top level object in 'override.yml' needs to be an object"
  453. assert error_msg in exc.exconly()
  454. def test_load_with_multiple_files_and_empty_base(self):
  455. base_file = config.ConfigFile('base.yml', None)
  456. override_file = config.ConfigFile(
  457. 'override.yml',
  458. {'web': {'image': 'example/web'}})
  459. details = config.ConfigDetails('.', [base_file, override_file])
  460. with pytest.raises(ConfigurationError) as exc:
  461. config.load(details)
  462. assert "Top level object in 'base.yml' needs to be an object" in exc.exconly()
  463. def test_load_with_multiple_files_and_empty_base_v2(self):
  464. base_file = config.ConfigFile('base.yml', None)
  465. override_file = config.ConfigFile(
  466. 'override.tml',
  467. {'version': '2', 'services': {'web': {'image': 'example/web'}}}
  468. )
  469. details = config.ConfigDetails('.', [base_file, override_file])
  470. with pytest.raises(ConfigurationError) as exc:
  471. config.load(details)
  472. assert "Top level object in 'base.yml' needs to be an object" in exc.exconly()
  473. def test_load_with_multiple_files_and_extends_in_override_file(self):
  474. base_file = config.ConfigFile(
  475. 'base.yaml',
  476. {
  477. 'web': {'image': 'example/web'},
  478. })
  479. override_file = config.ConfigFile(
  480. 'override.yaml',
  481. {
  482. 'web': {
  483. 'extends': {
  484. 'file': 'common.yml',
  485. 'service': 'base',
  486. },
  487. 'volumes': ['/home/user/project:/code'],
  488. },
  489. })
  490. details = config.ConfigDetails('.', [base_file, override_file])
  491. tmpdir = py.test.ensuretemp('config_test')
  492. self.addCleanup(tmpdir.remove)
  493. tmpdir.join('common.yml').write("""
  494. base:
  495. labels: ['label=one']
  496. """)
  497. with tmpdir.as_cwd():
  498. service_dicts = config.load(details).services
  499. expected = [
  500. {
  501. 'name': 'web',
  502. 'image': 'example/web',
  503. 'volumes': [VolumeSpec.parse('/home/user/project:/code')],
  504. 'labels': {'label': 'one'},
  505. },
  506. ]
  507. self.assertEqual(service_sort(service_dicts), service_sort(expected))
  508. def test_load_with_multiple_files_and_invalid_override(self):
  509. base_file = config.ConfigFile(
  510. 'base.yaml',
  511. {'web': {'image': 'example/web'}})
  512. override_file = config.ConfigFile(
  513. 'override.yaml',
  514. {'bogus': 'thing'})
  515. details = config.ConfigDetails('.', [base_file, override_file])
  516. with pytest.raises(ConfigurationError) as exc:
  517. config.load(details)
  518. assert "service 'bogus' must be a mapping not a string." in exc.exconly()
  519. assert "In file 'override.yaml'" in exc.exconly()
  520. def test_load_sorts_in_dependency_order(self):
  521. config_details = build_config_details({
  522. 'web': {
  523. 'image': 'busybox:latest',
  524. 'links': ['db'],
  525. },
  526. 'db': {
  527. 'image': 'busybox:latest',
  528. 'volumes_from': ['volume:ro']
  529. },
  530. 'volume': {
  531. 'image': 'busybox:latest',
  532. 'volumes': ['/tmp'],
  533. }
  534. })
  535. services = config.load(config_details).services
  536. assert services[0]['name'] == 'volume'
  537. assert services[1]['name'] == 'db'
  538. assert services[2]['name'] == 'web'
  539. def test_config_build_configuration(self):
  540. service = config.load(
  541. build_config_details(
  542. {'web': {
  543. 'build': '.',
  544. 'dockerfile': 'Dockerfile-alt'
  545. }},
  546. 'tests/fixtures/extends',
  547. 'filename.yml'
  548. )
  549. ).services
  550. self.assertTrue('context' in service[0]['build'])
  551. self.assertEqual(service[0]['build']['dockerfile'], 'Dockerfile-alt')
  552. def test_config_build_configuration_v2(self):
  553. # service.dockerfile is invalid in v2
  554. with self.assertRaises(ConfigurationError):
  555. config.load(
  556. build_config_details(
  557. {
  558. 'version': '2',
  559. 'services': {
  560. 'web': {
  561. 'build': '.',
  562. 'dockerfile': 'Dockerfile-alt'
  563. }
  564. }
  565. },
  566. 'tests/fixtures/extends',
  567. 'filename.yml'
  568. )
  569. )
  570. service = config.load(
  571. build_config_details({
  572. 'version': '2',
  573. 'services': {
  574. 'web': {
  575. 'build': '.'
  576. }
  577. }
  578. }, 'tests/fixtures/extends', 'filename.yml')
  579. ).services[0]
  580. self.assertTrue('context' in service['build'])
  581. service = config.load(
  582. build_config_details(
  583. {
  584. 'version': '2',
  585. 'services': {
  586. 'web': {
  587. 'build': {
  588. 'context': '.',
  589. 'dockerfile': 'Dockerfile-alt'
  590. }
  591. }
  592. }
  593. },
  594. 'tests/fixtures/extends',
  595. 'filename.yml'
  596. )
  597. ).services
  598. self.assertTrue('context' in service[0]['build'])
  599. self.assertEqual(service[0]['build']['dockerfile'], 'Dockerfile-alt')
  600. def test_load_with_buildargs(self):
  601. service = config.load(
  602. build_config_details(
  603. {
  604. 'version': '2',
  605. 'services': {
  606. 'web': {
  607. 'build': {
  608. 'context': '.',
  609. 'dockerfile': 'Dockerfile-alt',
  610. 'args': {
  611. 'opt1': 42,
  612. 'opt2': 'foobar'
  613. }
  614. }
  615. }
  616. }
  617. },
  618. 'tests/fixtures/extends',
  619. 'filename.yml'
  620. )
  621. ).services[0]
  622. assert 'args' in service['build']
  623. assert 'opt1' in service['build']['args']
  624. assert isinstance(service['build']['args']['opt1'], str)
  625. assert service['build']['args']['opt1'] == '42'
  626. assert service['build']['args']['opt2'] == 'foobar'
  627. def test_build_args_allow_empty_properties(self):
  628. service = config.load(
  629. build_config_details(
  630. {
  631. 'version': '2',
  632. 'services': {
  633. 'web': {
  634. 'build': {
  635. 'context': '.',
  636. 'dockerfile': 'Dockerfile-alt',
  637. 'args': {
  638. 'foo': None
  639. }
  640. }
  641. }
  642. }
  643. },
  644. 'tests/fixtures/extends',
  645. 'filename.yml'
  646. )
  647. ).services[0]
  648. assert 'args' in service['build']
  649. assert 'foo' in service['build']['args']
  650. assert service['build']['args']['foo'] == ''
  651. # If build argument is None then it will be converted to the empty
  652. # string. Make sure that int zero kept as it is, i.e. not converted to
  653. # the empty string
  654. def test_build_args_check_zero_preserved(self):
  655. service = config.load(
  656. build_config_details(
  657. {
  658. 'version': '2',
  659. 'services': {
  660. 'web': {
  661. 'build': {
  662. 'context': '.',
  663. 'dockerfile': 'Dockerfile-alt',
  664. 'args': {
  665. 'foo': 0
  666. }
  667. }
  668. }
  669. }
  670. },
  671. 'tests/fixtures/extends',
  672. 'filename.yml'
  673. )
  674. ).services[0]
  675. assert 'args' in service['build']
  676. assert 'foo' in service['build']['args']
  677. assert service['build']['args']['foo'] == '0'
  678. def test_load_with_multiple_files_mismatched_networks_format(self):
  679. base_file = config.ConfigFile(
  680. 'base.yaml',
  681. {
  682. 'version': '2',
  683. 'services': {
  684. 'web': {
  685. 'image': 'example/web',
  686. 'networks': {
  687. 'foobar': {'aliases': ['foo', 'bar']}
  688. }
  689. }
  690. },
  691. 'networks': {'foobar': {}, 'baz': {}}
  692. }
  693. )
  694. override_file = config.ConfigFile(
  695. 'override.yaml',
  696. {
  697. 'version': '2',
  698. 'services': {
  699. 'web': {
  700. 'networks': ['baz']
  701. }
  702. }
  703. }
  704. )
  705. details = config.ConfigDetails('.', [base_file, override_file])
  706. web_service = config.load(details).services[0]
  707. assert web_service['networks'] == {
  708. 'foobar': {'aliases': ['foo', 'bar']},
  709. 'baz': None
  710. }
  711. def test_load_with_multiple_files_v2(self):
  712. base_file = config.ConfigFile(
  713. 'base.yaml',
  714. {
  715. 'version': '2',
  716. 'services': {
  717. 'web': {
  718. 'image': 'example/web',
  719. 'depends_on': ['db'],
  720. },
  721. 'db': {
  722. 'image': 'example/db',
  723. }
  724. },
  725. })
  726. override_file = config.ConfigFile(
  727. 'override.yaml',
  728. {
  729. 'version': '2',
  730. 'services': {
  731. 'web': {
  732. 'build': '/',
  733. 'volumes': ['/home/user/project:/code'],
  734. 'depends_on': ['other'],
  735. },
  736. 'other': {
  737. 'image': 'example/other',
  738. }
  739. }
  740. })
  741. details = config.ConfigDetails('.', [base_file, override_file])
  742. service_dicts = config.load(details).services
  743. expected = [
  744. {
  745. 'name': 'web',
  746. 'build': {'context': os.path.abspath('/')},
  747. 'image': 'example/web',
  748. 'volumes': [VolumeSpec.parse('/home/user/project:/code')],
  749. 'depends_on': ['db', 'other'],
  750. },
  751. {
  752. 'name': 'db',
  753. 'image': 'example/db',
  754. },
  755. {
  756. 'name': 'other',
  757. 'image': 'example/other',
  758. },
  759. ]
  760. assert service_sort(service_dicts) == service_sort(expected)
  761. def test_undeclared_volume_v2(self):
  762. base_file = config.ConfigFile(
  763. 'base.yaml',
  764. {
  765. 'version': '2',
  766. 'services': {
  767. 'web': {
  768. 'image': 'busybox:latest',
  769. 'volumes': ['data0028:/data:ro'],
  770. },
  771. },
  772. }
  773. )
  774. details = config.ConfigDetails('.', [base_file])
  775. with self.assertRaises(ConfigurationError):
  776. config.load(details)
  777. base_file = config.ConfigFile(
  778. 'base.yaml',
  779. {
  780. 'version': '2',
  781. 'services': {
  782. 'web': {
  783. 'image': 'busybox:latest',
  784. 'volumes': ['./data0028:/data:ro'],
  785. },
  786. },
  787. }
  788. )
  789. details = config.ConfigDetails('.', [base_file])
  790. config_data = config.load(details)
  791. volume = config_data.services[0].get('volumes')[0]
  792. assert not volume.is_named_volume
  793. def test_undeclared_volume_v1(self):
  794. base_file = config.ConfigFile(
  795. 'base.yaml',
  796. {
  797. 'web': {
  798. 'image': 'busybox:latest',
  799. 'volumes': ['data0028:/data:ro'],
  800. },
  801. }
  802. )
  803. details = config.ConfigDetails('.', [base_file])
  804. config_data = config.load(details)
  805. volume = config_data.services[0].get('volumes')[0]
  806. assert volume.external == 'data0028'
  807. assert volume.is_named_volume
  808. def test_config_valid_service_names(self):
  809. for valid_name in ['_', '-', '.__.', '_what-up.', 'what_.up----', 'whatup']:
  810. services = config.load(
  811. build_config_details(
  812. {valid_name: {'image': 'busybox'}},
  813. 'tests/fixtures/extends',
  814. 'common.yml')).services
  815. assert services[0]['name'] == valid_name
  816. def test_config_hint(self):
  817. with pytest.raises(ConfigurationError) as excinfo:
  818. config.load(
  819. build_config_details(
  820. {
  821. 'foo': {'image': 'busybox', 'privilige': 'something'},
  822. },
  823. 'tests/fixtures/extends',
  824. 'filename.yml'
  825. )
  826. )
  827. assert "(did you mean 'privileged'?)" in excinfo.exconly()
  828. def test_load_errors_on_uppercase_with_no_image(self):
  829. with pytest.raises(ConfigurationError) as exc:
  830. config.load(build_config_details({
  831. 'Foo': {'build': '.'},
  832. }, 'tests/fixtures/build-ctx'))
  833. assert "Service 'Foo' contains uppercase characters" in exc.exconly()
  834. def test_invalid_config_v1(self):
  835. with pytest.raises(ConfigurationError) as excinfo:
  836. config.load(
  837. build_config_details(
  838. {
  839. 'foo': {'image': 1},
  840. },
  841. 'tests/fixtures/extends',
  842. 'filename.yml'
  843. )
  844. )
  845. assert "foo.image contains an invalid type, it should be a string" \
  846. in excinfo.exconly()
  847. def test_invalid_config_v2(self):
  848. with pytest.raises(ConfigurationError) as excinfo:
  849. config.load(
  850. build_config_details(
  851. {
  852. 'version': '2',
  853. 'services': {
  854. 'foo': {'image': 1},
  855. },
  856. },
  857. 'tests/fixtures/extends',
  858. 'filename.yml'
  859. )
  860. )
  861. assert "services.foo.image contains an invalid type, it should be a string" \
  862. in excinfo.exconly()
  863. def test_invalid_config_build_and_image_specified_v1(self):
  864. with pytest.raises(ConfigurationError) as excinfo:
  865. config.load(
  866. build_config_details(
  867. {
  868. 'foo': {'image': 'busybox', 'build': '.'},
  869. },
  870. 'tests/fixtures/extends',
  871. 'filename.yml'
  872. )
  873. )
  874. assert "foo has both an image and build path specified." in excinfo.exconly()
  875. def test_invalid_config_type_should_be_an_array(self):
  876. with pytest.raises(ConfigurationError) as excinfo:
  877. config.load(
  878. build_config_details(
  879. {
  880. 'foo': {'image': 'busybox', 'links': 'an_link'},
  881. },
  882. 'tests/fixtures/extends',
  883. 'filename.yml'
  884. )
  885. )
  886. assert "foo.links contains an invalid type, it should be an array" \
  887. in excinfo.exconly()
  888. def test_invalid_config_not_a_dictionary(self):
  889. with pytest.raises(ConfigurationError) as excinfo:
  890. config.load(
  891. build_config_details(
  892. ['foo', 'lol'],
  893. 'tests/fixtures/extends',
  894. 'filename.yml'
  895. )
  896. )
  897. assert "Top level object in 'filename.yml' needs to be an object" \
  898. in excinfo.exconly()
  899. def test_invalid_config_not_unique_items(self):
  900. with pytest.raises(ConfigurationError) as excinfo:
  901. config.load(
  902. build_config_details(
  903. {
  904. 'web': {'build': '.', 'devices': ['/dev/foo:/dev/foo', '/dev/foo:/dev/foo']}
  905. },
  906. 'tests/fixtures/extends',
  907. 'filename.yml'
  908. )
  909. )
  910. assert "has non-unique elements" in excinfo.exconly()
  911. def test_invalid_list_of_strings_format(self):
  912. with pytest.raises(ConfigurationError) as excinfo:
  913. config.load(
  914. build_config_details(
  915. {
  916. 'web': {'build': '.', 'command': [1]}
  917. },
  918. 'tests/fixtures/extends',
  919. 'filename.yml'
  920. )
  921. )
  922. assert "web.command contains 1, which is an invalid type, it should be a string" \
  923. in excinfo.exconly()
  924. def test_load_config_dockerfile_without_build_raises_error_v1(self):
  925. with pytest.raises(ConfigurationError) as exc:
  926. config.load(build_config_details({
  927. 'web': {
  928. 'image': 'busybox',
  929. 'dockerfile': 'Dockerfile.alt'
  930. }
  931. }))
  932. assert "web has both an image and alternate Dockerfile." in exc.exconly()
  933. def test_config_extra_hosts_string_raises_validation_error(self):
  934. with pytest.raises(ConfigurationError) as excinfo:
  935. config.load(
  936. build_config_details(
  937. {'web': {
  938. 'image': 'busybox',
  939. 'extra_hosts': 'somehost:162.242.195.82'
  940. }},
  941. 'working_dir',
  942. 'filename.yml'
  943. )
  944. )
  945. assert "web.extra_hosts contains an invalid type" \
  946. in excinfo.exconly()
  947. def test_config_extra_hosts_list_of_dicts_validation_error(self):
  948. with pytest.raises(ConfigurationError) as excinfo:
  949. config.load(
  950. build_config_details(
  951. {'web': {
  952. 'image': 'busybox',
  953. 'extra_hosts': [
  954. {'somehost': '162.242.195.82'},
  955. {'otherhost': '50.31.209.229'}
  956. ]
  957. }},
  958. 'working_dir',
  959. 'filename.yml'
  960. )
  961. )
  962. assert "web.extra_hosts contains {\"somehost\": \"162.242.195.82\"}, " \
  963. "which is an invalid type, it should be a string" \
  964. in excinfo.exconly()
  965. def test_config_ulimits_invalid_keys_validation_error(self):
  966. with pytest.raises(ConfigurationError) as exc:
  967. config.load(build_config_details(
  968. {
  969. 'web': {
  970. 'image': 'busybox',
  971. 'ulimits': {
  972. 'nofile': {
  973. "not_soft_or_hard": 100,
  974. "soft": 10000,
  975. "hard": 20000,
  976. }
  977. }
  978. }
  979. },
  980. 'working_dir',
  981. 'filename.yml'))
  982. assert "web.ulimits.nofile contains unsupported option: 'not_soft_or_hard'" \
  983. in exc.exconly()
  984. def test_config_ulimits_required_keys_validation_error(self):
  985. with pytest.raises(ConfigurationError) as exc:
  986. config.load(build_config_details(
  987. {
  988. 'web': {
  989. 'image': 'busybox',
  990. 'ulimits': {'nofile': {"soft": 10000}}
  991. }
  992. },
  993. 'working_dir',
  994. 'filename.yml'))
  995. assert "web.ulimits.nofile" in exc.exconly()
  996. assert "'hard' is a required property" in exc.exconly()
  997. def test_config_ulimits_soft_greater_than_hard_error(self):
  998. expected = "'soft' value can not be greater than 'hard' value"
  999. with pytest.raises(ConfigurationError) as exc:
  1000. config.load(build_config_details(
  1001. {
  1002. 'web': {
  1003. 'image': 'busybox',
  1004. 'ulimits': {
  1005. 'nofile': {"soft": 10000, "hard": 1000}
  1006. }
  1007. }
  1008. },
  1009. 'working_dir',
  1010. 'filename.yml'))
  1011. assert expected in exc.exconly()
  1012. def test_valid_config_which_allows_two_type_definitions(self):
  1013. expose_values = [["8000"], [8000]]
  1014. for expose in expose_values:
  1015. service = config.load(
  1016. build_config_details(
  1017. {'web': {
  1018. 'image': 'busybox',
  1019. 'expose': expose
  1020. }},
  1021. 'working_dir',
  1022. 'filename.yml'
  1023. )
  1024. ).services
  1025. self.assertEqual(service[0]['expose'], expose)
  1026. def test_valid_config_oneof_string_or_list(self):
  1027. entrypoint_values = [["sh"], "sh"]
  1028. for entrypoint in entrypoint_values:
  1029. service = config.load(
  1030. build_config_details(
  1031. {'web': {
  1032. 'image': 'busybox',
  1033. 'entrypoint': entrypoint
  1034. }},
  1035. 'working_dir',
  1036. 'filename.yml'
  1037. )
  1038. ).services
  1039. self.assertEqual(service[0]['entrypoint'], entrypoint)
  1040. def test_logs_warning_for_boolean_in_environment(self):
  1041. config_details = build_config_details({
  1042. 'web': {
  1043. 'image': 'busybox',
  1044. 'environment': {'SHOW_STUFF': True}
  1045. }
  1046. })
  1047. with pytest.raises(ConfigurationError) as exc:
  1048. config.load(config_details)
  1049. assert "contains true, which is an invalid type" in exc.exconly()
  1050. def test_config_valid_environment_dict_key_contains_dashes(self):
  1051. services = config.load(
  1052. build_config_details(
  1053. {'web': {
  1054. 'image': 'busybox',
  1055. 'environment': {'SPRING_JPA_HIBERNATE_DDL-AUTO': 'none'}
  1056. }},
  1057. 'working_dir',
  1058. 'filename.yml'
  1059. )
  1060. ).services
  1061. self.assertEqual(services[0]['environment']['SPRING_JPA_HIBERNATE_DDL-AUTO'], 'none')
  1062. def test_load_yaml_with_yaml_error(self):
  1063. tmpdir = py.test.ensuretemp('invalid_yaml_test')
  1064. self.addCleanup(tmpdir.remove)
  1065. invalid_yaml_file = tmpdir.join('docker-compose.yml')
  1066. invalid_yaml_file.write("""
  1067. web:
  1068. this is bogus: ok: what
  1069. """)
  1070. with pytest.raises(ConfigurationError) as exc:
  1071. config.load_yaml(str(invalid_yaml_file))
  1072. assert 'line 3, column 32' in exc.exconly()
  1073. def test_validate_extra_hosts_invalid(self):
  1074. with pytest.raises(ConfigurationError) as exc:
  1075. config.load(build_config_details({
  1076. 'web': {
  1077. 'image': 'alpine',
  1078. 'extra_hosts': "www.example.com: 192.168.0.17",
  1079. }
  1080. }))
  1081. assert "web.extra_hosts contains an invalid type" in exc.exconly()
  1082. def test_validate_extra_hosts_invalid_list(self):
  1083. with pytest.raises(ConfigurationError) as exc:
  1084. config.load(build_config_details({
  1085. 'web': {
  1086. 'image': 'alpine',
  1087. 'extra_hosts': [
  1088. {'www.example.com': '192.168.0.17'},
  1089. {'api.example.com': '192.168.0.18'}
  1090. ],
  1091. }
  1092. }))
  1093. assert "which is an invalid type" in exc.exconly()
  1094. def test_normalize_dns_options(self):
  1095. actual = config.load(build_config_details({
  1096. 'web': {
  1097. 'image': 'alpine',
  1098. 'dns': '8.8.8.8',
  1099. 'dns_search': 'domain.local',
  1100. }
  1101. }))
  1102. assert actual.services == [
  1103. {
  1104. 'name': 'web',
  1105. 'image': 'alpine',
  1106. 'dns': ['8.8.8.8'],
  1107. 'dns_search': ['domain.local'],
  1108. }
  1109. ]
  1110. def test_tmpfs_option(self):
  1111. actual = config.load(build_config_details({
  1112. 'version': '2',
  1113. 'services': {
  1114. 'web': {
  1115. 'image': 'alpine',
  1116. 'tmpfs': '/run',
  1117. }
  1118. }
  1119. }))
  1120. assert actual.services == [
  1121. {
  1122. 'name': 'web',
  1123. 'image': 'alpine',
  1124. 'tmpfs': ['/run'],
  1125. }
  1126. ]
  1127. def test_merge_service_dicts_from_files_with_extends_in_base(self):
  1128. base = {
  1129. 'volumes': ['.:/app'],
  1130. 'extends': {'service': 'app'}
  1131. }
  1132. override = {
  1133. 'image': 'alpine:edge',
  1134. }
  1135. actual = config.merge_service_dicts_from_files(
  1136. base,
  1137. override,
  1138. DEFAULT_VERSION)
  1139. assert actual == {
  1140. 'image': 'alpine:edge',
  1141. 'volumes': ['.:/app'],
  1142. 'extends': {'service': 'app'}
  1143. }
  1144. def test_merge_service_dicts_from_files_with_extends_in_override(self):
  1145. base = {
  1146. 'volumes': ['.:/app'],
  1147. 'extends': {'service': 'app'}
  1148. }
  1149. override = {
  1150. 'image': 'alpine:edge',
  1151. 'extends': {'service': 'foo'}
  1152. }
  1153. actual = config.merge_service_dicts_from_files(
  1154. base,
  1155. override,
  1156. DEFAULT_VERSION)
  1157. assert actual == {
  1158. 'image': 'alpine:edge',
  1159. 'volumes': ['.:/app'],
  1160. 'extends': {'service': 'foo'}
  1161. }
  1162. def test_merge_build_args(self):
  1163. base = {
  1164. 'build': {
  1165. 'context': '.',
  1166. 'args': {
  1167. 'ONE': '1',
  1168. 'TWO': '2',
  1169. },
  1170. }
  1171. }
  1172. override = {
  1173. 'build': {
  1174. 'args': {
  1175. 'TWO': 'dos',
  1176. 'THREE': '3',
  1177. },
  1178. }
  1179. }
  1180. actual = config.merge_service_dicts(
  1181. base,
  1182. override,
  1183. DEFAULT_VERSION)
  1184. assert actual == {
  1185. 'build': {
  1186. 'context': '.',
  1187. 'args': {
  1188. 'ONE': '1',
  1189. 'TWO': 'dos',
  1190. 'THREE': '3',
  1191. },
  1192. }
  1193. }
  1194. def test_merge_logging_v1(self):
  1195. base = {
  1196. 'image': 'alpine:edge',
  1197. 'log_driver': 'something',
  1198. 'log_opt': {'foo': 'three'},
  1199. }
  1200. override = {
  1201. 'image': 'alpine:edge',
  1202. 'command': 'true',
  1203. }
  1204. actual = config.merge_service_dicts(base, override, V1)
  1205. assert actual == {
  1206. 'image': 'alpine:edge',
  1207. 'log_driver': 'something',
  1208. 'log_opt': {'foo': 'three'},
  1209. 'command': 'true',
  1210. }
  1211. def test_external_volume_config(self):
  1212. config_details = build_config_details({
  1213. 'version': '2',
  1214. 'services': {
  1215. 'bogus': {'image': 'busybox'}
  1216. },
  1217. 'volumes': {
  1218. 'ext': {'external': True},
  1219. 'ext2': {'external': {'name': 'aliased'}}
  1220. }
  1221. })
  1222. config_result = config.load(config_details)
  1223. volumes = config_result.volumes
  1224. assert 'ext' in volumes
  1225. assert volumes['ext']['external'] is True
  1226. assert 'ext2' in volumes
  1227. assert volumes['ext2']['external']['name'] == 'aliased'
  1228. def test_external_volume_invalid_config(self):
  1229. config_details = build_config_details({
  1230. 'version': '2',
  1231. 'services': {
  1232. 'bogus': {'image': 'busybox'}
  1233. },
  1234. 'volumes': {
  1235. 'ext': {'external': True, 'driver': 'foo'}
  1236. }
  1237. })
  1238. with pytest.raises(ConfigurationError):
  1239. config.load(config_details)
  1240. def test_depends_on_orders_services(self):
  1241. config_details = build_config_details({
  1242. 'version': '2',
  1243. 'services': {
  1244. 'one': {'image': 'busybox', 'depends_on': ['three', 'two']},
  1245. 'two': {'image': 'busybox', 'depends_on': ['three']},
  1246. 'three': {'image': 'busybox'},
  1247. },
  1248. })
  1249. actual = config.load(config_details)
  1250. assert (
  1251. [service['name'] for service in actual.services] ==
  1252. ['three', 'two', 'one']
  1253. )
  1254. def test_depends_on_unknown_service_errors(self):
  1255. config_details = build_config_details({
  1256. 'version': '2',
  1257. 'services': {
  1258. 'one': {'image': 'busybox', 'depends_on': ['three']},
  1259. },
  1260. })
  1261. with pytest.raises(ConfigurationError) as exc:
  1262. config.load(config_details)
  1263. assert "Service 'one' depends on service 'three'" in exc.exconly()
  1264. def test_linked_service_is_undefined(self):
  1265. with self.assertRaises(ConfigurationError):
  1266. config.load(
  1267. build_config_details({
  1268. 'version': '2',
  1269. 'services': {
  1270. 'web': {'image': 'busybox', 'links': ['db:db']},
  1271. },
  1272. })
  1273. )
  1274. def test_load_dockerfile_without_context(self):
  1275. config_details = build_config_details({
  1276. 'version': '2',
  1277. 'services': {
  1278. 'one': {'build': {'dockerfile': 'Dockerfile.foo'}},
  1279. },
  1280. })
  1281. with pytest.raises(ConfigurationError) as exc:
  1282. config.load(config_details)
  1283. assert 'has neither an image nor a build context' in exc.exconly()
  1284. class NetworkModeTest(unittest.TestCase):
  1285. def test_network_mode_standard(self):
  1286. config_data = config.load(build_config_details({
  1287. 'version': '2',
  1288. 'services': {
  1289. 'web': {
  1290. 'image': 'busybox',
  1291. 'command': "top",
  1292. 'network_mode': 'bridge',
  1293. },
  1294. },
  1295. }))
  1296. assert config_data.services[0]['network_mode'] == 'bridge'
  1297. def test_network_mode_standard_v1(self):
  1298. config_data = config.load(build_config_details({
  1299. 'web': {
  1300. 'image': 'busybox',
  1301. 'command': "top",
  1302. 'net': 'bridge',
  1303. },
  1304. }))
  1305. assert config_data.services[0]['network_mode'] == 'bridge'
  1306. assert 'net' not in config_data.services[0]
  1307. def test_network_mode_container(self):
  1308. config_data = config.load(build_config_details({
  1309. 'version': '2',
  1310. 'services': {
  1311. 'web': {
  1312. 'image': 'busybox',
  1313. 'command': "top",
  1314. 'network_mode': 'container:foo',
  1315. },
  1316. },
  1317. }))
  1318. assert config_data.services[0]['network_mode'] == 'container:foo'
  1319. def test_network_mode_container_v1(self):
  1320. config_data = config.load(build_config_details({
  1321. 'web': {
  1322. 'image': 'busybox',
  1323. 'command': "top",
  1324. 'net': 'container:foo',
  1325. },
  1326. }))
  1327. assert config_data.services[0]['network_mode'] == 'container:foo'
  1328. def test_network_mode_service(self):
  1329. config_data = config.load(build_config_details({
  1330. 'version': '2',
  1331. 'services': {
  1332. 'web': {
  1333. 'image': 'busybox',
  1334. 'command': "top",
  1335. 'network_mode': 'service:foo',
  1336. },
  1337. 'foo': {
  1338. 'image': 'busybox',
  1339. 'command': "top",
  1340. },
  1341. },
  1342. }))
  1343. assert config_data.services[1]['network_mode'] == 'service:foo'
  1344. def test_network_mode_service_v1(self):
  1345. config_data = config.load(build_config_details({
  1346. 'web': {
  1347. 'image': 'busybox',
  1348. 'command': "top",
  1349. 'net': 'container:foo',
  1350. },
  1351. 'foo': {
  1352. 'image': 'busybox',
  1353. 'command': "top",
  1354. },
  1355. }))
  1356. assert config_data.services[1]['network_mode'] == 'service:foo'
  1357. def test_network_mode_service_nonexistent(self):
  1358. with pytest.raises(ConfigurationError) as excinfo:
  1359. config.load(build_config_details({
  1360. 'version': '2',
  1361. 'services': {
  1362. 'web': {
  1363. 'image': 'busybox',
  1364. 'command': "top",
  1365. 'network_mode': 'service:foo',
  1366. },
  1367. },
  1368. }))
  1369. assert "service 'foo' which is undefined" in excinfo.exconly()
  1370. def test_network_mode_plus_networks_is_invalid(self):
  1371. with pytest.raises(ConfigurationError) as excinfo:
  1372. config.load(build_config_details({
  1373. 'version': '2',
  1374. 'services': {
  1375. 'web': {
  1376. 'image': 'busybox',
  1377. 'command': "top",
  1378. 'network_mode': 'bridge',
  1379. 'networks': ['front'],
  1380. },
  1381. },
  1382. 'networks': {
  1383. 'front': None,
  1384. }
  1385. }))
  1386. assert "'network_mode' and 'networks' cannot be combined" in excinfo.exconly()
  1387. class PortsTest(unittest.TestCase):
  1388. INVALID_PORTS_TYPES = [
  1389. {"1": "8000"},
  1390. False,
  1391. "8000",
  1392. 8000,
  1393. ]
  1394. NON_UNIQUE_SINGLE_PORTS = [
  1395. ["8000", "8000"],
  1396. ]
  1397. INVALID_PORT_MAPPINGS = [
  1398. ["8000-8001:8000"],
  1399. ]
  1400. VALID_SINGLE_PORTS = [
  1401. ["8000"],
  1402. ["8000/tcp"],
  1403. ["8000", "9000"],
  1404. [8000],
  1405. [8000, 9000],
  1406. ]
  1407. VALID_PORT_MAPPINGS = [
  1408. ["8000:8050"],
  1409. ["49153-49154:3002-3003"],
  1410. ]
  1411. def test_config_invalid_ports_type_validation(self):
  1412. for invalid_ports in self.INVALID_PORTS_TYPES:
  1413. with pytest.raises(ConfigurationError) as exc:
  1414. self.check_config({'ports': invalid_ports})
  1415. assert "contains an invalid type" in exc.value.msg
  1416. def test_config_non_unique_ports_validation(self):
  1417. for invalid_ports in self.NON_UNIQUE_SINGLE_PORTS:
  1418. with pytest.raises(ConfigurationError) as exc:
  1419. self.check_config({'ports': invalid_ports})
  1420. assert "non-unique" in exc.value.msg
  1421. def test_config_invalid_ports_format_validation(self):
  1422. for invalid_ports in self.INVALID_PORT_MAPPINGS:
  1423. with pytest.raises(ConfigurationError) as exc:
  1424. self.check_config({'ports': invalid_ports})
  1425. assert "Port ranges don't match in length" in exc.value.msg
  1426. def test_config_valid_ports_format_validation(self):
  1427. for valid_ports in self.VALID_SINGLE_PORTS + self.VALID_PORT_MAPPINGS:
  1428. self.check_config({'ports': valid_ports})
  1429. def test_config_invalid_expose_type_validation(self):
  1430. for invalid_expose in self.INVALID_PORTS_TYPES:
  1431. with pytest.raises(ConfigurationError) as exc:
  1432. self.check_config({'expose': invalid_expose})
  1433. assert "contains an invalid type" in exc.value.msg
  1434. def test_config_non_unique_expose_validation(self):
  1435. for invalid_expose in self.NON_UNIQUE_SINGLE_PORTS:
  1436. with pytest.raises(ConfigurationError) as exc:
  1437. self.check_config({'expose': invalid_expose})
  1438. assert "non-unique" in exc.value.msg
  1439. def test_config_invalid_expose_format_validation(self):
  1440. # Valid port mappings ARE NOT valid 'expose' entries
  1441. for invalid_expose in self.INVALID_PORT_MAPPINGS + self.VALID_PORT_MAPPINGS:
  1442. with pytest.raises(ConfigurationError) as exc:
  1443. self.check_config({'expose': invalid_expose})
  1444. assert "should be of the format" in exc.value.msg
  1445. def test_config_valid_expose_format_validation(self):
  1446. # Valid single ports ARE valid 'expose' entries
  1447. for valid_expose in self.VALID_SINGLE_PORTS:
  1448. self.check_config({'expose': valid_expose})
  1449. def check_config(self, cfg):
  1450. config.load(
  1451. build_config_details(
  1452. {'web': dict(image='busybox', **cfg)},
  1453. 'working_dir',
  1454. 'filename.yml'
  1455. )
  1456. )
  1457. class InterpolationTest(unittest.TestCase):
  1458. @mock.patch.dict(os.environ)
  1459. def test_config_file_with_environment_file(self):
  1460. project_dir = 'tests/fixtures/default-env-file'
  1461. service_dicts = config.load(
  1462. config.find(
  1463. project_dir, None, Environment.from_env_file(project_dir)
  1464. )
  1465. ).services
  1466. self.assertEqual(service_dicts[0], {
  1467. 'name': 'web',
  1468. 'image': 'alpine:latest',
  1469. 'ports': ['5643', '9999'],
  1470. 'command': 'true'
  1471. })
  1472. @mock.patch.dict(os.environ)
  1473. def test_config_file_with_environment_variable(self):
  1474. project_dir = 'tests/fixtures/environment-interpolation'
  1475. os.environ.update(
  1476. IMAGE="busybox",
  1477. HOST_PORT="80",
  1478. LABEL_VALUE="myvalue",
  1479. )
  1480. service_dicts = config.load(
  1481. config.find(
  1482. project_dir, None, Environment.from_env_file(project_dir)
  1483. )
  1484. ).services
  1485. self.assertEqual(service_dicts, [
  1486. {
  1487. 'name': 'web',
  1488. 'image': 'busybox',
  1489. 'ports': ['80:8000'],
  1490. 'labels': {'mylabel': 'myvalue'},
  1491. 'hostname': 'host-',
  1492. 'command': '${ESCAPED}',
  1493. }
  1494. ])
  1495. @mock.patch.dict(os.environ)
  1496. def test_unset_variable_produces_warning(self):
  1497. os.environ.pop('FOO', None)
  1498. os.environ.pop('BAR', None)
  1499. config_details = build_config_details(
  1500. {
  1501. 'web': {
  1502. 'image': '${FOO}',
  1503. 'command': '${BAR}',
  1504. 'container_name': '${BAR}',
  1505. },
  1506. },
  1507. '.',
  1508. None,
  1509. )
  1510. with mock.patch('compose.config.environment.log') as log:
  1511. config.load(config_details)
  1512. self.assertEqual(2, log.warn.call_count)
  1513. warnings = sorted(args[0][0] for args in log.warn.call_args_list)
  1514. self.assertIn('BAR', warnings[0])
  1515. self.assertIn('FOO', warnings[1])
  1516. @mock.patch.dict(os.environ)
  1517. def test_invalid_interpolation(self):
  1518. with self.assertRaises(config.ConfigurationError) as cm:
  1519. config.load(
  1520. build_config_details(
  1521. {'web': {'image': '${'}},
  1522. 'working_dir',
  1523. 'filename.yml'
  1524. )
  1525. )
  1526. self.assertIn('Invalid', cm.exception.msg)
  1527. self.assertIn('for "image" option', cm.exception.msg)
  1528. self.assertIn('in service "web"', cm.exception.msg)
  1529. self.assertIn('"${"', cm.exception.msg)
  1530. def test_empty_environment_key_allowed(self):
  1531. service_dict = config.load(
  1532. build_config_details(
  1533. {
  1534. 'web': {
  1535. 'build': '.',
  1536. 'environment': {
  1537. 'POSTGRES_PASSWORD': ''
  1538. },
  1539. },
  1540. },
  1541. '.',
  1542. None,
  1543. )
  1544. ).services[0]
  1545. self.assertEquals(service_dict['environment']['POSTGRES_PASSWORD'], '')
  1546. class VolumeConfigTest(unittest.TestCase):
  1547. def test_no_binding(self):
  1548. d = make_service_dict('foo', {'build': '.', 'volumes': ['/data']}, working_dir='.')
  1549. self.assertEqual(d['volumes'], ['/data'])
  1550. @mock.patch.dict(os.environ)
  1551. def test_volume_binding_with_environment_variable(self):
  1552. os.environ['VOLUME_PATH'] = '/host/path'
  1553. d = config.load(
  1554. build_config_details(
  1555. {'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
  1556. '.',
  1557. None,
  1558. )
  1559. ).services[0]
  1560. self.assertEqual(d['volumes'], [VolumeSpec.parse('/host/path:/container/path')])
  1561. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1562. @mock.patch.dict(os.environ)
  1563. def test_volume_binding_with_home(self):
  1564. os.environ['HOME'] = '/home/user'
  1565. d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
  1566. self.assertEqual(d['volumes'], ['/home/user:/container/path'])
  1567. def test_name_does_not_expand(self):
  1568. d = make_service_dict('foo', {'build': '.', 'volumes': ['mydatavolume:/data']}, working_dir='.')
  1569. self.assertEqual(d['volumes'], ['mydatavolume:/data'])
  1570. def test_absolute_posix_path_does_not_expand(self):
  1571. d = make_service_dict('foo', {'build': '.', 'volumes': ['/var/lib/data:/data']}, working_dir='.')
  1572. self.assertEqual(d['volumes'], ['/var/lib/data:/data'])
  1573. def test_absolute_windows_path_does_not_expand(self):
  1574. d = make_service_dict('foo', {'build': '.', 'volumes': ['c:\\data:/data']}, working_dir='.')
  1575. self.assertEqual(d['volumes'], ['c:\\data:/data'])
  1576. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1577. def test_relative_path_does_expand_posix(self):
  1578. d = make_service_dict(
  1579. 'foo',
  1580. {'build': '.', 'volumes': ['./data:/data']},
  1581. working_dir='/home/me/myproject')
  1582. self.assertEqual(d['volumes'], ['/home/me/myproject/data:/data'])
  1583. d = make_service_dict(
  1584. 'foo',
  1585. {'build': '.', 'volumes': ['.:/data']},
  1586. working_dir='/home/me/myproject')
  1587. self.assertEqual(d['volumes'], ['/home/me/myproject:/data'])
  1588. d = make_service_dict(
  1589. 'foo',
  1590. {'build': '.', 'volumes': ['../otherproject:/data']},
  1591. working_dir='/home/me/myproject')
  1592. self.assertEqual(d['volumes'], ['/home/me/otherproject:/data'])
  1593. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='windows paths')
  1594. def test_relative_path_does_expand_windows(self):
  1595. d = make_service_dict(
  1596. 'foo',
  1597. {'build': '.', 'volumes': ['./data:/data']},
  1598. working_dir='c:\\Users\\me\\myproject')
  1599. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject\\data:/data'])
  1600. d = make_service_dict(
  1601. 'foo',
  1602. {'build': '.', 'volumes': ['.:/data']},
  1603. working_dir='c:\\Users\\me\\myproject')
  1604. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject:/data'])
  1605. d = make_service_dict(
  1606. 'foo',
  1607. {'build': '.', 'volumes': ['../otherproject:/data']},
  1608. working_dir='c:\\Users\\me\\myproject')
  1609. self.assertEqual(d['volumes'], ['c:\\Users\\me\\otherproject:/data'])
  1610. @mock.patch.dict(os.environ)
  1611. def test_home_directory_with_driver_does_not_expand(self):
  1612. os.environ['NAME'] = 'surprise!'
  1613. d = make_service_dict('foo', {
  1614. 'build': '.',
  1615. 'volumes': ['~:/data'],
  1616. 'volume_driver': 'foodriver',
  1617. }, working_dir='.')
  1618. self.assertEqual(d['volumes'], ['~:/data'])
  1619. def test_volume_path_with_non_ascii_directory(self):
  1620. volume = u'/Füü/data:/data'
  1621. container_path = config.resolve_volume_path(".", volume)
  1622. self.assertEqual(container_path, volume)
  1623. class MergePathMappingTest(object):
  1624. config_name = ""
  1625. def test_empty(self):
  1626. service_dict = config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1627. assert self.config_name not in service_dict
  1628. def test_no_override(self):
  1629. service_dict = config.merge_service_dicts(
  1630. {self.config_name: ['/foo:/code', '/data']},
  1631. {},
  1632. DEFAULT_VERSION)
  1633. assert set(service_dict[self.config_name]) == set(['/foo:/code', '/data'])
  1634. def test_no_base(self):
  1635. service_dict = config.merge_service_dicts(
  1636. {},
  1637. {self.config_name: ['/bar:/code']},
  1638. DEFAULT_VERSION)
  1639. assert set(service_dict[self.config_name]) == set(['/bar:/code'])
  1640. def test_override_explicit_path(self):
  1641. service_dict = config.merge_service_dicts(
  1642. {self.config_name: ['/foo:/code', '/data']},
  1643. {self.config_name: ['/bar:/code']},
  1644. DEFAULT_VERSION)
  1645. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1646. def test_add_explicit_path(self):
  1647. service_dict = config.merge_service_dicts(
  1648. {self.config_name: ['/foo:/code', '/data']},
  1649. {self.config_name: ['/bar:/code', '/quux:/data']},
  1650. DEFAULT_VERSION)
  1651. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/quux:/data'])
  1652. def test_remove_explicit_path(self):
  1653. service_dict = config.merge_service_dicts(
  1654. {self.config_name: ['/foo:/code', '/quux:/data']},
  1655. {self.config_name: ['/bar:/code', '/data']},
  1656. DEFAULT_VERSION)
  1657. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1658. class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
  1659. config_name = 'volumes'
  1660. class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
  1661. config_name = 'devices'
  1662. class BuildOrImageMergeTest(unittest.TestCase):
  1663. def test_merge_build_or_image_no_override(self):
  1664. self.assertEqual(
  1665. config.merge_service_dicts({'build': '.'}, {}, V1),
  1666. {'build': '.'},
  1667. )
  1668. self.assertEqual(
  1669. config.merge_service_dicts({'image': 'redis'}, {}, V1),
  1670. {'image': 'redis'},
  1671. )
  1672. def test_merge_build_or_image_override_with_same(self):
  1673. self.assertEqual(
  1674. config.merge_service_dicts({'build': '.'}, {'build': './web'}, V1),
  1675. {'build': './web'},
  1676. )
  1677. self.assertEqual(
  1678. config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}, V1),
  1679. {'image': 'postgres'},
  1680. )
  1681. def test_merge_build_or_image_override_with_other(self):
  1682. self.assertEqual(
  1683. config.merge_service_dicts({'build': '.'}, {'image': 'redis'}, V1),
  1684. {'image': 'redis'},
  1685. )
  1686. self.assertEqual(
  1687. config.merge_service_dicts({'image': 'redis'}, {'build': '.'}, V1),
  1688. {'build': '.'}
  1689. )
  1690. class MergeListsTest(object):
  1691. config_name = ""
  1692. base_config = []
  1693. override_config = []
  1694. def merged_config(self):
  1695. return set(self.base_config) | set(self.override_config)
  1696. def test_empty(self):
  1697. assert self.config_name not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1698. def test_no_override(self):
  1699. service_dict = config.merge_service_dicts(
  1700. {self.config_name: self.base_config},
  1701. {},
  1702. DEFAULT_VERSION)
  1703. assert set(service_dict[self.config_name]) == set(self.base_config)
  1704. def test_no_base(self):
  1705. service_dict = config.merge_service_dicts(
  1706. {},
  1707. {self.config_name: self.base_config},
  1708. DEFAULT_VERSION)
  1709. assert set(service_dict[self.config_name]) == set(self.base_config)
  1710. def test_add_item(self):
  1711. service_dict = config.merge_service_dicts(
  1712. {self.config_name: self.base_config},
  1713. {self.config_name: self.override_config},
  1714. DEFAULT_VERSION)
  1715. assert set(service_dict[self.config_name]) == set(self.merged_config())
  1716. class MergePortsTest(unittest.TestCase, MergeListsTest):
  1717. config_name = 'ports'
  1718. base_config = ['10:8000', '9000']
  1719. override_config = ['20:8000']
  1720. def test_duplicate_port_mappings(self):
  1721. service_dict = config.merge_service_dicts(
  1722. {self.config_name: self.base_config},
  1723. {self.config_name: self.base_config},
  1724. DEFAULT_VERSION
  1725. )
  1726. assert set(service_dict[self.config_name]) == set(self.base_config)
  1727. class MergeNetworksTest(unittest.TestCase, MergeListsTest):
  1728. config_name = 'networks'
  1729. base_config = ['frontend', 'backend']
  1730. override_config = ['monitoring']
  1731. class MergeStringsOrListsTest(unittest.TestCase):
  1732. def test_no_override(self):
  1733. service_dict = config.merge_service_dicts(
  1734. {'dns': '8.8.8.8'},
  1735. {},
  1736. DEFAULT_VERSION)
  1737. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1738. def test_no_base(self):
  1739. service_dict = config.merge_service_dicts(
  1740. {},
  1741. {'dns': '8.8.8.8'},
  1742. DEFAULT_VERSION)
  1743. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1744. def test_add_string(self):
  1745. service_dict = config.merge_service_dicts(
  1746. {'dns': ['8.8.8.8']},
  1747. {'dns': '9.9.9.9'},
  1748. DEFAULT_VERSION)
  1749. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1750. def test_add_list(self):
  1751. service_dict = config.merge_service_dicts(
  1752. {'dns': '8.8.8.8'},
  1753. {'dns': ['9.9.9.9']},
  1754. DEFAULT_VERSION)
  1755. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1756. class MergeLabelsTest(unittest.TestCase):
  1757. def test_empty(self):
  1758. assert 'labels' not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1759. def test_no_override(self):
  1760. service_dict = config.merge_service_dicts(
  1761. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1762. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1763. DEFAULT_VERSION)
  1764. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1765. def test_no_base(self):
  1766. service_dict = config.merge_service_dicts(
  1767. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1768. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1769. DEFAULT_VERSION)
  1770. assert service_dict['labels'] == {'foo': '2'}
  1771. def test_override_explicit_value(self):
  1772. service_dict = config.merge_service_dicts(
  1773. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1774. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1775. DEFAULT_VERSION)
  1776. assert service_dict['labels'] == {'foo': '2', 'bar': ''}
  1777. def test_add_explicit_value(self):
  1778. service_dict = config.merge_service_dicts(
  1779. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1780. make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
  1781. DEFAULT_VERSION)
  1782. assert service_dict['labels'] == {'foo': '1', 'bar': '2'}
  1783. def test_remove_explicit_value(self):
  1784. service_dict = config.merge_service_dicts(
  1785. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
  1786. make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
  1787. DEFAULT_VERSION)
  1788. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1789. class MemoryOptionsTest(unittest.TestCase):
  1790. def test_validation_fails_with_just_memswap_limit(self):
  1791. """
  1792. When you set a 'memswap_limit' it is invalid config unless you also set
  1793. a mem_limit
  1794. """
  1795. with pytest.raises(ConfigurationError) as excinfo:
  1796. config.load(
  1797. build_config_details(
  1798. {
  1799. 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
  1800. },
  1801. 'tests/fixtures/extends',
  1802. 'filename.yml'
  1803. )
  1804. )
  1805. assert "foo.memswap_limit is invalid: when defining " \
  1806. "'memswap_limit' you must set 'mem_limit' as well" \
  1807. in excinfo.exconly()
  1808. def test_validation_with_correct_memswap_values(self):
  1809. service_dict = config.load(
  1810. build_config_details(
  1811. {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
  1812. 'tests/fixtures/extends',
  1813. 'common.yml'
  1814. )
  1815. ).services
  1816. self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
  1817. def test_memswap_can_be_a_string(self):
  1818. service_dict = config.load(
  1819. build_config_details(
  1820. {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
  1821. 'tests/fixtures/extends',
  1822. 'common.yml'
  1823. )
  1824. ).services
  1825. self.assertEqual(service_dict[0]['memswap_limit'], "512M")
  1826. class EnvTest(unittest.TestCase):
  1827. def test_parse_environment_as_list(self):
  1828. environment = [
  1829. 'NORMAL=F1',
  1830. 'CONTAINS_EQUALS=F=2',
  1831. 'TRAILING_EQUALS=',
  1832. ]
  1833. self.assertEqual(
  1834. config.parse_environment(environment),
  1835. {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
  1836. )
  1837. def test_parse_environment_as_dict(self):
  1838. environment = {
  1839. 'NORMAL': 'F1',
  1840. 'CONTAINS_EQUALS': 'F=2',
  1841. 'TRAILING_EQUALS': None,
  1842. }
  1843. self.assertEqual(config.parse_environment(environment), environment)
  1844. def test_parse_environment_invalid(self):
  1845. with self.assertRaises(ConfigurationError):
  1846. config.parse_environment('a=b')
  1847. def test_parse_environment_empty(self):
  1848. self.assertEqual(config.parse_environment(None), {})
  1849. @mock.patch.dict(os.environ)
  1850. def test_resolve_environment(self):
  1851. os.environ['FILE_DEF'] = 'E1'
  1852. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1853. os.environ['ENV_DEF'] = 'E3'
  1854. service_dict = {
  1855. 'build': '.',
  1856. 'environment': {
  1857. 'FILE_DEF': 'F1',
  1858. 'FILE_DEF_EMPTY': '',
  1859. 'ENV_DEF': None,
  1860. 'NO_DEF': None
  1861. },
  1862. }
  1863. self.assertEqual(
  1864. resolve_environment(
  1865. service_dict, Environment.from_env_file(None)
  1866. ),
  1867. {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None},
  1868. )
  1869. def test_resolve_environment_from_env_file(self):
  1870. self.assertEqual(
  1871. resolve_environment({'env_file': ['tests/fixtures/env/one.env']}),
  1872. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
  1873. )
  1874. def test_resolve_environment_with_multiple_env_files(self):
  1875. service_dict = {
  1876. 'env_file': [
  1877. 'tests/fixtures/env/one.env',
  1878. 'tests/fixtures/env/two.env'
  1879. ]
  1880. }
  1881. self.assertEqual(
  1882. resolve_environment(service_dict),
  1883. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
  1884. )
  1885. def test_resolve_environment_nonexistent_file(self):
  1886. with pytest.raises(ConfigurationError) as exc:
  1887. config.load(build_config_details(
  1888. {'foo': {'image': 'example', 'env_file': 'nonexistent.env'}},
  1889. working_dir='tests/fixtures/env'))
  1890. assert 'Couldn\'t find env file' in exc.exconly()
  1891. assert 'nonexistent.env' in exc.exconly()
  1892. @mock.patch.dict(os.environ)
  1893. def test_resolve_environment_from_env_file_with_empty_values(self):
  1894. os.environ['FILE_DEF'] = 'E1'
  1895. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1896. os.environ['ENV_DEF'] = 'E3'
  1897. self.assertEqual(
  1898. resolve_environment(
  1899. {'env_file': ['tests/fixtures/env/resolve.env']},
  1900. Environment.from_env_file(None)
  1901. ),
  1902. {
  1903. 'FILE_DEF': u'bär',
  1904. 'FILE_DEF_EMPTY': '',
  1905. 'ENV_DEF': 'E3',
  1906. 'NO_DEF': None
  1907. },
  1908. )
  1909. @mock.patch.dict(os.environ)
  1910. def test_resolve_build_args(self):
  1911. os.environ['env_arg'] = 'value2'
  1912. build = {
  1913. 'context': '.',
  1914. 'args': {
  1915. 'arg1': 'value1',
  1916. 'empty_arg': '',
  1917. 'env_arg': None,
  1918. 'no_env': None
  1919. }
  1920. }
  1921. self.assertEqual(
  1922. resolve_build_args(build, Environment.from_env_file(build['context'])),
  1923. {'arg1': 'value1', 'empty_arg': '', 'env_arg': 'value2', 'no_env': None},
  1924. )
  1925. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  1926. @mock.patch.dict(os.environ)
  1927. def test_resolve_path(self):
  1928. os.environ['HOSTENV'] = '/tmp'
  1929. os.environ['CONTAINERENV'] = '/host/tmp'
  1930. service_dict = config.load(
  1931. build_config_details(
  1932. {'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
  1933. "tests/fixtures/env",
  1934. )
  1935. ).services[0]
  1936. self.assertEqual(
  1937. set(service_dict['volumes']),
  1938. set([VolumeSpec.parse('/tmp:/host/tmp')]))
  1939. service_dict = config.load(
  1940. build_config_details(
  1941. {'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
  1942. "tests/fixtures/env",
  1943. )
  1944. ).services[0]
  1945. self.assertEqual(
  1946. set(service_dict['volumes']),
  1947. set([VolumeSpec.parse('/opt/tmp:/opt/host/tmp')]))
  1948. def load_from_filename(filename):
  1949. return config.load(
  1950. config.find('.', [filename], Environment.from_env_file('.'))
  1951. ).services
  1952. class ExtendsTest(unittest.TestCase):
  1953. def test_extends(self):
  1954. service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
  1955. self.assertEqual(service_sort(service_dicts), service_sort([
  1956. {
  1957. 'name': 'mydb',
  1958. 'image': 'busybox',
  1959. 'command': 'top',
  1960. },
  1961. {
  1962. 'name': 'myweb',
  1963. 'image': 'busybox',
  1964. 'command': 'top',
  1965. 'network_mode': 'bridge',
  1966. 'links': ['mydb:db'],
  1967. 'environment': {
  1968. "FOO": "1",
  1969. "BAR": "2",
  1970. "BAZ": "2",
  1971. },
  1972. }
  1973. ]))
  1974. def test_merging_env_labels_ulimits(self):
  1975. service_dicts = load_from_filename('tests/fixtures/extends/common-env-labels-ulimits.yml')
  1976. self.assertEqual(service_sort(service_dicts), service_sort([
  1977. {
  1978. 'name': 'web',
  1979. 'image': 'busybox',
  1980. 'command': '/bin/true',
  1981. 'network_mode': 'host',
  1982. 'environment': {
  1983. "FOO": "2",
  1984. "BAR": "1",
  1985. "BAZ": "3",
  1986. },
  1987. 'labels': {'label': 'one'},
  1988. 'ulimits': {'nproc': 65535, 'memlock': {'soft': 1024, 'hard': 2048}}
  1989. }
  1990. ]))
  1991. def test_nested(self):
  1992. service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
  1993. self.assertEqual(service_dicts, [
  1994. {
  1995. 'name': 'myweb',
  1996. 'image': 'busybox',
  1997. 'command': '/bin/true',
  1998. 'network_mode': 'host',
  1999. 'environment': {
  2000. "FOO": "2",
  2001. "BAR": "2",
  2002. },
  2003. },
  2004. ])
  2005. def test_self_referencing_file(self):
  2006. """
  2007. We specify a 'file' key that is the filename we're already in.
  2008. """
  2009. service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
  2010. self.assertEqual(service_sort(service_dicts), service_sort([
  2011. {
  2012. 'environment':
  2013. {
  2014. 'YEP': '1', 'BAR': '1', 'BAZ': '3'
  2015. },
  2016. 'image': 'busybox',
  2017. 'name': 'myweb'
  2018. },
  2019. {
  2020. 'environment':
  2021. {'YEP': '1'},
  2022. 'image': 'busybox',
  2023. 'name': 'otherweb'
  2024. },
  2025. {
  2026. 'environment':
  2027. {'YEP': '1', 'BAZ': '3'},
  2028. 'image': 'busybox',
  2029. 'name': 'web'
  2030. }
  2031. ]))
  2032. def test_circular(self):
  2033. with pytest.raises(config.CircularReference) as exc:
  2034. load_from_filename('tests/fixtures/extends/circle-1.yml')
  2035. path = [
  2036. (os.path.basename(filename), service_name)
  2037. for (filename, service_name) in exc.value.trail
  2038. ]
  2039. expected = [
  2040. ('circle-1.yml', 'web'),
  2041. ('circle-2.yml', 'other'),
  2042. ('circle-1.yml', 'web'),
  2043. ]
  2044. self.assertEqual(path, expected)
  2045. def test_extends_validation_empty_dictionary(self):
  2046. with pytest.raises(ConfigurationError) as excinfo:
  2047. config.load(
  2048. build_config_details(
  2049. {
  2050. 'web': {'image': 'busybox', 'extends': {}},
  2051. },
  2052. 'tests/fixtures/extends',
  2053. 'filename.yml'
  2054. )
  2055. )
  2056. assert 'service' in excinfo.exconly()
  2057. def test_extends_validation_missing_service_key(self):
  2058. with pytest.raises(ConfigurationError) as excinfo:
  2059. config.load(
  2060. build_config_details(
  2061. {
  2062. 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
  2063. },
  2064. 'tests/fixtures/extends',
  2065. 'filename.yml'
  2066. )
  2067. )
  2068. assert "'service' is a required property" in excinfo.exconly()
  2069. def test_extends_validation_invalid_key(self):
  2070. with pytest.raises(ConfigurationError) as excinfo:
  2071. config.load(
  2072. build_config_details(
  2073. {
  2074. 'web': {
  2075. 'image': 'busybox',
  2076. 'extends': {
  2077. 'file': 'common.yml',
  2078. 'service': 'web',
  2079. 'rogue_key': 'is not allowed'
  2080. }
  2081. },
  2082. },
  2083. 'tests/fixtures/extends',
  2084. 'filename.yml'
  2085. )
  2086. )
  2087. assert "web.extends contains unsupported option: 'rogue_key'" \
  2088. in excinfo.exconly()
  2089. def test_extends_validation_sub_property_key(self):
  2090. with pytest.raises(ConfigurationError) as excinfo:
  2091. config.load(
  2092. build_config_details(
  2093. {
  2094. 'web': {
  2095. 'image': 'busybox',
  2096. 'extends': {
  2097. 'file': 1,
  2098. 'service': 'web',
  2099. }
  2100. },
  2101. },
  2102. 'tests/fixtures/extends',
  2103. 'filename.yml'
  2104. )
  2105. )
  2106. assert "web.extends.file contains 1, which is an invalid type, it should be a string" \
  2107. in excinfo.exconly()
  2108. def test_extends_validation_no_file_key_no_filename_set(self):
  2109. dictionary = {'extends': {'service': 'web'}}
  2110. with pytest.raises(ConfigurationError) as excinfo:
  2111. make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
  2112. assert 'file' in excinfo.exconly()
  2113. def test_extends_validation_valid_config(self):
  2114. service = config.load(
  2115. build_config_details(
  2116. {
  2117. 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
  2118. },
  2119. 'tests/fixtures/extends',
  2120. 'common.yml'
  2121. )
  2122. ).services
  2123. self.assertEquals(len(service), 1)
  2124. self.assertIsInstance(service[0], dict)
  2125. self.assertEquals(service[0]['command'], "/bin/true")
  2126. def test_extended_service_with_invalid_config(self):
  2127. with pytest.raises(ConfigurationError) as exc:
  2128. load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
  2129. assert (
  2130. "myweb has neither an image nor a build context specified" in
  2131. exc.exconly()
  2132. )
  2133. def test_extended_service_with_valid_config(self):
  2134. service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
  2135. self.assertEquals(service[0]['command'], "top")
  2136. def test_extends_file_defaults_to_self(self):
  2137. """
  2138. Test not specifying a file in our extends options that the
  2139. config is valid and correctly extends from itself.
  2140. """
  2141. service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
  2142. self.assertEqual(service_sort(service_dicts), service_sort([
  2143. {
  2144. 'name': 'myweb',
  2145. 'image': 'busybox',
  2146. 'environment': {
  2147. "BAR": "1",
  2148. "BAZ": "3",
  2149. }
  2150. },
  2151. {
  2152. 'name': 'web',
  2153. 'image': 'busybox',
  2154. 'environment': {
  2155. "BAZ": "3",
  2156. }
  2157. }
  2158. ]))
  2159. def test_invalid_links_in_extended_service(self):
  2160. with pytest.raises(ConfigurationError) as excinfo:
  2161. load_from_filename('tests/fixtures/extends/invalid-links.yml')
  2162. assert "services with 'links' cannot be extended" in excinfo.exconly()
  2163. def test_invalid_volumes_from_in_extended_service(self):
  2164. with pytest.raises(ConfigurationError) as excinfo:
  2165. load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
  2166. assert "services with 'volumes_from' cannot be extended" in excinfo.exconly()
  2167. def test_invalid_net_in_extended_service(self):
  2168. with pytest.raises(ConfigurationError) as excinfo:
  2169. load_from_filename('tests/fixtures/extends/invalid-net-v2.yml')
  2170. assert 'network_mode: service' in excinfo.exconly()
  2171. assert 'cannot be extended' in excinfo.exconly()
  2172. with pytest.raises(ConfigurationError) as excinfo:
  2173. load_from_filename('tests/fixtures/extends/invalid-net.yml')
  2174. assert 'net: container' in excinfo.exconly()
  2175. assert 'cannot be extended' in excinfo.exconly()
  2176. @mock.patch.dict(os.environ)
  2177. def test_load_config_runs_interpolation_in_extended_service(self):
  2178. os.environ.update(HOSTNAME_VALUE="penguin")
  2179. expected_interpolated_value = "host-penguin"
  2180. service_dicts = load_from_filename(
  2181. 'tests/fixtures/extends/valid-interpolation.yml')
  2182. for service in service_dicts:
  2183. assert service['hostname'] == expected_interpolated_value
  2184. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2185. def test_volume_path(self):
  2186. dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
  2187. paths = [
  2188. VolumeSpec(
  2189. os.path.abspath('tests/fixtures/volume-path/common/foo'),
  2190. '/foo',
  2191. 'rw'),
  2192. VolumeSpec(
  2193. os.path.abspath('tests/fixtures/volume-path/bar'),
  2194. '/bar',
  2195. 'rw')
  2196. ]
  2197. self.assertEqual(set(dicts[0]['volumes']), set(paths))
  2198. def test_parent_build_path_dne(self):
  2199. child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
  2200. self.assertEqual(child, [
  2201. {
  2202. 'name': 'dnechild',
  2203. 'image': 'busybox',
  2204. 'command': '/bin/true',
  2205. 'environment': {
  2206. "FOO": "1",
  2207. "BAR": "2",
  2208. },
  2209. },
  2210. ])
  2211. def test_load_throws_error_when_base_service_does_not_exist(self):
  2212. with pytest.raises(ConfigurationError) as excinfo:
  2213. load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
  2214. assert "Cannot extend service 'foo'" in excinfo.exconly()
  2215. assert "Service not found" in excinfo.exconly()
  2216. def test_partial_service_config_in_extends_is_still_valid(self):
  2217. dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
  2218. self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
  2219. def test_extended_service_with_verbose_and_shorthand_way(self):
  2220. services = load_from_filename('tests/fixtures/extends/verbose-and-shorthand.yml')
  2221. self.assertEqual(service_sort(services), service_sort([
  2222. {
  2223. 'name': 'base',
  2224. 'image': 'busybox',
  2225. 'environment': {'BAR': '1'},
  2226. },
  2227. {
  2228. 'name': 'verbose',
  2229. 'image': 'busybox',
  2230. 'environment': {'BAR': '1', 'FOO': '1'},
  2231. },
  2232. {
  2233. 'name': 'shorthand',
  2234. 'image': 'busybox',
  2235. 'environment': {'BAR': '1', 'FOO': '2'},
  2236. },
  2237. ]))
  2238. @mock.patch.dict(os.environ)
  2239. def test_extends_with_environment_and_env_files(self):
  2240. tmpdir = py.test.ensuretemp('test_extends_with_environment')
  2241. self.addCleanup(tmpdir.remove)
  2242. commondir = tmpdir.mkdir('common')
  2243. commondir.join('base.yml').write("""
  2244. app:
  2245. image: 'example/app'
  2246. env_file:
  2247. - 'envs'
  2248. environment:
  2249. - SECRET
  2250. - TEST_ONE=common
  2251. - TEST_TWO=common
  2252. """)
  2253. tmpdir.join('docker-compose.yml').write("""
  2254. ext:
  2255. extends:
  2256. file: common/base.yml
  2257. service: app
  2258. env_file:
  2259. - 'envs'
  2260. environment:
  2261. - THING
  2262. - TEST_ONE=top
  2263. """)
  2264. commondir.join('envs').write("""
  2265. COMMON_ENV_FILE
  2266. TEST_ONE=common-env-file
  2267. TEST_TWO=common-env-file
  2268. TEST_THREE=common-env-file
  2269. TEST_FOUR=common-env-file
  2270. """)
  2271. tmpdir.join('envs').write("""
  2272. TOP_ENV_FILE
  2273. TEST_ONE=top-env-file
  2274. TEST_TWO=top-env-file
  2275. TEST_THREE=top-env-file
  2276. """)
  2277. expected = [
  2278. {
  2279. 'name': 'ext',
  2280. 'image': 'example/app',
  2281. 'environment': {
  2282. 'SECRET': 'secret',
  2283. 'TOP_ENV_FILE': 'secret',
  2284. 'COMMON_ENV_FILE': 'secret',
  2285. 'THING': 'thing',
  2286. 'TEST_ONE': 'top',
  2287. 'TEST_TWO': 'common',
  2288. 'TEST_THREE': 'top-env-file',
  2289. 'TEST_FOUR': 'common-env-file',
  2290. },
  2291. },
  2292. ]
  2293. os.environ['SECRET'] = 'secret'
  2294. os.environ['THING'] = 'thing'
  2295. os.environ['COMMON_ENV_FILE'] = 'secret'
  2296. os.environ['TOP_ENV_FILE'] = 'secret'
  2297. config = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2298. assert config == expected
  2299. def test_extends_with_mixed_versions_is_error(self):
  2300. tmpdir = py.test.ensuretemp('test_extends_with_mixed_version')
  2301. self.addCleanup(tmpdir.remove)
  2302. tmpdir.join('docker-compose.yml').write("""
  2303. version: "2"
  2304. services:
  2305. web:
  2306. extends:
  2307. file: base.yml
  2308. service: base
  2309. image: busybox
  2310. """)
  2311. tmpdir.join('base.yml').write("""
  2312. base:
  2313. volumes: ['/foo']
  2314. ports: ['3000:3000']
  2315. """)
  2316. with pytest.raises(ConfigurationError) as exc:
  2317. load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2318. assert 'Version mismatch' in exc.exconly()
  2319. def test_extends_with_defined_version_passes(self):
  2320. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2321. self.addCleanup(tmpdir.remove)
  2322. tmpdir.join('docker-compose.yml').write("""
  2323. version: "2"
  2324. services:
  2325. web:
  2326. extends:
  2327. file: base.yml
  2328. service: base
  2329. image: busybox
  2330. """)
  2331. tmpdir.join('base.yml').write("""
  2332. version: "2"
  2333. services:
  2334. base:
  2335. volumes: ['/foo']
  2336. ports: ['3000:3000']
  2337. command: top
  2338. """)
  2339. service = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2340. self.assertEquals(service[0]['command'], "top")
  2341. def test_extends_with_depends_on(self):
  2342. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2343. self.addCleanup(tmpdir.remove)
  2344. tmpdir.join('docker-compose.yml').write("""
  2345. version: "2"
  2346. services:
  2347. base:
  2348. image: example
  2349. web:
  2350. extends: base
  2351. image: busybox
  2352. depends_on: ['other']
  2353. other:
  2354. image: example
  2355. """)
  2356. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2357. assert service_sort(services)[2]['depends_on'] == ['other']
  2358. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2359. class ExpandPathTest(unittest.TestCase):
  2360. working_dir = '/home/user/somedir'
  2361. def test_expand_path_normal(self):
  2362. result = config.expand_path(self.working_dir, 'myfile')
  2363. self.assertEqual(result, self.working_dir + '/' + 'myfile')
  2364. def test_expand_path_absolute(self):
  2365. abs_path = '/home/user/otherdir/somefile'
  2366. result = config.expand_path(self.working_dir, abs_path)
  2367. self.assertEqual(result, abs_path)
  2368. def test_expand_path_with_tilde(self):
  2369. test_path = '~/otherdir/somefile'
  2370. with mock.patch.dict(os.environ):
  2371. os.environ['HOME'] = user_path = '/home/user/'
  2372. result = config.expand_path(self.working_dir, test_path)
  2373. self.assertEqual(result, user_path + 'otherdir/somefile')
  2374. class VolumePathTest(unittest.TestCase):
  2375. def test_split_path_mapping_with_windows_path(self):
  2376. host_path = "c:\\Users\\msamblanet\\Documents\\anvil\\connect\\config"
  2377. windows_volume_path = host_path + ":/opt/connect/config:ro"
  2378. expected_mapping = ("/opt/connect/config:ro", host_path)
  2379. mapping = config.split_path_mapping(windows_volume_path)
  2380. assert mapping == expected_mapping
  2381. def test_split_path_mapping_with_windows_path_in_container(self):
  2382. host_path = 'c:\\Users\\remilia\\data'
  2383. container_path = 'c:\\scarletdevil\\data'
  2384. expected_mapping = (container_path, host_path)
  2385. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  2386. assert mapping == expected_mapping
  2387. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2388. class BuildPathTest(unittest.TestCase):
  2389. def setUp(self):
  2390. self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
  2391. def test_nonexistent_path(self):
  2392. with self.assertRaises(ConfigurationError):
  2393. config.load(
  2394. build_config_details(
  2395. {
  2396. 'foo': {'build': 'nonexistent.path'},
  2397. },
  2398. 'working_dir',
  2399. 'filename.yml'
  2400. )
  2401. )
  2402. def test_relative_path(self):
  2403. relative_build_path = '../build-ctx/'
  2404. service_dict = make_service_dict(
  2405. 'relpath',
  2406. {'build': relative_build_path},
  2407. working_dir='tests/fixtures/build-path'
  2408. )
  2409. self.assertEquals(service_dict['build'], self.abs_context_path)
  2410. def test_absolute_path(self):
  2411. service_dict = make_service_dict(
  2412. 'abspath',
  2413. {'build': self.abs_context_path},
  2414. working_dir='tests/fixtures/build-path'
  2415. )
  2416. self.assertEquals(service_dict['build'], self.abs_context_path)
  2417. def test_from_file(self):
  2418. service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
  2419. self.assertEquals(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  2420. def test_valid_url_in_build_path(self):
  2421. valid_urls = [
  2422. 'git://github.com/docker/docker',
  2423. '[email protected]:docker/docker.git',
  2424. '[email protected]:atlassianlabs/atlassian-docker.git',
  2425. 'https://github.com/docker/docker.git',
  2426. 'http://github.com/docker/docker.git',
  2427. 'github.com/docker/docker.git',
  2428. ]
  2429. for valid_url in valid_urls:
  2430. service_dict = config.load(build_config_details({
  2431. 'validurl': {'build': valid_url},
  2432. }, '.', None)).services
  2433. assert service_dict[0]['build'] == {'context': valid_url}
  2434. def test_invalid_url_in_build_path(self):
  2435. invalid_urls = [
  2436. 'example.com/bogus',
  2437. 'ftp://example.com/',
  2438. '/path/does/not/exist',
  2439. ]
  2440. for invalid_url in invalid_urls:
  2441. with pytest.raises(ConfigurationError) as exc:
  2442. config.load(build_config_details({
  2443. 'invalidurl': {'build': invalid_url},
  2444. }, '.', None))
  2445. assert 'build path' in exc.exconly()
  2446. class GetDefaultConfigFilesTestCase(unittest.TestCase):
  2447. files = [
  2448. 'docker-compose.yml',
  2449. 'docker-compose.yaml',
  2450. ]
  2451. def test_get_config_path_default_file_in_basedir(self):
  2452. for index, filename in enumerate(self.files):
  2453. self.assertEqual(
  2454. filename,
  2455. get_config_filename_for_files(self.files[index:]))
  2456. with self.assertRaises(config.ComposeFileNotFound):
  2457. get_config_filename_for_files([])
  2458. def test_get_config_path_default_file_in_parent_dir(self):
  2459. """Test with files placed in the subdir"""
  2460. def get_config_in_subdir(files):
  2461. return get_config_filename_for_files(files, subdir=True)
  2462. for index, filename in enumerate(self.files):
  2463. self.assertEqual(filename, get_config_in_subdir(self.files[index:]))
  2464. with self.assertRaises(config.ComposeFileNotFound):
  2465. get_config_in_subdir([])
  2466. def get_config_filename_for_files(filenames, subdir=None):
  2467. def make_files(dirname, filenames):
  2468. for fname in filenames:
  2469. with open(os.path.join(dirname, fname), 'w') as f:
  2470. f.write('')
  2471. project_dir = tempfile.mkdtemp()
  2472. try:
  2473. make_files(project_dir, filenames)
  2474. if subdir:
  2475. base_dir = tempfile.mkdtemp(dir=project_dir)
  2476. else:
  2477. base_dir = project_dir
  2478. filename, = config.get_default_config_files(base_dir)
  2479. return os.path.basename(filename)
  2480. finally:
  2481. shutil.rmtree(project_dir)