config_test.py 98 KB

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