config_test.py 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782
  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'] == 'None'
  651. def test_load_with_multiple_files_mismatched_networks_format(self):
  652. base_file = config.ConfigFile(
  653. 'base.yaml',
  654. {
  655. 'version': '2',
  656. 'services': {
  657. 'web': {
  658. 'image': 'example/web',
  659. 'networks': {
  660. 'foobar': {'aliases': ['foo', 'bar']}
  661. }
  662. }
  663. },
  664. 'networks': {'foobar': {}, 'baz': {}}
  665. }
  666. )
  667. override_file = config.ConfigFile(
  668. 'override.yaml',
  669. {
  670. 'version': '2',
  671. 'services': {
  672. 'web': {
  673. 'networks': ['baz']
  674. }
  675. }
  676. }
  677. )
  678. details = config.ConfigDetails('.', [base_file, override_file])
  679. web_service = config.load(details).services[0]
  680. assert web_service['networks'] == {
  681. 'foobar': {'aliases': ['foo', 'bar']},
  682. 'baz': None
  683. }
  684. def test_load_with_multiple_files_v2(self):
  685. base_file = config.ConfigFile(
  686. 'base.yaml',
  687. {
  688. 'version': '2',
  689. 'services': {
  690. 'web': {
  691. 'image': 'example/web',
  692. 'depends_on': ['db'],
  693. },
  694. 'db': {
  695. 'image': 'example/db',
  696. }
  697. },
  698. })
  699. override_file = config.ConfigFile(
  700. 'override.yaml',
  701. {
  702. 'version': '2',
  703. 'services': {
  704. 'web': {
  705. 'build': '/',
  706. 'volumes': ['/home/user/project:/code'],
  707. 'depends_on': ['other'],
  708. },
  709. 'other': {
  710. 'image': 'example/other',
  711. }
  712. }
  713. })
  714. details = config.ConfigDetails('.', [base_file, override_file])
  715. service_dicts = config.load(details).services
  716. expected = [
  717. {
  718. 'name': 'web',
  719. 'build': {'context': os.path.abspath('/')},
  720. 'image': 'example/web',
  721. 'volumes': [VolumeSpec.parse('/home/user/project:/code')],
  722. 'depends_on': ['db', 'other'],
  723. },
  724. {
  725. 'name': 'db',
  726. 'image': 'example/db',
  727. },
  728. {
  729. 'name': 'other',
  730. 'image': 'example/other',
  731. },
  732. ]
  733. assert service_sort(service_dicts) == service_sort(expected)
  734. def test_undeclared_volume_v2(self):
  735. base_file = config.ConfigFile(
  736. 'base.yaml',
  737. {
  738. 'version': '2',
  739. 'services': {
  740. 'web': {
  741. 'image': 'busybox:latest',
  742. 'volumes': ['data0028:/data:ro'],
  743. },
  744. },
  745. }
  746. )
  747. details = config.ConfigDetails('.', [base_file])
  748. with self.assertRaises(ConfigurationError):
  749. config.load(details)
  750. base_file = config.ConfigFile(
  751. 'base.yaml',
  752. {
  753. 'version': '2',
  754. 'services': {
  755. 'web': {
  756. 'image': 'busybox:latest',
  757. 'volumes': ['./data0028:/data:ro'],
  758. },
  759. },
  760. }
  761. )
  762. details = config.ConfigDetails('.', [base_file])
  763. config_data = config.load(details)
  764. volume = config_data.services[0].get('volumes')[0]
  765. assert not volume.is_named_volume
  766. def test_undeclared_volume_v1(self):
  767. base_file = config.ConfigFile(
  768. 'base.yaml',
  769. {
  770. 'web': {
  771. 'image': 'busybox:latest',
  772. 'volumes': ['data0028:/data:ro'],
  773. },
  774. }
  775. )
  776. details = config.ConfigDetails('.', [base_file])
  777. config_data = config.load(details)
  778. volume = config_data.services[0].get('volumes')[0]
  779. assert volume.external == 'data0028'
  780. assert volume.is_named_volume
  781. def test_config_valid_service_names(self):
  782. for valid_name in ['_', '-', '.__.', '_what-up.', 'what_.up----', 'whatup']:
  783. services = config.load(
  784. build_config_details(
  785. {valid_name: {'image': 'busybox'}},
  786. 'tests/fixtures/extends',
  787. 'common.yml')).services
  788. assert services[0]['name'] == valid_name
  789. def test_config_hint(self):
  790. with pytest.raises(ConfigurationError) as excinfo:
  791. config.load(
  792. build_config_details(
  793. {
  794. 'foo': {'image': 'busybox', 'privilige': 'something'},
  795. },
  796. 'tests/fixtures/extends',
  797. 'filename.yml'
  798. )
  799. )
  800. assert "(did you mean 'privileged'?)" in excinfo.exconly()
  801. def test_load_errors_on_uppercase_with_no_image(self):
  802. with pytest.raises(ConfigurationError) as exc:
  803. config.load(build_config_details({
  804. 'Foo': {'build': '.'},
  805. }, 'tests/fixtures/build-ctx'))
  806. assert "Service 'Foo' contains uppercase characters" in exc.exconly()
  807. def test_invalid_config_v1(self):
  808. with pytest.raises(ConfigurationError) as excinfo:
  809. config.load(
  810. build_config_details(
  811. {
  812. 'foo': {'image': 1},
  813. },
  814. 'tests/fixtures/extends',
  815. 'filename.yml'
  816. )
  817. )
  818. assert "foo.image contains an invalid type, it should be a string" \
  819. in excinfo.exconly()
  820. def test_invalid_config_v2(self):
  821. with pytest.raises(ConfigurationError) as excinfo:
  822. config.load(
  823. build_config_details(
  824. {
  825. 'version': '2',
  826. 'services': {
  827. 'foo': {'image': 1},
  828. },
  829. },
  830. 'tests/fixtures/extends',
  831. 'filename.yml'
  832. )
  833. )
  834. assert "services.foo.image contains an invalid type, it should be a string" \
  835. in excinfo.exconly()
  836. def test_invalid_config_build_and_image_specified_v1(self):
  837. with pytest.raises(ConfigurationError) as excinfo:
  838. config.load(
  839. build_config_details(
  840. {
  841. 'foo': {'image': 'busybox', 'build': '.'},
  842. },
  843. 'tests/fixtures/extends',
  844. 'filename.yml'
  845. )
  846. )
  847. assert "foo has both an image and build path specified." in excinfo.exconly()
  848. def test_invalid_config_type_should_be_an_array(self):
  849. with pytest.raises(ConfigurationError) as excinfo:
  850. config.load(
  851. build_config_details(
  852. {
  853. 'foo': {'image': 'busybox', 'links': 'an_link'},
  854. },
  855. 'tests/fixtures/extends',
  856. 'filename.yml'
  857. )
  858. )
  859. assert "foo.links contains an invalid type, it should be an array" \
  860. in excinfo.exconly()
  861. def test_invalid_config_not_a_dictionary(self):
  862. with pytest.raises(ConfigurationError) as excinfo:
  863. config.load(
  864. build_config_details(
  865. ['foo', 'lol'],
  866. 'tests/fixtures/extends',
  867. 'filename.yml'
  868. )
  869. )
  870. assert "Top level object in 'filename.yml' needs to be an object" \
  871. in excinfo.exconly()
  872. def test_invalid_config_not_unique_items(self):
  873. with pytest.raises(ConfigurationError) as excinfo:
  874. config.load(
  875. build_config_details(
  876. {
  877. 'web': {'build': '.', 'devices': ['/dev/foo:/dev/foo', '/dev/foo:/dev/foo']}
  878. },
  879. 'tests/fixtures/extends',
  880. 'filename.yml'
  881. )
  882. )
  883. assert "has non-unique elements" in excinfo.exconly()
  884. def test_invalid_list_of_strings_format(self):
  885. with pytest.raises(ConfigurationError) as excinfo:
  886. config.load(
  887. build_config_details(
  888. {
  889. 'web': {'build': '.', 'command': [1]}
  890. },
  891. 'tests/fixtures/extends',
  892. 'filename.yml'
  893. )
  894. )
  895. assert "web.command contains 1, which is an invalid type, it should be a string" \
  896. in excinfo.exconly()
  897. def test_load_config_dockerfile_without_build_raises_error_v1(self):
  898. with pytest.raises(ConfigurationError) as exc:
  899. config.load(build_config_details({
  900. 'web': {
  901. 'image': 'busybox',
  902. 'dockerfile': 'Dockerfile.alt'
  903. }
  904. }))
  905. assert "web has both an image and alternate Dockerfile." in exc.exconly()
  906. def test_config_extra_hosts_string_raises_validation_error(self):
  907. with pytest.raises(ConfigurationError) as excinfo:
  908. config.load(
  909. build_config_details(
  910. {'web': {
  911. 'image': 'busybox',
  912. 'extra_hosts': 'somehost:162.242.195.82'
  913. }},
  914. 'working_dir',
  915. 'filename.yml'
  916. )
  917. )
  918. assert "web.extra_hosts contains an invalid type" \
  919. in excinfo.exconly()
  920. def test_config_extra_hosts_list_of_dicts_validation_error(self):
  921. with pytest.raises(ConfigurationError) as excinfo:
  922. config.load(
  923. build_config_details(
  924. {'web': {
  925. 'image': 'busybox',
  926. 'extra_hosts': [
  927. {'somehost': '162.242.195.82'},
  928. {'otherhost': '50.31.209.229'}
  929. ]
  930. }},
  931. 'working_dir',
  932. 'filename.yml'
  933. )
  934. )
  935. assert "web.extra_hosts contains {\"somehost\": \"162.242.195.82\"}, " \
  936. "which is an invalid type, it should be a string" \
  937. in excinfo.exconly()
  938. def test_config_ulimits_invalid_keys_validation_error(self):
  939. with pytest.raises(ConfigurationError) as exc:
  940. config.load(build_config_details(
  941. {
  942. 'web': {
  943. 'image': 'busybox',
  944. 'ulimits': {
  945. 'nofile': {
  946. "not_soft_or_hard": 100,
  947. "soft": 10000,
  948. "hard": 20000,
  949. }
  950. }
  951. }
  952. },
  953. 'working_dir',
  954. 'filename.yml'))
  955. assert "web.ulimits.nofile contains unsupported option: 'not_soft_or_hard'" \
  956. in exc.exconly()
  957. def test_config_ulimits_required_keys_validation_error(self):
  958. with pytest.raises(ConfigurationError) as exc:
  959. config.load(build_config_details(
  960. {
  961. 'web': {
  962. 'image': 'busybox',
  963. 'ulimits': {'nofile': {"soft": 10000}}
  964. }
  965. },
  966. 'working_dir',
  967. 'filename.yml'))
  968. assert "web.ulimits.nofile" in exc.exconly()
  969. assert "'hard' is a required property" in exc.exconly()
  970. def test_config_ulimits_soft_greater_than_hard_error(self):
  971. expected = "'soft' value can not be greater than 'hard' value"
  972. with pytest.raises(ConfigurationError) as exc:
  973. config.load(build_config_details(
  974. {
  975. 'web': {
  976. 'image': 'busybox',
  977. 'ulimits': {
  978. 'nofile': {"soft": 10000, "hard": 1000}
  979. }
  980. }
  981. },
  982. 'working_dir',
  983. 'filename.yml'))
  984. assert expected in exc.exconly()
  985. def test_valid_config_which_allows_two_type_definitions(self):
  986. expose_values = [["8000"], [8000]]
  987. for expose in expose_values:
  988. service = config.load(
  989. build_config_details(
  990. {'web': {
  991. 'image': 'busybox',
  992. 'expose': expose
  993. }},
  994. 'working_dir',
  995. 'filename.yml'
  996. )
  997. ).services
  998. self.assertEqual(service[0]['expose'], expose)
  999. def test_valid_config_oneof_string_or_list(self):
  1000. entrypoint_values = [["sh"], "sh"]
  1001. for entrypoint in entrypoint_values:
  1002. service = config.load(
  1003. build_config_details(
  1004. {'web': {
  1005. 'image': 'busybox',
  1006. 'entrypoint': entrypoint
  1007. }},
  1008. 'working_dir',
  1009. 'filename.yml'
  1010. )
  1011. ).services
  1012. self.assertEqual(service[0]['entrypoint'], entrypoint)
  1013. def test_logs_warning_for_boolean_in_environment(self):
  1014. config_details = build_config_details({
  1015. 'web': {
  1016. 'image': 'busybox',
  1017. 'environment': {'SHOW_STUFF': True}
  1018. }
  1019. })
  1020. with pytest.raises(ConfigurationError) as exc:
  1021. config.load(config_details)
  1022. assert "contains true, which is an invalid type" in exc.exconly()
  1023. def test_config_valid_environment_dict_key_contains_dashes(self):
  1024. services = config.load(
  1025. build_config_details(
  1026. {'web': {
  1027. 'image': 'busybox',
  1028. 'environment': {'SPRING_JPA_HIBERNATE_DDL-AUTO': 'none'}
  1029. }},
  1030. 'working_dir',
  1031. 'filename.yml'
  1032. )
  1033. ).services
  1034. self.assertEqual(services[0]['environment']['SPRING_JPA_HIBERNATE_DDL-AUTO'], 'none')
  1035. def test_load_yaml_with_yaml_error(self):
  1036. tmpdir = py.test.ensuretemp('invalid_yaml_test')
  1037. self.addCleanup(tmpdir.remove)
  1038. invalid_yaml_file = tmpdir.join('docker-compose.yml')
  1039. invalid_yaml_file.write("""
  1040. web:
  1041. this is bogus: ok: what
  1042. """)
  1043. with pytest.raises(ConfigurationError) as exc:
  1044. config.load_yaml(str(invalid_yaml_file))
  1045. assert 'line 3, column 32' in exc.exconly()
  1046. def test_validate_extra_hosts_invalid(self):
  1047. with pytest.raises(ConfigurationError) as exc:
  1048. config.load(build_config_details({
  1049. 'web': {
  1050. 'image': 'alpine',
  1051. 'extra_hosts': "www.example.com: 192.168.0.17",
  1052. }
  1053. }))
  1054. assert "web.extra_hosts contains an invalid type" in exc.exconly()
  1055. def test_validate_extra_hosts_invalid_list(self):
  1056. with pytest.raises(ConfigurationError) as exc:
  1057. config.load(build_config_details({
  1058. 'web': {
  1059. 'image': 'alpine',
  1060. 'extra_hosts': [
  1061. {'www.example.com': '192.168.0.17'},
  1062. {'api.example.com': '192.168.0.18'}
  1063. ],
  1064. }
  1065. }))
  1066. assert "which is an invalid type" in exc.exconly()
  1067. def test_normalize_dns_options(self):
  1068. actual = config.load(build_config_details({
  1069. 'web': {
  1070. 'image': 'alpine',
  1071. 'dns': '8.8.8.8',
  1072. 'dns_search': 'domain.local',
  1073. }
  1074. }))
  1075. assert actual.services == [
  1076. {
  1077. 'name': 'web',
  1078. 'image': 'alpine',
  1079. 'dns': ['8.8.8.8'],
  1080. 'dns_search': ['domain.local'],
  1081. }
  1082. ]
  1083. def test_tmpfs_option(self):
  1084. actual = config.load(build_config_details({
  1085. 'version': '2',
  1086. 'services': {
  1087. 'web': {
  1088. 'image': 'alpine',
  1089. 'tmpfs': '/run',
  1090. }
  1091. }
  1092. }))
  1093. assert actual.services == [
  1094. {
  1095. 'name': 'web',
  1096. 'image': 'alpine',
  1097. 'tmpfs': ['/run'],
  1098. }
  1099. ]
  1100. def test_merge_service_dicts_from_files_with_extends_in_base(self):
  1101. base = {
  1102. 'volumes': ['.:/app'],
  1103. 'extends': {'service': 'app'}
  1104. }
  1105. override = {
  1106. 'image': 'alpine:edge',
  1107. }
  1108. actual = config.merge_service_dicts_from_files(
  1109. base,
  1110. override,
  1111. DEFAULT_VERSION)
  1112. assert actual == {
  1113. 'image': 'alpine:edge',
  1114. 'volumes': ['.:/app'],
  1115. 'extends': {'service': 'app'}
  1116. }
  1117. def test_merge_service_dicts_from_files_with_extends_in_override(self):
  1118. base = {
  1119. 'volumes': ['.:/app'],
  1120. 'extends': {'service': 'app'}
  1121. }
  1122. override = {
  1123. 'image': 'alpine:edge',
  1124. 'extends': {'service': 'foo'}
  1125. }
  1126. actual = config.merge_service_dicts_from_files(
  1127. base,
  1128. override,
  1129. DEFAULT_VERSION)
  1130. assert actual == {
  1131. 'image': 'alpine:edge',
  1132. 'volumes': ['.:/app'],
  1133. 'extends': {'service': 'foo'}
  1134. }
  1135. def test_merge_build_args(self):
  1136. base = {
  1137. 'build': {
  1138. 'context': '.',
  1139. 'args': {
  1140. 'ONE': '1',
  1141. 'TWO': '2',
  1142. },
  1143. }
  1144. }
  1145. override = {
  1146. 'build': {
  1147. 'args': {
  1148. 'TWO': 'dos',
  1149. 'THREE': '3',
  1150. },
  1151. }
  1152. }
  1153. actual = config.merge_service_dicts(
  1154. base,
  1155. override,
  1156. DEFAULT_VERSION)
  1157. assert actual == {
  1158. 'build': {
  1159. 'context': '.',
  1160. 'args': {
  1161. 'ONE': '1',
  1162. 'TWO': 'dos',
  1163. 'THREE': '3',
  1164. },
  1165. }
  1166. }
  1167. def test_merge_logging_v1(self):
  1168. base = {
  1169. 'image': 'alpine:edge',
  1170. 'log_driver': 'something',
  1171. 'log_opt': {'foo': 'three'},
  1172. }
  1173. override = {
  1174. 'image': 'alpine:edge',
  1175. 'command': 'true',
  1176. }
  1177. actual = config.merge_service_dicts(base, override, V1)
  1178. assert actual == {
  1179. 'image': 'alpine:edge',
  1180. 'log_driver': 'something',
  1181. 'log_opt': {'foo': 'three'},
  1182. 'command': 'true',
  1183. }
  1184. def test_external_volume_config(self):
  1185. config_details = build_config_details({
  1186. 'version': '2',
  1187. 'services': {
  1188. 'bogus': {'image': 'busybox'}
  1189. },
  1190. 'volumes': {
  1191. 'ext': {'external': True},
  1192. 'ext2': {'external': {'name': 'aliased'}}
  1193. }
  1194. })
  1195. config_result = config.load(config_details)
  1196. volumes = config_result.volumes
  1197. assert 'ext' in volumes
  1198. assert volumes['ext']['external'] is True
  1199. assert 'ext2' in volumes
  1200. assert volumes['ext2']['external']['name'] == 'aliased'
  1201. def test_external_volume_invalid_config(self):
  1202. config_details = build_config_details({
  1203. 'version': '2',
  1204. 'services': {
  1205. 'bogus': {'image': 'busybox'}
  1206. },
  1207. 'volumes': {
  1208. 'ext': {'external': True, 'driver': 'foo'}
  1209. }
  1210. })
  1211. with pytest.raises(ConfigurationError):
  1212. config.load(config_details)
  1213. def test_depends_on_orders_services(self):
  1214. config_details = build_config_details({
  1215. 'version': '2',
  1216. 'services': {
  1217. 'one': {'image': 'busybox', 'depends_on': ['three', 'two']},
  1218. 'two': {'image': 'busybox', 'depends_on': ['three']},
  1219. 'three': {'image': 'busybox'},
  1220. },
  1221. })
  1222. actual = config.load(config_details)
  1223. assert (
  1224. [service['name'] for service in actual.services] ==
  1225. ['three', 'two', 'one']
  1226. )
  1227. def test_depends_on_unknown_service_errors(self):
  1228. config_details = build_config_details({
  1229. 'version': '2',
  1230. 'services': {
  1231. 'one': {'image': 'busybox', 'depends_on': ['three']},
  1232. },
  1233. })
  1234. with pytest.raises(ConfigurationError) as exc:
  1235. config.load(config_details)
  1236. assert "Service 'one' depends on service 'three'" in exc.exconly()
  1237. def test_linked_service_is_undefined(self):
  1238. with self.assertRaises(ConfigurationError):
  1239. config.load(
  1240. build_config_details({
  1241. 'version': '2',
  1242. 'services': {
  1243. 'web': {'image': 'busybox', 'links': ['db']},
  1244. },
  1245. })
  1246. )
  1247. def test_load_dockerfile_without_context(self):
  1248. config_details = build_config_details({
  1249. 'version': '2',
  1250. 'services': {
  1251. 'one': {'build': {'dockerfile': 'Dockerfile.foo'}},
  1252. },
  1253. })
  1254. with pytest.raises(ConfigurationError) as exc:
  1255. config.load(config_details)
  1256. assert 'has neither an image nor a build context' in exc.exconly()
  1257. class NetworkModeTest(unittest.TestCase):
  1258. def test_network_mode_standard(self):
  1259. config_data = config.load(build_config_details({
  1260. 'version': '2',
  1261. 'services': {
  1262. 'web': {
  1263. 'image': 'busybox',
  1264. 'command': "top",
  1265. 'network_mode': 'bridge',
  1266. },
  1267. },
  1268. }))
  1269. assert config_data.services[0]['network_mode'] == 'bridge'
  1270. def test_network_mode_standard_v1(self):
  1271. config_data = config.load(build_config_details({
  1272. 'web': {
  1273. 'image': 'busybox',
  1274. 'command': "top",
  1275. 'net': 'bridge',
  1276. },
  1277. }))
  1278. assert config_data.services[0]['network_mode'] == 'bridge'
  1279. assert 'net' not in config_data.services[0]
  1280. def test_network_mode_container(self):
  1281. config_data = config.load(build_config_details({
  1282. 'version': '2',
  1283. 'services': {
  1284. 'web': {
  1285. 'image': 'busybox',
  1286. 'command': "top",
  1287. 'network_mode': 'container:foo',
  1288. },
  1289. },
  1290. }))
  1291. assert config_data.services[0]['network_mode'] == 'container:foo'
  1292. def test_network_mode_container_v1(self):
  1293. config_data = config.load(build_config_details({
  1294. 'web': {
  1295. 'image': 'busybox',
  1296. 'command': "top",
  1297. 'net': 'container:foo',
  1298. },
  1299. }))
  1300. assert config_data.services[0]['network_mode'] == 'container:foo'
  1301. def test_network_mode_service(self):
  1302. config_data = config.load(build_config_details({
  1303. 'version': '2',
  1304. 'services': {
  1305. 'web': {
  1306. 'image': 'busybox',
  1307. 'command': "top",
  1308. 'network_mode': 'service:foo',
  1309. },
  1310. 'foo': {
  1311. 'image': 'busybox',
  1312. 'command': "top",
  1313. },
  1314. },
  1315. }))
  1316. assert config_data.services[1]['network_mode'] == 'service:foo'
  1317. def test_network_mode_service_v1(self):
  1318. config_data = config.load(build_config_details({
  1319. 'web': {
  1320. 'image': 'busybox',
  1321. 'command': "top",
  1322. 'net': 'container:foo',
  1323. },
  1324. 'foo': {
  1325. 'image': 'busybox',
  1326. 'command': "top",
  1327. },
  1328. }))
  1329. assert config_data.services[1]['network_mode'] == 'service:foo'
  1330. def test_network_mode_service_nonexistent(self):
  1331. with pytest.raises(ConfigurationError) as excinfo:
  1332. config.load(build_config_details({
  1333. 'version': '2',
  1334. 'services': {
  1335. 'web': {
  1336. 'image': 'busybox',
  1337. 'command': "top",
  1338. 'network_mode': 'service:foo',
  1339. },
  1340. },
  1341. }))
  1342. assert "service 'foo' which is undefined" in excinfo.exconly()
  1343. def test_network_mode_plus_networks_is_invalid(self):
  1344. with pytest.raises(ConfigurationError) as excinfo:
  1345. config.load(build_config_details({
  1346. 'version': '2',
  1347. 'services': {
  1348. 'web': {
  1349. 'image': 'busybox',
  1350. 'command': "top",
  1351. 'network_mode': 'bridge',
  1352. 'networks': ['front'],
  1353. },
  1354. },
  1355. 'networks': {
  1356. 'front': None,
  1357. }
  1358. }))
  1359. assert "'network_mode' and 'networks' cannot be combined" in excinfo.exconly()
  1360. class PortsTest(unittest.TestCase):
  1361. INVALID_PORTS_TYPES = [
  1362. {"1": "8000"},
  1363. False,
  1364. "8000",
  1365. 8000,
  1366. ]
  1367. NON_UNIQUE_SINGLE_PORTS = [
  1368. ["8000", "8000"],
  1369. ]
  1370. INVALID_PORT_MAPPINGS = [
  1371. ["8000-8001:8000"],
  1372. ]
  1373. VALID_SINGLE_PORTS = [
  1374. ["8000"],
  1375. ["8000/tcp"],
  1376. ["8000", "9000"],
  1377. [8000],
  1378. [8000, 9000],
  1379. ]
  1380. VALID_PORT_MAPPINGS = [
  1381. ["8000:8050"],
  1382. ["49153-49154:3002-3003"],
  1383. ]
  1384. def test_config_invalid_ports_type_validation(self):
  1385. for invalid_ports in self.INVALID_PORTS_TYPES:
  1386. with pytest.raises(ConfigurationError) as exc:
  1387. self.check_config({'ports': invalid_ports})
  1388. assert "contains an invalid type" in exc.value.msg
  1389. def test_config_non_unique_ports_validation(self):
  1390. for invalid_ports in self.NON_UNIQUE_SINGLE_PORTS:
  1391. with pytest.raises(ConfigurationError) as exc:
  1392. self.check_config({'ports': invalid_ports})
  1393. assert "non-unique" in exc.value.msg
  1394. def test_config_invalid_ports_format_validation(self):
  1395. for invalid_ports in self.INVALID_PORT_MAPPINGS:
  1396. with pytest.raises(ConfigurationError) as exc:
  1397. self.check_config({'ports': invalid_ports})
  1398. assert "Port ranges don't match in length" in exc.value.msg
  1399. def test_config_valid_ports_format_validation(self):
  1400. for valid_ports in self.VALID_SINGLE_PORTS + self.VALID_PORT_MAPPINGS:
  1401. self.check_config({'ports': valid_ports})
  1402. def test_config_invalid_expose_type_validation(self):
  1403. for invalid_expose in self.INVALID_PORTS_TYPES:
  1404. with pytest.raises(ConfigurationError) as exc:
  1405. self.check_config({'expose': invalid_expose})
  1406. assert "contains an invalid type" in exc.value.msg
  1407. def test_config_non_unique_expose_validation(self):
  1408. for invalid_expose in self.NON_UNIQUE_SINGLE_PORTS:
  1409. with pytest.raises(ConfigurationError) as exc:
  1410. self.check_config({'expose': invalid_expose})
  1411. assert "non-unique" in exc.value.msg
  1412. def test_config_invalid_expose_format_validation(self):
  1413. # Valid port mappings ARE NOT valid 'expose' entries
  1414. for invalid_expose in self.INVALID_PORT_MAPPINGS + self.VALID_PORT_MAPPINGS:
  1415. with pytest.raises(ConfigurationError) as exc:
  1416. self.check_config({'expose': invalid_expose})
  1417. assert "should be of the format" in exc.value.msg
  1418. def test_config_valid_expose_format_validation(self):
  1419. # Valid single ports ARE valid 'expose' entries
  1420. for valid_expose in self.VALID_SINGLE_PORTS:
  1421. self.check_config({'expose': valid_expose})
  1422. def check_config(self, cfg):
  1423. config.load(
  1424. build_config_details(
  1425. {'web': dict(image='busybox', **cfg)},
  1426. 'working_dir',
  1427. 'filename.yml'
  1428. )
  1429. )
  1430. class InterpolationTest(unittest.TestCase):
  1431. @mock.patch.dict(os.environ)
  1432. def test_config_file_with_environment_file(self):
  1433. project_dir = 'tests/fixtures/default-env-file'
  1434. service_dicts = config.load(
  1435. config.find(
  1436. project_dir, None, Environment.from_env_file(project_dir)
  1437. )
  1438. ).services
  1439. self.assertEqual(service_dicts[0], {
  1440. 'name': 'web',
  1441. 'image': 'alpine:latest',
  1442. 'ports': ['5643', '9999'],
  1443. 'command': 'true'
  1444. })
  1445. @mock.patch.dict(os.environ)
  1446. def test_config_file_with_environment_variable(self):
  1447. project_dir = 'tests/fixtures/environment-interpolation'
  1448. os.environ.update(
  1449. IMAGE="busybox",
  1450. HOST_PORT="80",
  1451. LABEL_VALUE="myvalue",
  1452. )
  1453. service_dicts = config.load(
  1454. config.find(
  1455. project_dir, None, Environment.from_env_file(project_dir)
  1456. )
  1457. ).services
  1458. self.assertEqual(service_dicts, [
  1459. {
  1460. 'name': 'web',
  1461. 'image': 'busybox',
  1462. 'ports': ['80:8000'],
  1463. 'labels': {'mylabel': 'myvalue'},
  1464. 'hostname': 'host-',
  1465. 'command': '${ESCAPED}',
  1466. }
  1467. ])
  1468. @mock.patch.dict(os.environ)
  1469. def test_unset_variable_produces_warning(self):
  1470. os.environ.pop('FOO', None)
  1471. os.environ.pop('BAR', None)
  1472. config_details = build_config_details(
  1473. {
  1474. 'web': {
  1475. 'image': '${FOO}',
  1476. 'command': '${BAR}',
  1477. 'container_name': '${BAR}',
  1478. },
  1479. },
  1480. '.',
  1481. None,
  1482. )
  1483. with mock.patch('compose.config.environment.log') as log:
  1484. config.load(config_details)
  1485. self.assertEqual(2, log.warn.call_count)
  1486. warnings = sorted(args[0][0] for args in log.warn.call_args_list)
  1487. self.assertIn('BAR', warnings[0])
  1488. self.assertIn('FOO', warnings[1])
  1489. @mock.patch.dict(os.environ)
  1490. def test_invalid_interpolation(self):
  1491. with self.assertRaises(config.ConfigurationError) as cm:
  1492. config.load(
  1493. build_config_details(
  1494. {'web': {'image': '${'}},
  1495. 'working_dir',
  1496. 'filename.yml'
  1497. )
  1498. )
  1499. self.assertIn('Invalid', cm.exception.msg)
  1500. self.assertIn('for "image" option', cm.exception.msg)
  1501. self.assertIn('in service "web"', cm.exception.msg)
  1502. self.assertIn('"${"', cm.exception.msg)
  1503. def test_empty_environment_key_allowed(self):
  1504. service_dict = config.load(
  1505. build_config_details(
  1506. {
  1507. 'web': {
  1508. 'build': '.',
  1509. 'environment': {
  1510. 'POSTGRES_PASSWORD': ''
  1511. },
  1512. },
  1513. },
  1514. '.',
  1515. None,
  1516. )
  1517. ).services[0]
  1518. self.assertEquals(service_dict['environment']['POSTGRES_PASSWORD'], '')
  1519. class VolumeConfigTest(unittest.TestCase):
  1520. def test_no_binding(self):
  1521. d = make_service_dict('foo', {'build': '.', 'volumes': ['/data']}, working_dir='.')
  1522. self.assertEqual(d['volumes'], ['/data'])
  1523. @mock.patch.dict(os.environ)
  1524. def test_volume_binding_with_environment_variable(self):
  1525. os.environ['VOLUME_PATH'] = '/host/path'
  1526. d = config.load(
  1527. build_config_details(
  1528. {'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
  1529. '.',
  1530. None,
  1531. )
  1532. ).services[0]
  1533. self.assertEqual(d['volumes'], [VolumeSpec.parse('/host/path:/container/path')])
  1534. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1535. @mock.patch.dict(os.environ)
  1536. def test_volume_binding_with_home(self):
  1537. os.environ['HOME'] = '/home/user'
  1538. d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
  1539. self.assertEqual(d['volumes'], ['/home/user:/container/path'])
  1540. def test_name_does_not_expand(self):
  1541. d = make_service_dict('foo', {'build': '.', 'volumes': ['mydatavolume:/data']}, working_dir='.')
  1542. self.assertEqual(d['volumes'], ['mydatavolume:/data'])
  1543. def test_absolute_posix_path_does_not_expand(self):
  1544. d = make_service_dict('foo', {'build': '.', 'volumes': ['/var/lib/data:/data']}, working_dir='.')
  1545. self.assertEqual(d['volumes'], ['/var/lib/data:/data'])
  1546. def test_absolute_windows_path_does_not_expand(self):
  1547. d = make_service_dict('foo', {'build': '.', 'volumes': ['c:\\data:/data']}, working_dir='.')
  1548. self.assertEqual(d['volumes'], ['c:\\data:/data'])
  1549. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1550. def test_relative_path_does_expand_posix(self):
  1551. d = make_service_dict(
  1552. 'foo',
  1553. {'build': '.', 'volumes': ['./data:/data']},
  1554. working_dir='/home/me/myproject')
  1555. self.assertEqual(d['volumes'], ['/home/me/myproject/data:/data'])
  1556. d = make_service_dict(
  1557. 'foo',
  1558. {'build': '.', 'volumes': ['.:/data']},
  1559. working_dir='/home/me/myproject')
  1560. self.assertEqual(d['volumes'], ['/home/me/myproject:/data'])
  1561. d = make_service_dict(
  1562. 'foo',
  1563. {'build': '.', 'volumes': ['../otherproject:/data']},
  1564. working_dir='/home/me/myproject')
  1565. self.assertEqual(d['volumes'], ['/home/me/otherproject:/data'])
  1566. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='windows paths')
  1567. def test_relative_path_does_expand_windows(self):
  1568. d = make_service_dict(
  1569. 'foo',
  1570. {'build': '.', 'volumes': ['./data:/data']},
  1571. working_dir='c:\\Users\\me\\myproject')
  1572. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject\\data:/data'])
  1573. d = make_service_dict(
  1574. 'foo',
  1575. {'build': '.', 'volumes': ['.:/data']},
  1576. working_dir='c:\\Users\\me\\myproject')
  1577. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject:/data'])
  1578. d = make_service_dict(
  1579. 'foo',
  1580. {'build': '.', 'volumes': ['../otherproject:/data']},
  1581. working_dir='c:\\Users\\me\\myproject')
  1582. self.assertEqual(d['volumes'], ['c:\\Users\\me\\otherproject:/data'])
  1583. @mock.patch.dict(os.environ)
  1584. def test_home_directory_with_driver_does_not_expand(self):
  1585. os.environ['NAME'] = 'surprise!'
  1586. d = make_service_dict('foo', {
  1587. 'build': '.',
  1588. 'volumes': ['~:/data'],
  1589. 'volume_driver': 'foodriver',
  1590. }, working_dir='.')
  1591. self.assertEqual(d['volumes'], ['~:/data'])
  1592. def test_volume_path_with_non_ascii_directory(self):
  1593. volume = u'/Füü/data:/data'
  1594. container_path = config.resolve_volume_path(".", volume)
  1595. self.assertEqual(container_path, volume)
  1596. class MergePathMappingTest(object):
  1597. config_name = ""
  1598. def test_empty(self):
  1599. service_dict = config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1600. assert self.config_name not in service_dict
  1601. def test_no_override(self):
  1602. service_dict = config.merge_service_dicts(
  1603. {self.config_name: ['/foo:/code', '/data']},
  1604. {},
  1605. DEFAULT_VERSION)
  1606. assert set(service_dict[self.config_name]) == set(['/foo:/code', '/data'])
  1607. def test_no_base(self):
  1608. service_dict = config.merge_service_dicts(
  1609. {},
  1610. {self.config_name: ['/bar:/code']},
  1611. DEFAULT_VERSION)
  1612. assert set(service_dict[self.config_name]) == set(['/bar:/code'])
  1613. def test_override_explicit_path(self):
  1614. service_dict = config.merge_service_dicts(
  1615. {self.config_name: ['/foo:/code', '/data']},
  1616. {self.config_name: ['/bar:/code']},
  1617. DEFAULT_VERSION)
  1618. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1619. def test_add_explicit_path(self):
  1620. service_dict = config.merge_service_dicts(
  1621. {self.config_name: ['/foo:/code', '/data']},
  1622. {self.config_name: ['/bar:/code', '/quux:/data']},
  1623. DEFAULT_VERSION)
  1624. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/quux:/data'])
  1625. def test_remove_explicit_path(self):
  1626. service_dict = config.merge_service_dicts(
  1627. {self.config_name: ['/foo:/code', '/quux:/data']},
  1628. {self.config_name: ['/bar:/code', '/data']},
  1629. DEFAULT_VERSION)
  1630. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1631. class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
  1632. config_name = 'volumes'
  1633. class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
  1634. config_name = 'devices'
  1635. class BuildOrImageMergeTest(unittest.TestCase):
  1636. def test_merge_build_or_image_no_override(self):
  1637. self.assertEqual(
  1638. config.merge_service_dicts({'build': '.'}, {}, V1),
  1639. {'build': '.'},
  1640. )
  1641. self.assertEqual(
  1642. config.merge_service_dicts({'image': 'redis'}, {}, V1),
  1643. {'image': 'redis'},
  1644. )
  1645. def test_merge_build_or_image_override_with_same(self):
  1646. self.assertEqual(
  1647. config.merge_service_dicts({'build': '.'}, {'build': './web'}, V1),
  1648. {'build': './web'},
  1649. )
  1650. self.assertEqual(
  1651. config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}, V1),
  1652. {'image': 'postgres'},
  1653. )
  1654. def test_merge_build_or_image_override_with_other(self):
  1655. self.assertEqual(
  1656. config.merge_service_dicts({'build': '.'}, {'image': 'redis'}, V1),
  1657. {'image': 'redis'},
  1658. )
  1659. self.assertEqual(
  1660. config.merge_service_dicts({'image': 'redis'}, {'build': '.'}, V1),
  1661. {'build': '.'}
  1662. )
  1663. class MergeListsTest(object):
  1664. config_name = ""
  1665. base_config = []
  1666. override_config = []
  1667. def merged_config(self):
  1668. return set(self.base_config) | set(self.override_config)
  1669. def test_empty(self):
  1670. assert self.config_name not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1671. def test_no_override(self):
  1672. service_dict = config.merge_service_dicts(
  1673. {self.config_name: self.base_config},
  1674. {},
  1675. DEFAULT_VERSION)
  1676. assert set(service_dict[self.config_name]) == set(self.base_config)
  1677. def test_no_base(self):
  1678. service_dict = config.merge_service_dicts(
  1679. {},
  1680. {self.config_name: self.base_config},
  1681. DEFAULT_VERSION)
  1682. assert set(service_dict[self.config_name]) == set(self.base_config)
  1683. def test_add_item(self):
  1684. service_dict = config.merge_service_dicts(
  1685. {self.config_name: self.base_config},
  1686. {self.config_name: self.override_config},
  1687. DEFAULT_VERSION)
  1688. assert set(service_dict[self.config_name]) == set(self.merged_config())
  1689. class MergePortsTest(unittest.TestCase, MergeListsTest):
  1690. config_name = 'ports'
  1691. base_config = ['10:8000', '9000']
  1692. override_config = ['20:8000']
  1693. class MergeNetworksTest(unittest.TestCase, MergeListsTest):
  1694. config_name = 'networks'
  1695. base_config = ['frontend', 'backend']
  1696. override_config = ['monitoring']
  1697. class MergeStringsOrListsTest(unittest.TestCase):
  1698. def test_no_override(self):
  1699. service_dict = config.merge_service_dicts(
  1700. {'dns': '8.8.8.8'},
  1701. {},
  1702. DEFAULT_VERSION)
  1703. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1704. def test_no_base(self):
  1705. service_dict = config.merge_service_dicts(
  1706. {},
  1707. {'dns': '8.8.8.8'},
  1708. DEFAULT_VERSION)
  1709. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1710. def test_add_string(self):
  1711. service_dict = config.merge_service_dicts(
  1712. {'dns': ['8.8.8.8']},
  1713. {'dns': '9.9.9.9'},
  1714. DEFAULT_VERSION)
  1715. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1716. def test_add_list(self):
  1717. service_dict = config.merge_service_dicts(
  1718. {'dns': '8.8.8.8'},
  1719. {'dns': ['9.9.9.9']},
  1720. DEFAULT_VERSION)
  1721. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1722. class MergeLabelsTest(unittest.TestCase):
  1723. def test_empty(self):
  1724. assert 'labels' not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1725. def test_no_override(self):
  1726. service_dict = config.merge_service_dicts(
  1727. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1728. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1729. DEFAULT_VERSION)
  1730. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1731. def test_no_base(self):
  1732. service_dict = config.merge_service_dicts(
  1733. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1734. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1735. DEFAULT_VERSION)
  1736. assert service_dict['labels'] == {'foo': '2'}
  1737. def test_override_explicit_value(self):
  1738. service_dict = config.merge_service_dicts(
  1739. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1740. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1741. DEFAULT_VERSION)
  1742. assert service_dict['labels'] == {'foo': '2', 'bar': ''}
  1743. def test_add_explicit_value(self):
  1744. service_dict = config.merge_service_dicts(
  1745. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1746. make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
  1747. DEFAULT_VERSION)
  1748. assert service_dict['labels'] == {'foo': '1', 'bar': '2'}
  1749. def test_remove_explicit_value(self):
  1750. service_dict = config.merge_service_dicts(
  1751. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
  1752. make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
  1753. DEFAULT_VERSION)
  1754. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1755. class MemoryOptionsTest(unittest.TestCase):
  1756. def test_validation_fails_with_just_memswap_limit(self):
  1757. """
  1758. When you set a 'memswap_limit' it is invalid config unless you also set
  1759. a mem_limit
  1760. """
  1761. with pytest.raises(ConfigurationError) as excinfo:
  1762. config.load(
  1763. build_config_details(
  1764. {
  1765. 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
  1766. },
  1767. 'tests/fixtures/extends',
  1768. 'filename.yml'
  1769. )
  1770. )
  1771. assert "foo.memswap_limit is invalid: when defining " \
  1772. "'memswap_limit' you must set 'mem_limit' as well" \
  1773. in excinfo.exconly()
  1774. def test_validation_with_correct_memswap_values(self):
  1775. service_dict = config.load(
  1776. build_config_details(
  1777. {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
  1778. 'tests/fixtures/extends',
  1779. 'common.yml'
  1780. )
  1781. ).services
  1782. self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
  1783. def test_memswap_can_be_a_string(self):
  1784. service_dict = config.load(
  1785. build_config_details(
  1786. {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
  1787. 'tests/fixtures/extends',
  1788. 'common.yml'
  1789. )
  1790. ).services
  1791. self.assertEqual(service_dict[0]['memswap_limit'], "512M")
  1792. class EnvTest(unittest.TestCase):
  1793. def test_parse_environment_as_list(self):
  1794. environment = [
  1795. 'NORMAL=F1',
  1796. 'CONTAINS_EQUALS=F=2',
  1797. 'TRAILING_EQUALS=',
  1798. ]
  1799. self.assertEqual(
  1800. config.parse_environment(environment),
  1801. {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
  1802. )
  1803. def test_parse_environment_as_dict(self):
  1804. environment = {
  1805. 'NORMAL': 'F1',
  1806. 'CONTAINS_EQUALS': 'F=2',
  1807. 'TRAILING_EQUALS': None,
  1808. }
  1809. self.assertEqual(config.parse_environment(environment), environment)
  1810. def test_parse_environment_invalid(self):
  1811. with self.assertRaises(ConfigurationError):
  1812. config.parse_environment('a=b')
  1813. def test_parse_environment_empty(self):
  1814. self.assertEqual(config.parse_environment(None), {})
  1815. @mock.patch.dict(os.environ)
  1816. def test_resolve_environment(self):
  1817. os.environ['FILE_DEF'] = 'E1'
  1818. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1819. os.environ['ENV_DEF'] = 'E3'
  1820. service_dict = {
  1821. 'build': '.',
  1822. 'environment': {
  1823. 'FILE_DEF': 'F1',
  1824. 'FILE_DEF_EMPTY': '',
  1825. 'ENV_DEF': None,
  1826. 'NO_DEF': None
  1827. },
  1828. }
  1829. self.assertEqual(
  1830. resolve_environment(
  1831. service_dict, Environment.from_env_file(None)
  1832. ),
  1833. {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None},
  1834. )
  1835. def test_resolve_environment_from_env_file(self):
  1836. self.assertEqual(
  1837. resolve_environment({'env_file': ['tests/fixtures/env/one.env']}),
  1838. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
  1839. )
  1840. def test_resolve_environment_with_multiple_env_files(self):
  1841. service_dict = {
  1842. 'env_file': [
  1843. 'tests/fixtures/env/one.env',
  1844. 'tests/fixtures/env/two.env'
  1845. ]
  1846. }
  1847. self.assertEqual(
  1848. resolve_environment(service_dict),
  1849. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
  1850. )
  1851. def test_resolve_environment_nonexistent_file(self):
  1852. with pytest.raises(ConfigurationError) as exc:
  1853. config.load(build_config_details(
  1854. {'foo': {'image': 'example', 'env_file': 'nonexistent.env'}},
  1855. working_dir='tests/fixtures/env'))
  1856. assert 'Couldn\'t find env file' in exc.exconly()
  1857. assert 'nonexistent.env' in exc.exconly()
  1858. @mock.patch.dict(os.environ)
  1859. def test_resolve_environment_from_env_file_with_empty_values(self):
  1860. os.environ['FILE_DEF'] = 'E1'
  1861. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1862. os.environ['ENV_DEF'] = 'E3'
  1863. self.assertEqual(
  1864. resolve_environment(
  1865. {'env_file': ['tests/fixtures/env/resolve.env']},
  1866. Environment.from_env_file(None)
  1867. ),
  1868. {
  1869. 'FILE_DEF': u'bär',
  1870. 'FILE_DEF_EMPTY': '',
  1871. 'ENV_DEF': 'E3',
  1872. 'NO_DEF': None
  1873. },
  1874. )
  1875. @mock.patch.dict(os.environ)
  1876. def test_resolve_build_args(self):
  1877. os.environ['env_arg'] = 'value2'
  1878. build = {
  1879. 'context': '.',
  1880. 'args': {
  1881. 'arg1': 'value1',
  1882. 'empty_arg': '',
  1883. 'env_arg': None,
  1884. 'no_env': None
  1885. }
  1886. }
  1887. self.assertEqual(
  1888. resolve_build_args(build, Environment.from_env_file(build['context'])),
  1889. {'arg1': 'value1', 'empty_arg': '', 'env_arg': 'value2', 'no_env': None},
  1890. )
  1891. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  1892. @mock.patch.dict(os.environ)
  1893. def test_resolve_path(self):
  1894. os.environ['HOSTENV'] = '/tmp'
  1895. os.environ['CONTAINERENV'] = '/host/tmp'
  1896. service_dict = config.load(
  1897. build_config_details(
  1898. {'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
  1899. "tests/fixtures/env",
  1900. )
  1901. ).services[0]
  1902. self.assertEqual(
  1903. set(service_dict['volumes']),
  1904. set([VolumeSpec.parse('/tmp:/host/tmp')]))
  1905. service_dict = config.load(
  1906. build_config_details(
  1907. {'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
  1908. "tests/fixtures/env",
  1909. )
  1910. ).services[0]
  1911. self.assertEqual(
  1912. set(service_dict['volumes']),
  1913. set([VolumeSpec.parse('/opt/tmp:/opt/host/tmp')]))
  1914. def load_from_filename(filename):
  1915. return config.load(
  1916. config.find('.', [filename], Environment.from_env_file('.'))
  1917. ).services
  1918. class ExtendsTest(unittest.TestCase):
  1919. def test_extends(self):
  1920. service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
  1921. self.assertEqual(service_sort(service_dicts), service_sort([
  1922. {
  1923. 'name': 'mydb',
  1924. 'image': 'busybox',
  1925. 'command': 'top',
  1926. },
  1927. {
  1928. 'name': 'myweb',
  1929. 'image': 'busybox',
  1930. 'command': 'top',
  1931. 'network_mode': 'bridge',
  1932. 'links': ['mydb:db'],
  1933. 'environment': {
  1934. "FOO": "1",
  1935. "BAR": "2",
  1936. "BAZ": "2",
  1937. },
  1938. }
  1939. ]))
  1940. def test_merging_env_labels_ulimits(self):
  1941. service_dicts = load_from_filename('tests/fixtures/extends/common-env-labels-ulimits.yml')
  1942. self.assertEqual(service_sort(service_dicts), service_sort([
  1943. {
  1944. 'name': 'web',
  1945. 'image': 'busybox',
  1946. 'command': '/bin/true',
  1947. 'network_mode': 'host',
  1948. 'environment': {
  1949. "FOO": "2",
  1950. "BAR": "1",
  1951. "BAZ": "3",
  1952. },
  1953. 'labels': {'label': 'one'},
  1954. 'ulimits': {'nproc': 65535, 'memlock': {'soft': 1024, 'hard': 2048}}
  1955. }
  1956. ]))
  1957. def test_nested(self):
  1958. service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
  1959. self.assertEqual(service_dicts, [
  1960. {
  1961. 'name': 'myweb',
  1962. 'image': 'busybox',
  1963. 'command': '/bin/true',
  1964. 'network_mode': 'host',
  1965. 'environment': {
  1966. "FOO": "2",
  1967. "BAR": "2",
  1968. },
  1969. },
  1970. ])
  1971. def test_self_referencing_file(self):
  1972. """
  1973. We specify a 'file' key that is the filename we're already in.
  1974. """
  1975. service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
  1976. self.assertEqual(service_sort(service_dicts), service_sort([
  1977. {
  1978. 'environment':
  1979. {
  1980. 'YEP': '1', 'BAR': '1', 'BAZ': '3'
  1981. },
  1982. 'image': 'busybox',
  1983. 'name': 'myweb'
  1984. },
  1985. {
  1986. 'environment':
  1987. {'YEP': '1'},
  1988. 'image': 'busybox',
  1989. 'name': 'otherweb'
  1990. },
  1991. {
  1992. 'environment':
  1993. {'YEP': '1', 'BAZ': '3'},
  1994. 'image': 'busybox',
  1995. 'name': 'web'
  1996. }
  1997. ]))
  1998. def test_circular(self):
  1999. with pytest.raises(config.CircularReference) as exc:
  2000. load_from_filename('tests/fixtures/extends/circle-1.yml')
  2001. path = [
  2002. (os.path.basename(filename), service_name)
  2003. for (filename, service_name) in exc.value.trail
  2004. ]
  2005. expected = [
  2006. ('circle-1.yml', 'web'),
  2007. ('circle-2.yml', 'other'),
  2008. ('circle-1.yml', 'web'),
  2009. ]
  2010. self.assertEqual(path, expected)
  2011. def test_extends_validation_empty_dictionary(self):
  2012. with pytest.raises(ConfigurationError) as excinfo:
  2013. config.load(
  2014. build_config_details(
  2015. {
  2016. 'web': {'image': 'busybox', 'extends': {}},
  2017. },
  2018. 'tests/fixtures/extends',
  2019. 'filename.yml'
  2020. )
  2021. )
  2022. assert 'service' in excinfo.exconly()
  2023. def test_extends_validation_missing_service_key(self):
  2024. with pytest.raises(ConfigurationError) as excinfo:
  2025. config.load(
  2026. build_config_details(
  2027. {
  2028. 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
  2029. },
  2030. 'tests/fixtures/extends',
  2031. 'filename.yml'
  2032. )
  2033. )
  2034. assert "'service' is a required property" in excinfo.exconly()
  2035. def test_extends_validation_invalid_key(self):
  2036. with pytest.raises(ConfigurationError) as excinfo:
  2037. config.load(
  2038. build_config_details(
  2039. {
  2040. 'web': {
  2041. 'image': 'busybox',
  2042. 'extends': {
  2043. 'file': 'common.yml',
  2044. 'service': 'web',
  2045. 'rogue_key': 'is not allowed'
  2046. }
  2047. },
  2048. },
  2049. 'tests/fixtures/extends',
  2050. 'filename.yml'
  2051. )
  2052. )
  2053. assert "web.extends contains unsupported option: 'rogue_key'" \
  2054. in excinfo.exconly()
  2055. def test_extends_validation_sub_property_key(self):
  2056. with pytest.raises(ConfigurationError) as excinfo:
  2057. config.load(
  2058. build_config_details(
  2059. {
  2060. 'web': {
  2061. 'image': 'busybox',
  2062. 'extends': {
  2063. 'file': 1,
  2064. 'service': 'web',
  2065. }
  2066. },
  2067. },
  2068. 'tests/fixtures/extends',
  2069. 'filename.yml'
  2070. )
  2071. )
  2072. assert "web.extends.file contains 1, which is an invalid type, it should be a string" \
  2073. in excinfo.exconly()
  2074. def test_extends_validation_no_file_key_no_filename_set(self):
  2075. dictionary = {'extends': {'service': 'web'}}
  2076. with pytest.raises(ConfigurationError) as excinfo:
  2077. make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
  2078. assert 'file' in excinfo.exconly()
  2079. def test_extends_validation_valid_config(self):
  2080. service = config.load(
  2081. build_config_details(
  2082. {
  2083. 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
  2084. },
  2085. 'tests/fixtures/extends',
  2086. 'common.yml'
  2087. )
  2088. ).services
  2089. self.assertEquals(len(service), 1)
  2090. self.assertIsInstance(service[0], dict)
  2091. self.assertEquals(service[0]['command'], "/bin/true")
  2092. def test_extended_service_with_invalid_config(self):
  2093. with pytest.raises(ConfigurationError) as exc:
  2094. load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
  2095. assert (
  2096. "myweb has neither an image nor a build context specified" in
  2097. exc.exconly()
  2098. )
  2099. def test_extended_service_with_valid_config(self):
  2100. service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
  2101. self.assertEquals(service[0]['command'], "top")
  2102. def test_extends_file_defaults_to_self(self):
  2103. """
  2104. Test not specifying a file in our extends options that the
  2105. config is valid and correctly extends from itself.
  2106. """
  2107. service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
  2108. self.assertEqual(service_sort(service_dicts), service_sort([
  2109. {
  2110. 'name': 'myweb',
  2111. 'image': 'busybox',
  2112. 'environment': {
  2113. "BAR": "1",
  2114. "BAZ": "3",
  2115. }
  2116. },
  2117. {
  2118. 'name': 'web',
  2119. 'image': 'busybox',
  2120. 'environment': {
  2121. "BAZ": "3",
  2122. }
  2123. }
  2124. ]))
  2125. def test_invalid_links_in_extended_service(self):
  2126. with pytest.raises(ConfigurationError) as excinfo:
  2127. load_from_filename('tests/fixtures/extends/invalid-links.yml')
  2128. assert "services with 'links' cannot be extended" in excinfo.exconly()
  2129. def test_invalid_volumes_from_in_extended_service(self):
  2130. with pytest.raises(ConfigurationError) as excinfo:
  2131. load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
  2132. assert "services with 'volumes_from' cannot be extended" in excinfo.exconly()
  2133. def test_invalid_net_in_extended_service(self):
  2134. with pytest.raises(ConfigurationError) as excinfo:
  2135. load_from_filename('tests/fixtures/extends/invalid-net-v2.yml')
  2136. assert 'network_mode: service' in excinfo.exconly()
  2137. assert 'cannot be extended' in excinfo.exconly()
  2138. with pytest.raises(ConfigurationError) as excinfo:
  2139. load_from_filename('tests/fixtures/extends/invalid-net.yml')
  2140. assert 'net: container' in excinfo.exconly()
  2141. assert 'cannot be extended' in excinfo.exconly()
  2142. @mock.patch.dict(os.environ)
  2143. def test_load_config_runs_interpolation_in_extended_service(self):
  2144. os.environ.update(HOSTNAME_VALUE="penguin")
  2145. expected_interpolated_value = "host-penguin"
  2146. service_dicts = load_from_filename(
  2147. 'tests/fixtures/extends/valid-interpolation.yml')
  2148. for service in service_dicts:
  2149. assert service['hostname'] == expected_interpolated_value
  2150. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2151. def test_volume_path(self):
  2152. dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
  2153. paths = [
  2154. VolumeSpec(
  2155. os.path.abspath('tests/fixtures/volume-path/common/foo'),
  2156. '/foo',
  2157. 'rw'),
  2158. VolumeSpec(
  2159. os.path.abspath('tests/fixtures/volume-path/bar'),
  2160. '/bar',
  2161. 'rw')
  2162. ]
  2163. self.assertEqual(set(dicts[0]['volumes']), set(paths))
  2164. def test_parent_build_path_dne(self):
  2165. child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
  2166. self.assertEqual(child, [
  2167. {
  2168. 'name': 'dnechild',
  2169. 'image': 'busybox',
  2170. 'command': '/bin/true',
  2171. 'environment': {
  2172. "FOO": "1",
  2173. "BAR": "2",
  2174. },
  2175. },
  2176. ])
  2177. def test_load_throws_error_when_base_service_does_not_exist(self):
  2178. with pytest.raises(ConfigurationError) as excinfo:
  2179. load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
  2180. assert "Cannot extend service 'foo'" in excinfo.exconly()
  2181. assert "Service not found" in excinfo.exconly()
  2182. def test_partial_service_config_in_extends_is_still_valid(self):
  2183. dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
  2184. self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
  2185. def test_extended_service_with_verbose_and_shorthand_way(self):
  2186. services = load_from_filename('tests/fixtures/extends/verbose-and-shorthand.yml')
  2187. self.assertEqual(service_sort(services), service_sort([
  2188. {
  2189. 'name': 'base',
  2190. 'image': 'busybox',
  2191. 'environment': {'BAR': '1'},
  2192. },
  2193. {
  2194. 'name': 'verbose',
  2195. 'image': 'busybox',
  2196. 'environment': {'BAR': '1', 'FOO': '1'},
  2197. },
  2198. {
  2199. 'name': 'shorthand',
  2200. 'image': 'busybox',
  2201. 'environment': {'BAR': '1', 'FOO': '2'},
  2202. },
  2203. ]))
  2204. @mock.patch.dict(os.environ)
  2205. def test_extends_with_environment_and_env_files(self):
  2206. tmpdir = py.test.ensuretemp('test_extends_with_environment')
  2207. self.addCleanup(tmpdir.remove)
  2208. commondir = tmpdir.mkdir('common')
  2209. commondir.join('base.yml').write("""
  2210. app:
  2211. image: 'example/app'
  2212. env_file:
  2213. - 'envs'
  2214. environment:
  2215. - SECRET
  2216. - TEST_ONE=common
  2217. - TEST_TWO=common
  2218. """)
  2219. tmpdir.join('docker-compose.yml').write("""
  2220. ext:
  2221. extends:
  2222. file: common/base.yml
  2223. service: app
  2224. env_file:
  2225. - 'envs'
  2226. environment:
  2227. - THING
  2228. - TEST_ONE=top
  2229. """)
  2230. commondir.join('envs').write("""
  2231. COMMON_ENV_FILE
  2232. TEST_ONE=common-env-file
  2233. TEST_TWO=common-env-file
  2234. TEST_THREE=common-env-file
  2235. TEST_FOUR=common-env-file
  2236. """)
  2237. tmpdir.join('envs').write("""
  2238. TOP_ENV_FILE
  2239. TEST_ONE=top-env-file
  2240. TEST_TWO=top-env-file
  2241. TEST_THREE=top-env-file
  2242. """)
  2243. expected = [
  2244. {
  2245. 'name': 'ext',
  2246. 'image': 'example/app',
  2247. 'environment': {
  2248. 'SECRET': 'secret',
  2249. 'TOP_ENV_FILE': 'secret',
  2250. 'COMMON_ENV_FILE': 'secret',
  2251. 'THING': 'thing',
  2252. 'TEST_ONE': 'top',
  2253. 'TEST_TWO': 'common',
  2254. 'TEST_THREE': 'top-env-file',
  2255. 'TEST_FOUR': 'common-env-file',
  2256. },
  2257. },
  2258. ]
  2259. os.environ['SECRET'] = 'secret'
  2260. os.environ['THING'] = 'thing'
  2261. os.environ['COMMON_ENV_FILE'] = 'secret'
  2262. os.environ['TOP_ENV_FILE'] = 'secret'
  2263. config = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2264. assert config == expected
  2265. def test_extends_with_mixed_versions_is_error(self):
  2266. tmpdir = py.test.ensuretemp('test_extends_with_mixed_version')
  2267. self.addCleanup(tmpdir.remove)
  2268. tmpdir.join('docker-compose.yml').write("""
  2269. version: "2"
  2270. services:
  2271. web:
  2272. extends:
  2273. file: base.yml
  2274. service: base
  2275. image: busybox
  2276. """)
  2277. tmpdir.join('base.yml').write("""
  2278. base:
  2279. volumes: ['/foo']
  2280. ports: ['3000:3000']
  2281. """)
  2282. with pytest.raises(ConfigurationError) as exc:
  2283. load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2284. assert 'Version mismatch' in exc.exconly()
  2285. def test_extends_with_defined_version_passes(self):
  2286. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2287. self.addCleanup(tmpdir.remove)
  2288. tmpdir.join('docker-compose.yml').write("""
  2289. version: "2"
  2290. services:
  2291. web:
  2292. extends:
  2293. file: base.yml
  2294. service: base
  2295. image: busybox
  2296. """)
  2297. tmpdir.join('base.yml').write("""
  2298. version: "2"
  2299. services:
  2300. base:
  2301. volumes: ['/foo']
  2302. ports: ['3000:3000']
  2303. command: top
  2304. """)
  2305. service = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2306. self.assertEquals(service[0]['command'], "top")
  2307. def test_extends_with_depends_on(self):
  2308. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2309. self.addCleanup(tmpdir.remove)
  2310. tmpdir.join('docker-compose.yml').write("""
  2311. version: "2"
  2312. services:
  2313. base:
  2314. image: example
  2315. web:
  2316. extends: base
  2317. image: busybox
  2318. depends_on: ['other']
  2319. other:
  2320. image: example
  2321. """)
  2322. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2323. assert service_sort(services)[2]['depends_on'] == ['other']
  2324. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2325. class ExpandPathTest(unittest.TestCase):
  2326. working_dir = '/home/user/somedir'
  2327. def test_expand_path_normal(self):
  2328. result = config.expand_path(self.working_dir, 'myfile')
  2329. self.assertEqual(result, self.working_dir + '/' + 'myfile')
  2330. def test_expand_path_absolute(self):
  2331. abs_path = '/home/user/otherdir/somefile'
  2332. result = config.expand_path(self.working_dir, abs_path)
  2333. self.assertEqual(result, abs_path)
  2334. def test_expand_path_with_tilde(self):
  2335. test_path = '~/otherdir/somefile'
  2336. with mock.patch.dict(os.environ):
  2337. os.environ['HOME'] = user_path = '/home/user/'
  2338. result = config.expand_path(self.working_dir, test_path)
  2339. self.assertEqual(result, user_path + 'otherdir/somefile')
  2340. class VolumePathTest(unittest.TestCase):
  2341. @pytest.mark.xfail((not IS_WINDOWS_PLATFORM), reason='does not have a drive')
  2342. def test_split_path_mapping_with_windows_path(self):
  2343. host_path = "c:\\Users\\msamblanet\\Documents\\anvil\\connect\\config"
  2344. windows_volume_path = host_path + ":/opt/connect/config:ro"
  2345. expected_mapping = ("/opt/connect/config:ro", host_path)
  2346. mapping = config.split_path_mapping(windows_volume_path)
  2347. self.assertEqual(mapping, expected_mapping)
  2348. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2349. class BuildPathTest(unittest.TestCase):
  2350. def setUp(self):
  2351. self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
  2352. def test_nonexistent_path(self):
  2353. with self.assertRaises(ConfigurationError):
  2354. config.load(
  2355. build_config_details(
  2356. {
  2357. 'foo': {'build': 'nonexistent.path'},
  2358. },
  2359. 'working_dir',
  2360. 'filename.yml'
  2361. )
  2362. )
  2363. def test_relative_path(self):
  2364. relative_build_path = '../build-ctx/'
  2365. service_dict = make_service_dict(
  2366. 'relpath',
  2367. {'build': relative_build_path},
  2368. working_dir='tests/fixtures/build-path'
  2369. )
  2370. self.assertEquals(service_dict['build'], self.abs_context_path)
  2371. def test_absolute_path(self):
  2372. service_dict = make_service_dict(
  2373. 'abspath',
  2374. {'build': self.abs_context_path},
  2375. working_dir='tests/fixtures/build-path'
  2376. )
  2377. self.assertEquals(service_dict['build'], self.abs_context_path)
  2378. def test_from_file(self):
  2379. service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
  2380. self.assertEquals(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  2381. def test_valid_url_in_build_path(self):
  2382. valid_urls = [
  2383. 'git://github.com/docker/docker',
  2384. '[email protected]:docker/docker.git',
  2385. '[email protected]:atlassianlabs/atlassian-docker.git',
  2386. 'https://github.com/docker/docker.git',
  2387. 'http://github.com/docker/docker.git',
  2388. 'github.com/docker/docker.git',
  2389. ]
  2390. for valid_url in valid_urls:
  2391. service_dict = config.load(build_config_details({
  2392. 'validurl': {'build': valid_url},
  2393. }, '.', None)).services
  2394. assert service_dict[0]['build'] == {'context': valid_url}
  2395. def test_invalid_url_in_build_path(self):
  2396. invalid_urls = [
  2397. 'example.com/bogus',
  2398. 'ftp://example.com/',
  2399. '/path/does/not/exist',
  2400. ]
  2401. for invalid_url in invalid_urls:
  2402. with pytest.raises(ConfigurationError) as exc:
  2403. config.load(build_config_details({
  2404. 'invalidurl': {'build': invalid_url},
  2405. }, '.', None))
  2406. assert 'build path' in exc.exconly()
  2407. class GetDefaultConfigFilesTestCase(unittest.TestCase):
  2408. files = [
  2409. 'docker-compose.yml',
  2410. 'docker-compose.yaml',
  2411. ]
  2412. def test_get_config_path_default_file_in_basedir(self):
  2413. for index, filename in enumerate(self.files):
  2414. self.assertEqual(
  2415. filename,
  2416. get_config_filename_for_files(self.files[index:]))
  2417. with self.assertRaises(config.ComposeFileNotFound):
  2418. get_config_filename_for_files([])
  2419. def test_get_config_path_default_file_in_parent_dir(self):
  2420. """Test with files placed in the subdir"""
  2421. def get_config_in_subdir(files):
  2422. return get_config_filename_for_files(files, subdir=True)
  2423. for index, filename in enumerate(self.files):
  2424. self.assertEqual(filename, get_config_in_subdir(self.files[index:]))
  2425. with self.assertRaises(config.ComposeFileNotFound):
  2426. get_config_in_subdir([])
  2427. def get_config_filename_for_files(filenames, subdir=None):
  2428. def make_files(dirname, filenames):
  2429. for fname in filenames:
  2430. with open(os.path.join(dirname, fname), 'w') as f:
  2431. f.write('')
  2432. project_dir = tempfile.mkdtemp()
  2433. try:
  2434. make_files(project_dir, filenames)
  2435. if subdir:
  2436. base_dir = tempfile.mkdtemp(dir=project_dir)
  2437. else:
  2438. base_dir = project_dir
  2439. filename, = config.get_default_config_files(base_dir)
  2440. return os.path.basename(filename)
  2441. finally:
  2442. shutil.rmtree(project_dir)