config_test.py 96 KB

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