config_test.py 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085
  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_merge_logging_v2(self):
  1301. base = {
  1302. 'image': 'alpine:edge',
  1303. 'logging': {
  1304. 'driver': 'json-file',
  1305. 'options': {
  1306. 'frequency': '2000',
  1307. 'timeout': '23'
  1308. }
  1309. }
  1310. }
  1311. override = {
  1312. 'logging': {
  1313. 'options': {
  1314. 'timeout': '360',
  1315. 'pretty-print': 'on'
  1316. }
  1317. }
  1318. }
  1319. actual = config.merge_service_dicts(base, override, V2_0)
  1320. assert actual == {
  1321. 'image': 'alpine:edge',
  1322. 'logging': {
  1323. 'driver': 'json-file',
  1324. 'options': {
  1325. 'frequency': '2000',
  1326. 'timeout': '360',
  1327. 'pretty-print': 'on'
  1328. }
  1329. }
  1330. }
  1331. def test_merge_logging_v2_override_driver(self):
  1332. base = {
  1333. 'image': 'alpine:edge',
  1334. 'logging': {
  1335. 'driver': 'json-file',
  1336. 'options': {
  1337. 'frequency': '2000',
  1338. 'timeout': '23'
  1339. }
  1340. }
  1341. }
  1342. override = {
  1343. 'logging': {
  1344. 'driver': 'syslog',
  1345. 'options': {
  1346. 'timeout': '360',
  1347. 'pretty-print': 'on'
  1348. }
  1349. }
  1350. }
  1351. actual = config.merge_service_dicts(base, override, V2_0)
  1352. assert actual == {
  1353. 'image': 'alpine:edge',
  1354. 'logging': {
  1355. 'driver': 'syslog',
  1356. 'options': {
  1357. 'timeout': '360',
  1358. 'pretty-print': 'on'
  1359. }
  1360. }
  1361. }
  1362. def test_merge_logging_v2_no_base_driver(self):
  1363. base = {
  1364. 'image': 'alpine:edge',
  1365. 'logging': {
  1366. 'options': {
  1367. 'frequency': '2000',
  1368. 'timeout': '23'
  1369. }
  1370. }
  1371. }
  1372. override = {
  1373. 'logging': {
  1374. 'driver': 'json-file',
  1375. 'options': {
  1376. 'timeout': '360',
  1377. 'pretty-print': 'on'
  1378. }
  1379. }
  1380. }
  1381. actual = config.merge_service_dicts(base, override, V2_0)
  1382. assert actual == {
  1383. 'image': 'alpine:edge',
  1384. 'logging': {
  1385. 'driver': 'json-file',
  1386. 'options': {
  1387. 'frequency': '2000',
  1388. 'timeout': '360',
  1389. 'pretty-print': 'on'
  1390. }
  1391. }
  1392. }
  1393. def test_merge_logging_v2_no_drivers(self):
  1394. base = {
  1395. 'image': 'alpine:edge',
  1396. 'logging': {
  1397. 'options': {
  1398. 'frequency': '2000',
  1399. 'timeout': '23'
  1400. }
  1401. }
  1402. }
  1403. override = {
  1404. 'logging': {
  1405. 'options': {
  1406. 'timeout': '360',
  1407. 'pretty-print': 'on'
  1408. }
  1409. }
  1410. }
  1411. actual = config.merge_service_dicts(base, override, V2_0)
  1412. assert actual == {
  1413. 'image': 'alpine:edge',
  1414. 'logging': {
  1415. 'options': {
  1416. 'frequency': '2000',
  1417. 'timeout': '360',
  1418. 'pretty-print': 'on'
  1419. }
  1420. }
  1421. }
  1422. def test_merge_logging_v2_no_override_options(self):
  1423. base = {
  1424. 'image': 'alpine:edge',
  1425. 'logging': {
  1426. 'driver': 'json-file',
  1427. 'options': {
  1428. 'frequency': '2000',
  1429. 'timeout': '23'
  1430. }
  1431. }
  1432. }
  1433. override = {
  1434. 'logging': {
  1435. 'driver': 'syslog'
  1436. }
  1437. }
  1438. actual = config.merge_service_dicts(base, override, V2_0)
  1439. assert actual == {
  1440. 'image': 'alpine:edge',
  1441. 'logging': {
  1442. 'driver': 'syslog',
  1443. 'options': None
  1444. }
  1445. }
  1446. def test_external_volume_config(self):
  1447. config_details = build_config_details({
  1448. 'version': '2',
  1449. 'services': {
  1450. 'bogus': {'image': 'busybox'}
  1451. },
  1452. 'volumes': {
  1453. 'ext': {'external': True},
  1454. 'ext2': {'external': {'name': 'aliased'}}
  1455. }
  1456. })
  1457. config_result = config.load(config_details)
  1458. volumes = config_result.volumes
  1459. assert 'ext' in volumes
  1460. assert volumes['ext']['external'] is True
  1461. assert 'ext2' in volumes
  1462. assert volumes['ext2']['external']['name'] == 'aliased'
  1463. def test_external_volume_invalid_config(self):
  1464. config_details = build_config_details({
  1465. 'version': '2',
  1466. 'services': {
  1467. 'bogus': {'image': 'busybox'}
  1468. },
  1469. 'volumes': {
  1470. 'ext': {'external': True, 'driver': 'foo'}
  1471. }
  1472. })
  1473. with pytest.raises(ConfigurationError):
  1474. config.load(config_details)
  1475. def test_depends_on_orders_services(self):
  1476. config_details = build_config_details({
  1477. 'version': '2',
  1478. 'services': {
  1479. 'one': {'image': 'busybox', 'depends_on': ['three', 'two']},
  1480. 'two': {'image': 'busybox', 'depends_on': ['three']},
  1481. 'three': {'image': 'busybox'},
  1482. },
  1483. })
  1484. actual = config.load(config_details)
  1485. assert (
  1486. [service['name'] for service in actual.services] ==
  1487. ['three', 'two', 'one']
  1488. )
  1489. def test_depends_on_unknown_service_errors(self):
  1490. config_details = build_config_details({
  1491. 'version': '2',
  1492. 'services': {
  1493. 'one': {'image': 'busybox', 'depends_on': ['three']},
  1494. },
  1495. })
  1496. with pytest.raises(ConfigurationError) as exc:
  1497. config.load(config_details)
  1498. assert "Service 'one' depends on service 'three'" in exc.exconly()
  1499. def test_linked_service_is_undefined(self):
  1500. with self.assertRaises(ConfigurationError):
  1501. config.load(
  1502. build_config_details({
  1503. 'version': '2',
  1504. 'services': {
  1505. 'web': {'image': 'busybox', 'links': ['db:db']},
  1506. },
  1507. })
  1508. )
  1509. def test_load_dockerfile_without_context(self):
  1510. config_details = build_config_details({
  1511. 'version': '2',
  1512. 'services': {
  1513. 'one': {'build': {'dockerfile': 'Dockerfile.foo'}},
  1514. },
  1515. })
  1516. with pytest.raises(ConfigurationError) as exc:
  1517. config.load(config_details)
  1518. assert 'has neither an image nor a build context' in exc.exconly()
  1519. class NetworkModeTest(unittest.TestCase):
  1520. def test_network_mode_standard(self):
  1521. config_data = config.load(build_config_details({
  1522. 'version': '2',
  1523. 'services': {
  1524. 'web': {
  1525. 'image': 'busybox',
  1526. 'command': "top",
  1527. 'network_mode': 'bridge',
  1528. },
  1529. },
  1530. }))
  1531. assert config_data.services[0]['network_mode'] == 'bridge'
  1532. def test_network_mode_standard_v1(self):
  1533. config_data = config.load(build_config_details({
  1534. 'web': {
  1535. 'image': 'busybox',
  1536. 'command': "top",
  1537. 'net': 'bridge',
  1538. },
  1539. }))
  1540. assert config_data.services[0]['network_mode'] == 'bridge'
  1541. assert 'net' not in config_data.services[0]
  1542. def test_network_mode_container(self):
  1543. config_data = config.load(build_config_details({
  1544. 'version': '2',
  1545. 'services': {
  1546. 'web': {
  1547. 'image': 'busybox',
  1548. 'command': "top",
  1549. 'network_mode': 'container:foo',
  1550. },
  1551. },
  1552. }))
  1553. assert config_data.services[0]['network_mode'] == 'container:foo'
  1554. def test_network_mode_container_v1(self):
  1555. config_data = config.load(build_config_details({
  1556. 'web': {
  1557. 'image': 'busybox',
  1558. 'command': "top",
  1559. 'net': 'container:foo',
  1560. },
  1561. }))
  1562. assert config_data.services[0]['network_mode'] == 'container:foo'
  1563. def test_network_mode_service(self):
  1564. config_data = config.load(build_config_details({
  1565. 'version': '2',
  1566. 'services': {
  1567. 'web': {
  1568. 'image': 'busybox',
  1569. 'command': "top",
  1570. 'network_mode': 'service:foo',
  1571. },
  1572. 'foo': {
  1573. 'image': 'busybox',
  1574. 'command': "top",
  1575. },
  1576. },
  1577. }))
  1578. assert config_data.services[1]['network_mode'] == 'service:foo'
  1579. def test_network_mode_service_v1(self):
  1580. config_data = config.load(build_config_details({
  1581. 'web': {
  1582. 'image': 'busybox',
  1583. 'command': "top",
  1584. 'net': 'container:foo',
  1585. },
  1586. 'foo': {
  1587. 'image': 'busybox',
  1588. 'command': "top",
  1589. },
  1590. }))
  1591. assert config_data.services[1]['network_mode'] == 'service:foo'
  1592. def test_network_mode_service_nonexistent(self):
  1593. with pytest.raises(ConfigurationError) as excinfo:
  1594. config.load(build_config_details({
  1595. 'version': '2',
  1596. 'services': {
  1597. 'web': {
  1598. 'image': 'busybox',
  1599. 'command': "top",
  1600. 'network_mode': 'service:foo',
  1601. },
  1602. },
  1603. }))
  1604. assert "service 'foo' which is undefined" in excinfo.exconly()
  1605. def test_network_mode_plus_networks_is_invalid(self):
  1606. with pytest.raises(ConfigurationError) as excinfo:
  1607. config.load(build_config_details({
  1608. 'version': '2',
  1609. 'services': {
  1610. 'web': {
  1611. 'image': 'busybox',
  1612. 'command': "top",
  1613. 'network_mode': 'bridge',
  1614. 'networks': ['front'],
  1615. },
  1616. },
  1617. 'networks': {
  1618. 'front': None,
  1619. }
  1620. }))
  1621. assert "'network_mode' and 'networks' cannot be combined" in excinfo.exconly()
  1622. class PortsTest(unittest.TestCase):
  1623. INVALID_PORTS_TYPES = [
  1624. {"1": "8000"},
  1625. False,
  1626. "8000",
  1627. 8000,
  1628. ]
  1629. NON_UNIQUE_SINGLE_PORTS = [
  1630. ["8000", "8000"],
  1631. ]
  1632. INVALID_PORT_MAPPINGS = [
  1633. ["8000-8001:8000"],
  1634. ]
  1635. VALID_SINGLE_PORTS = [
  1636. ["8000"],
  1637. ["8000/tcp"],
  1638. ["8000", "9000"],
  1639. [8000],
  1640. [8000, 9000],
  1641. ]
  1642. VALID_PORT_MAPPINGS = [
  1643. ["8000:8050"],
  1644. ["49153-49154:3002-3003"],
  1645. ]
  1646. def test_config_invalid_ports_type_validation(self):
  1647. for invalid_ports in self.INVALID_PORTS_TYPES:
  1648. with pytest.raises(ConfigurationError) as exc:
  1649. self.check_config({'ports': invalid_ports})
  1650. assert "contains an invalid type" in exc.value.msg
  1651. def test_config_non_unique_ports_validation(self):
  1652. for invalid_ports in self.NON_UNIQUE_SINGLE_PORTS:
  1653. with pytest.raises(ConfigurationError) as exc:
  1654. self.check_config({'ports': invalid_ports})
  1655. assert "non-unique" in exc.value.msg
  1656. def test_config_invalid_ports_format_validation(self):
  1657. for invalid_ports in self.INVALID_PORT_MAPPINGS:
  1658. with pytest.raises(ConfigurationError) as exc:
  1659. self.check_config({'ports': invalid_ports})
  1660. assert "Port ranges don't match in length" in exc.value.msg
  1661. def test_config_valid_ports_format_validation(self):
  1662. for valid_ports in self.VALID_SINGLE_PORTS + self.VALID_PORT_MAPPINGS:
  1663. self.check_config({'ports': valid_ports})
  1664. def test_config_invalid_expose_type_validation(self):
  1665. for invalid_expose in self.INVALID_PORTS_TYPES:
  1666. with pytest.raises(ConfigurationError) as exc:
  1667. self.check_config({'expose': invalid_expose})
  1668. assert "contains an invalid type" in exc.value.msg
  1669. def test_config_non_unique_expose_validation(self):
  1670. for invalid_expose in self.NON_UNIQUE_SINGLE_PORTS:
  1671. with pytest.raises(ConfigurationError) as exc:
  1672. self.check_config({'expose': invalid_expose})
  1673. assert "non-unique" in exc.value.msg
  1674. def test_config_invalid_expose_format_validation(self):
  1675. # Valid port mappings ARE NOT valid 'expose' entries
  1676. for invalid_expose in self.INVALID_PORT_MAPPINGS + self.VALID_PORT_MAPPINGS:
  1677. with pytest.raises(ConfigurationError) as exc:
  1678. self.check_config({'expose': invalid_expose})
  1679. assert "should be of the format" in exc.value.msg
  1680. def test_config_valid_expose_format_validation(self):
  1681. # Valid single ports ARE valid 'expose' entries
  1682. for valid_expose in self.VALID_SINGLE_PORTS:
  1683. self.check_config({'expose': valid_expose})
  1684. def check_config(self, cfg):
  1685. config.load(
  1686. build_config_details(
  1687. {'web': dict(image='busybox', **cfg)},
  1688. 'working_dir',
  1689. 'filename.yml'
  1690. )
  1691. )
  1692. class InterpolationTest(unittest.TestCase):
  1693. @mock.patch.dict(os.environ)
  1694. def test_config_file_with_environment_file(self):
  1695. project_dir = 'tests/fixtures/default-env-file'
  1696. service_dicts = config.load(
  1697. config.find(
  1698. project_dir, None, Environment.from_env_file(project_dir)
  1699. )
  1700. ).services
  1701. self.assertEqual(service_dicts[0], {
  1702. 'name': 'web',
  1703. 'image': 'alpine:latest',
  1704. 'ports': ['5643', '9999'],
  1705. 'command': 'true'
  1706. })
  1707. @mock.patch.dict(os.environ)
  1708. def test_config_file_with_environment_variable(self):
  1709. project_dir = 'tests/fixtures/environment-interpolation'
  1710. os.environ.update(
  1711. IMAGE="busybox",
  1712. HOST_PORT="80",
  1713. LABEL_VALUE="myvalue",
  1714. )
  1715. service_dicts = config.load(
  1716. config.find(
  1717. project_dir, None, Environment.from_env_file(project_dir)
  1718. )
  1719. ).services
  1720. self.assertEqual(service_dicts, [
  1721. {
  1722. 'name': 'web',
  1723. 'image': 'busybox',
  1724. 'ports': ['80:8000'],
  1725. 'labels': {'mylabel': 'myvalue'},
  1726. 'hostname': 'host-',
  1727. 'command': '${ESCAPED}',
  1728. }
  1729. ])
  1730. @mock.patch.dict(os.environ)
  1731. def test_unset_variable_produces_warning(self):
  1732. os.environ.pop('FOO', None)
  1733. os.environ.pop('BAR', None)
  1734. config_details = build_config_details(
  1735. {
  1736. 'web': {
  1737. 'image': '${FOO}',
  1738. 'command': '${BAR}',
  1739. 'container_name': '${BAR}',
  1740. },
  1741. },
  1742. '.',
  1743. None,
  1744. )
  1745. with mock.patch('compose.config.environment.log') as log:
  1746. config.load(config_details)
  1747. self.assertEqual(2, log.warn.call_count)
  1748. warnings = sorted(args[0][0] for args in log.warn.call_args_list)
  1749. self.assertIn('BAR', warnings[0])
  1750. self.assertIn('FOO', warnings[1])
  1751. @mock.patch.dict(os.environ)
  1752. def test_invalid_interpolation(self):
  1753. with self.assertRaises(config.ConfigurationError) as cm:
  1754. config.load(
  1755. build_config_details(
  1756. {'web': {'image': '${'}},
  1757. 'working_dir',
  1758. 'filename.yml'
  1759. )
  1760. )
  1761. self.assertIn('Invalid', cm.exception.msg)
  1762. self.assertIn('for "image" option', cm.exception.msg)
  1763. self.assertIn('in service "web"', cm.exception.msg)
  1764. self.assertIn('"${"', cm.exception.msg)
  1765. def test_empty_environment_key_allowed(self):
  1766. service_dict = config.load(
  1767. build_config_details(
  1768. {
  1769. 'web': {
  1770. 'build': '.',
  1771. 'environment': {
  1772. 'POSTGRES_PASSWORD': ''
  1773. },
  1774. },
  1775. },
  1776. '.',
  1777. None,
  1778. )
  1779. ).services[0]
  1780. self.assertEquals(service_dict['environment']['POSTGRES_PASSWORD'], '')
  1781. class VolumeConfigTest(unittest.TestCase):
  1782. def test_no_binding(self):
  1783. d = make_service_dict('foo', {'build': '.', 'volumes': ['/data']}, working_dir='.')
  1784. self.assertEqual(d['volumes'], ['/data'])
  1785. @mock.patch.dict(os.environ)
  1786. def test_volume_binding_with_environment_variable(self):
  1787. os.environ['VOLUME_PATH'] = '/host/path'
  1788. d = config.load(
  1789. build_config_details(
  1790. {'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
  1791. '.',
  1792. None,
  1793. )
  1794. ).services[0]
  1795. self.assertEqual(d['volumes'], [VolumeSpec.parse('/host/path:/container/path')])
  1796. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1797. @mock.patch.dict(os.environ)
  1798. def test_volume_binding_with_home(self):
  1799. os.environ['HOME'] = '/home/user'
  1800. d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
  1801. self.assertEqual(d['volumes'], ['/home/user:/container/path'])
  1802. def test_name_does_not_expand(self):
  1803. d = make_service_dict('foo', {'build': '.', 'volumes': ['mydatavolume:/data']}, working_dir='.')
  1804. self.assertEqual(d['volumes'], ['mydatavolume:/data'])
  1805. def test_absolute_posix_path_does_not_expand(self):
  1806. d = make_service_dict('foo', {'build': '.', 'volumes': ['/var/lib/data:/data']}, working_dir='.')
  1807. self.assertEqual(d['volumes'], ['/var/lib/data:/data'])
  1808. def test_absolute_windows_path_does_not_expand(self):
  1809. d = make_service_dict('foo', {'build': '.', 'volumes': ['c:\\data:/data']}, working_dir='.')
  1810. self.assertEqual(d['volumes'], ['c:\\data:/data'])
  1811. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1812. def test_relative_path_does_expand_posix(self):
  1813. d = make_service_dict(
  1814. 'foo',
  1815. {'build': '.', 'volumes': ['./data:/data']},
  1816. working_dir='/home/me/myproject')
  1817. self.assertEqual(d['volumes'], ['/home/me/myproject/data:/data'])
  1818. d = make_service_dict(
  1819. 'foo',
  1820. {'build': '.', 'volumes': ['.:/data']},
  1821. working_dir='/home/me/myproject')
  1822. self.assertEqual(d['volumes'], ['/home/me/myproject:/data'])
  1823. d = make_service_dict(
  1824. 'foo',
  1825. {'build': '.', 'volumes': ['../otherproject:/data']},
  1826. working_dir='/home/me/myproject')
  1827. self.assertEqual(d['volumes'], ['/home/me/otherproject:/data'])
  1828. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='windows paths')
  1829. def test_relative_path_does_expand_windows(self):
  1830. d = make_service_dict(
  1831. 'foo',
  1832. {'build': '.', 'volumes': ['./data:/data']},
  1833. working_dir='c:\\Users\\me\\myproject')
  1834. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject\\data:/data'])
  1835. d = make_service_dict(
  1836. 'foo',
  1837. {'build': '.', 'volumes': ['.:/data']},
  1838. working_dir='c:\\Users\\me\\myproject')
  1839. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject:/data'])
  1840. d = make_service_dict(
  1841. 'foo',
  1842. {'build': '.', 'volumes': ['../otherproject:/data']},
  1843. working_dir='c:\\Users\\me\\myproject')
  1844. self.assertEqual(d['volumes'], ['c:\\Users\\me\\otherproject:/data'])
  1845. @mock.patch.dict(os.environ)
  1846. def test_home_directory_with_driver_does_not_expand(self):
  1847. os.environ['NAME'] = 'surprise!'
  1848. d = make_service_dict('foo', {
  1849. 'build': '.',
  1850. 'volumes': ['~:/data'],
  1851. 'volume_driver': 'foodriver',
  1852. }, working_dir='.')
  1853. self.assertEqual(d['volumes'], ['~:/data'])
  1854. def test_volume_path_with_non_ascii_directory(self):
  1855. volume = u'/Füü/data:/data'
  1856. container_path = config.resolve_volume_path(".", volume)
  1857. self.assertEqual(container_path, volume)
  1858. class MergePathMappingTest(object):
  1859. config_name = ""
  1860. def test_empty(self):
  1861. service_dict = config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1862. assert self.config_name not in service_dict
  1863. def test_no_override(self):
  1864. service_dict = config.merge_service_dicts(
  1865. {self.config_name: ['/foo:/code', '/data']},
  1866. {},
  1867. DEFAULT_VERSION)
  1868. assert set(service_dict[self.config_name]) == set(['/foo:/code', '/data'])
  1869. def test_no_base(self):
  1870. service_dict = config.merge_service_dicts(
  1871. {},
  1872. {self.config_name: ['/bar:/code']},
  1873. DEFAULT_VERSION)
  1874. assert set(service_dict[self.config_name]) == set(['/bar:/code'])
  1875. def test_override_explicit_path(self):
  1876. service_dict = config.merge_service_dicts(
  1877. {self.config_name: ['/foo:/code', '/data']},
  1878. {self.config_name: ['/bar:/code']},
  1879. DEFAULT_VERSION)
  1880. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1881. def test_add_explicit_path(self):
  1882. service_dict = config.merge_service_dicts(
  1883. {self.config_name: ['/foo:/code', '/data']},
  1884. {self.config_name: ['/bar:/code', '/quux:/data']},
  1885. DEFAULT_VERSION)
  1886. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/quux:/data'])
  1887. def test_remove_explicit_path(self):
  1888. service_dict = config.merge_service_dicts(
  1889. {self.config_name: ['/foo:/code', '/quux:/data']},
  1890. {self.config_name: ['/bar:/code', '/data']},
  1891. DEFAULT_VERSION)
  1892. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1893. class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
  1894. config_name = 'volumes'
  1895. class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
  1896. config_name = 'devices'
  1897. class BuildOrImageMergeTest(unittest.TestCase):
  1898. def test_merge_build_or_image_no_override(self):
  1899. self.assertEqual(
  1900. config.merge_service_dicts({'build': '.'}, {}, V1),
  1901. {'build': '.'},
  1902. )
  1903. self.assertEqual(
  1904. config.merge_service_dicts({'image': 'redis'}, {}, V1),
  1905. {'image': 'redis'},
  1906. )
  1907. def test_merge_build_or_image_override_with_same(self):
  1908. self.assertEqual(
  1909. config.merge_service_dicts({'build': '.'}, {'build': './web'}, V1),
  1910. {'build': './web'},
  1911. )
  1912. self.assertEqual(
  1913. config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}, V1),
  1914. {'image': 'postgres'},
  1915. )
  1916. def test_merge_build_or_image_override_with_other(self):
  1917. self.assertEqual(
  1918. config.merge_service_dicts({'build': '.'}, {'image': 'redis'}, V1),
  1919. {'image': 'redis'},
  1920. )
  1921. self.assertEqual(
  1922. config.merge_service_dicts({'image': 'redis'}, {'build': '.'}, V1),
  1923. {'build': '.'}
  1924. )
  1925. class MergeListsTest(object):
  1926. config_name = ""
  1927. base_config = []
  1928. override_config = []
  1929. def merged_config(self):
  1930. return set(self.base_config) | set(self.override_config)
  1931. def test_empty(self):
  1932. assert self.config_name not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1933. def test_no_override(self):
  1934. service_dict = config.merge_service_dicts(
  1935. {self.config_name: self.base_config},
  1936. {},
  1937. DEFAULT_VERSION)
  1938. assert set(service_dict[self.config_name]) == set(self.base_config)
  1939. def test_no_base(self):
  1940. service_dict = config.merge_service_dicts(
  1941. {},
  1942. {self.config_name: self.base_config},
  1943. DEFAULT_VERSION)
  1944. assert set(service_dict[self.config_name]) == set(self.base_config)
  1945. def test_add_item(self):
  1946. service_dict = config.merge_service_dicts(
  1947. {self.config_name: self.base_config},
  1948. {self.config_name: self.override_config},
  1949. DEFAULT_VERSION)
  1950. assert set(service_dict[self.config_name]) == set(self.merged_config())
  1951. class MergePortsTest(unittest.TestCase, MergeListsTest):
  1952. config_name = 'ports'
  1953. base_config = ['10:8000', '9000']
  1954. override_config = ['20:8000']
  1955. def test_duplicate_port_mappings(self):
  1956. service_dict = config.merge_service_dicts(
  1957. {self.config_name: self.base_config},
  1958. {self.config_name: self.base_config},
  1959. DEFAULT_VERSION
  1960. )
  1961. assert set(service_dict[self.config_name]) == set(self.base_config)
  1962. class MergeNetworksTest(unittest.TestCase, MergeListsTest):
  1963. config_name = 'networks'
  1964. base_config = ['frontend', 'backend']
  1965. override_config = ['monitoring']
  1966. class MergeStringsOrListsTest(unittest.TestCase):
  1967. def test_no_override(self):
  1968. service_dict = config.merge_service_dicts(
  1969. {'dns': '8.8.8.8'},
  1970. {},
  1971. DEFAULT_VERSION)
  1972. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1973. def test_no_base(self):
  1974. service_dict = config.merge_service_dicts(
  1975. {},
  1976. {'dns': '8.8.8.8'},
  1977. DEFAULT_VERSION)
  1978. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1979. def test_add_string(self):
  1980. service_dict = config.merge_service_dicts(
  1981. {'dns': ['8.8.8.8']},
  1982. {'dns': '9.9.9.9'},
  1983. DEFAULT_VERSION)
  1984. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1985. def test_add_list(self):
  1986. service_dict = config.merge_service_dicts(
  1987. {'dns': '8.8.8.8'},
  1988. {'dns': ['9.9.9.9']},
  1989. DEFAULT_VERSION)
  1990. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1991. class MergeLabelsTest(unittest.TestCase):
  1992. def test_empty(self):
  1993. assert 'labels' not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1994. def test_no_override(self):
  1995. service_dict = config.merge_service_dicts(
  1996. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1997. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1998. DEFAULT_VERSION)
  1999. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  2000. def test_no_base(self):
  2001. service_dict = config.merge_service_dicts(
  2002. make_service_dict('foo', {'build': '.'}, 'tests/'),
  2003. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  2004. DEFAULT_VERSION)
  2005. assert service_dict['labels'] == {'foo': '2'}
  2006. def test_override_explicit_value(self):
  2007. service_dict = config.merge_service_dicts(
  2008. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2009. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  2010. DEFAULT_VERSION)
  2011. assert service_dict['labels'] == {'foo': '2', 'bar': ''}
  2012. def test_add_explicit_value(self):
  2013. service_dict = config.merge_service_dicts(
  2014. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  2015. make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
  2016. DEFAULT_VERSION)
  2017. assert service_dict['labels'] == {'foo': '1', 'bar': '2'}
  2018. def test_remove_explicit_value(self):
  2019. service_dict = config.merge_service_dicts(
  2020. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
  2021. make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
  2022. DEFAULT_VERSION)
  2023. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  2024. class MemoryOptionsTest(unittest.TestCase):
  2025. def test_validation_fails_with_just_memswap_limit(self):
  2026. """
  2027. When you set a 'memswap_limit' it is invalid config unless you also set
  2028. a mem_limit
  2029. """
  2030. with pytest.raises(ConfigurationError) as excinfo:
  2031. config.load(
  2032. build_config_details(
  2033. {
  2034. 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
  2035. },
  2036. 'tests/fixtures/extends',
  2037. 'filename.yml'
  2038. )
  2039. )
  2040. assert "foo.memswap_limit is invalid: when defining " \
  2041. "'memswap_limit' you must set 'mem_limit' as well" \
  2042. in excinfo.exconly()
  2043. def test_validation_with_correct_memswap_values(self):
  2044. service_dict = config.load(
  2045. build_config_details(
  2046. {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
  2047. 'tests/fixtures/extends',
  2048. 'common.yml'
  2049. )
  2050. ).services
  2051. self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
  2052. def test_memswap_can_be_a_string(self):
  2053. service_dict = config.load(
  2054. build_config_details(
  2055. {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
  2056. 'tests/fixtures/extends',
  2057. 'common.yml'
  2058. )
  2059. ).services
  2060. self.assertEqual(service_dict[0]['memswap_limit'], "512M")
  2061. class EnvTest(unittest.TestCase):
  2062. def test_parse_environment_as_list(self):
  2063. environment = [
  2064. 'NORMAL=F1',
  2065. 'CONTAINS_EQUALS=F=2',
  2066. 'TRAILING_EQUALS=',
  2067. ]
  2068. self.assertEqual(
  2069. config.parse_environment(environment),
  2070. {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
  2071. )
  2072. def test_parse_environment_as_dict(self):
  2073. environment = {
  2074. 'NORMAL': 'F1',
  2075. 'CONTAINS_EQUALS': 'F=2',
  2076. 'TRAILING_EQUALS': None,
  2077. }
  2078. self.assertEqual(config.parse_environment(environment), environment)
  2079. def test_parse_environment_invalid(self):
  2080. with self.assertRaises(ConfigurationError):
  2081. config.parse_environment('a=b')
  2082. def test_parse_environment_empty(self):
  2083. self.assertEqual(config.parse_environment(None), {})
  2084. @mock.patch.dict(os.environ)
  2085. def test_resolve_environment(self):
  2086. os.environ['FILE_DEF'] = 'E1'
  2087. os.environ['FILE_DEF_EMPTY'] = 'E2'
  2088. os.environ['ENV_DEF'] = 'E3'
  2089. service_dict = {
  2090. 'build': '.',
  2091. 'environment': {
  2092. 'FILE_DEF': 'F1',
  2093. 'FILE_DEF_EMPTY': '',
  2094. 'ENV_DEF': None,
  2095. 'NO_DEF': None
  2096. },
  2097. }
  2098. self.assertEqual(
  2099. resolve_environment(
  2100. service_dict, Environment.from_env_file(None)
  2101. ),
  2102. {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None},
  2103. )
  2104. def test_resolve_environment_from_env_file(self):
  2105. self.assertEqual(
  2106. resolve_environment({'env_file': ['tests/fixtures/env/one.env']}),
  2107. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
  2108. )
  2109. def test_resolve_environment_with_multiple_env_files(self):
  2110. service_dict = {
  2111. 'env_file': [
  2112. 'tests/fixtures/env/one.env',
  2113. 'tests/fixtures/env/two.env'
  2114. ]
  2115. }
  2116. self.assertEqual(
  2117. resolve_environment(service_dict),
  2118. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
  2119. )
  2120. def test_resolve_environment_nonexistent_file(self):
  2121. with pytest.raises(ConfigurationError) as exc:
  2122. config.load(build_config_details(
  2123. {'foo': {'image': 'example', 'env_file': 'nonexistent.env'}},
  2124. working_dir='tests/fixtures/env'))
  2125. assert 'Couldn\'t find env file' in exc.exconly()
  2126. assert 'nonexistent.env' in exc.exconly()
  2127. @mock.patch.dict(os.environ)
  2128. def test_resolve_environment_from_env_file_with_empty_values(self):
  2129. os.environ['FILE_DEF'] = 'E1'
  2130. os.environ['FILE_DEF_EMPTY'] = 'E2'
  2131. os.environ['ENV_DEF'] = 'E3'
  2132. self.assertEqual(
  2133. resolve_environment(
  2134. {'env_file': ['tests/fixtures/env/resolve.env']},
  2135. Environment.from_env_file(None)
  2136. ),
  2137. {
  2138. 'FILE_DEF': u'bär',
  2139. 'FILE_DEF_EMPTY': '',
  2140. 'ENV_DEF': 'E3',
  2141. 'NO_DEF': None
  2142. },
  2143. )
  2144. @mock.patch.dict(os.environ)
  2145. def test_resolve_build_args(self):
  2146. os.environ['env_arg'] = 'value2'
  2147. build = {
  2148. 'context': '.',
  2149. 'args': {
  2150. 'arg1': 'value1',
  2151. 'empty_arg': '',
  2152. 'env_arg': None,
  2153. 'no_env': None
  2154. }
  2155. }
  2156. self.assertEqual(
  2157. resolve_build_args(build, Environment.from_env_file(build['context'])),
  2158. {'arg1': 'value1', 'empty_arg': '', 'env_arg': 'value2', 'no_env': None},
  2159. )
  2160. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2161. @mock.patch.dict(os.environ)
  2162. def test_resolve_path(self):
  2163. os.environ['HOSTENV'] = '/tmp'
  2164. os.environ['CONTAINERENV'] = '/host/tmp'
  2165. service_dict = config.load(
  2166. build_config_details(
  2167. {'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
  2168. "tests/fixtures/env",
  2169. )
  2170. ).services[0]
  2171. self.assertEqual(
  2172. set(service_dict['volumes']),
  2173. set([VolumeSpec.parse('/tmp:/host/tmp')]))
  2174. service_dict = config.load(
  2175. build_config_details(
  2176. {'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
  2177. "tests/fixtures/env",
  2178. )
  2179. ).services[0]
  2180. self.assertEqual(
  2181. set(service_dict['volumes']),
  2182. set([VolumeSpec.parse('/opt/tmp:/opt/host/tmp')]))
  2183. def load_from_filename(filename):
  2184. return config.load(
  2185. config.find('.', [filename], Environment.from_env_file('.'))
  2186. ).services
  2187. class ExtendsTest(unittest.TestCase):
  2188. def test_extends(self):
  2189. service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
  2190. self.assertEqual(service_sort(service_dicts), service_sort([
  2191. {
  2192. 'name': 'mydb',
  2193. 'image': 'busybox',
  2194. 'command': 'top',
  2195. },
  2196. {
  2197. 'name': 'myweb',
  2198. 'image': 'busybox',
  2199. 'command': 'top',
  2200. 'network_mode': 'bridge',
  2201. 'links': ['mydb:db'],
  2202. 'environment': {
  2203. "FOO": "1",
  2204. "BAR": "2",
  2205. "BAZ": "2",
  2206. },
  2207. }
  2208. ]))
  2209. def test_merging_env_labels_ulimits(self):
  2210. service_dicts = load_from_filename('tests/fixtures/extends/common-env-labels-ulimits.yml')
  2211. self.assertEqual(service_sort(service_dicts), service_sort([
  2212. {
  2213. 'name': 'web',
  2214. 'image': 'busybox',
  2215. 'command': '/bin/true',
  2216. 'network_mode': 'host',
  2217. 'environment': {
  2218. "FOO": "2",
  2219. "BAR": "1",
  2220. "BAZ": "3",
  2221. },
  2222. 'labels': {'label': 'one'},
  2223. 'ulimits': {'nproc': 65535, 'memlock': {'soft': 1024, 'hard': 2048}}
  2224. }
  2225. ]))
  2226. def test_nested(self):
  2227. service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
  2228. self.assertEqual(service_dicts, [
  2229. {
  2230. 'name': 'myweb',
  2231. 'image': 'busybox',
  2232. 'command': '/bin/true',
  2233. 'network_mode': 'host',
  2234. 'environment': {
  2235. "FOO": "2",
  2236. "BAR": "2",
  2237. },
  2238. },
  2239. ])
  2240. def test_self_referencing_file(self):
  2241. """
  2242. We specify a 'file' key that is the filename we're already in.
  2243. """
  2244. service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
  2245. self.assertEqual(service_sort(service_dicts), service_sort([
  2246. {
  2247. 'environment':
  2248. {
  2249. 'YEP': '1', 'BAR': '1', 'BAZ': '3'
  2250. },
  2251. 'image': 'busybox',
  2252. 'name': 'myweb'
  2253. },
  2254. {
  2255. 'environment':
  2256. {'YEP': '1'},
  2257. 'image': 'busybox',
  2258. 'name': 'otherweb'
  2259. },
  2260. {
  2261. 'environment':
  2262. {'YEP': '1', 'BAZ': '3'},
  2263. 'image': 'busybox',
  2264. 'name': 'web'
  2265. }
  2266. ]))
  2267. def test_circular(self):
  2268. with pytest.raises(config.CircularReference) as exc:
  2269. load_from_filename('tests/fixtures/extends/circle-1.yml')
  2270. path = [
  2271. (os.path.basename(filename), service_name)
  2272. for (filename, service_name) in exc.value.trail
  2273. ]
  2274. expected = [
  2275. ('circle-1.yml', 'web'),
  2276. ('circle-2.yml', 'other'),
  2277. ('circle-1.yml', 'web'),
  2278. ]
  2279. self.assertEqual(path, expected)
  2280. def test_extends_validation_empty_dictionary(self):
  2281. with pytest.raises(ConfigurationError) as excinfo:
  2282. config.load(
  2283. build_config_details(
  2284. {
  2285. 'web': {'image': 'busybox', 'extends': {}},
  2286. },
  2287. 'tests/fixtures/extends',
  2288. 'filename.yml'
  2289. )
  2290. )
  2291. assert 'service' in excinfo.exconly()
  2292. def test_extends_validation_missing_service_key(self):
  2293. with pytest.raises(ConfigurationError) as excinfo:
  2294. config.load(
  2295. build_config_details(
  2296. {
  2297. 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
  2298. },
  2299. 'tests/fixtures/extends',
  2300. 'filename.yml'
  2301. )
  2302. )
  2303. assert "'service' is a required property" in excinfo.exconly()
  2304. def test_extends_validation_invalid_key(self):
  2305. with pytest.raises(ConfigurationError) as excinfo:
  2306. config.load(
  2307. build_config_details(
  2308. {
  2309. 'web': {
  2310. 'image': 'busybox',
  2311. 'extends': {
  2312. 'file': 'common.yml',
  2313. 'service': 'web',
  2314. 'rogue_key': 'is not allowed'
  2315. }
  2316. },
  2317. },
  2318. 'tests/fixtures/extends',
  2319. 'filename.yml'
  2320. )
  2321. )
  2322. assert "web.extends contains unsupported option: 'rogue_key'" \
  2323. in excinfo.exconly()
  2324. def test_extends_validation_sub_property_key(self):
  2325. with pytest.raises(ConfigurationError) as excinfo:
  2326. config.load(
  2327. build_config_details(
  2328. {
  2329. 'web': {
  2330. 'image': 'busybox',
  2331. 'extends': {
  2332. 'file': 1,
  2333. 'service': 'web',
  2334. }
  2335. },
  2336. },
  2337. 'tests/fixtures/extends',
  2338. 'filename.yml'
  2339. )
  2340. )
  2341. assert "web.extends.file contains 1, which is an invalid type, it should be a string" \
  2342. in excinfo.exconly()
  2343. def test_extends_validation_no_file_key_no_filename_set(self):
  2344. dictionary = {'extends': {'service': 'web'}}
  2345. with pytest.raises(ConfigurationError) as excinfo:
  2346. make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
  2347. assert 'file' in excinfo.exconly()
  2348. def test_extends_validation_valid_config(self):
  2349. service = config.load(
  2350. build_config_details(
  2351. {
  2352. 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
  2353. },
  2354. 'tests/fixtures/extends',
  2355. 'common.yml'
  2356. )
  2357. ).services
  2358. self.assertEquals(len(service), 1)
  2359. self.assertIsInstance(service[0], dict)
  2360. self.assertEquals(service[0]['command'], "/bin/true")
  2361. def test_extended_service_with_invalid_config(self):
  2362. with pytest.raises(ConfigurationError) as exc:
  2363. load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
  2364. assert (
  2365. "myweb has neither an image nor a build context specified" in
  2366. exc.exconly()
  2367. )
  2368. def test_extended_service_with_valid_config(self):
  2369. service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
  2370. self.assertEquals(service[0]['command'], "top")
  2371. def test_extends_file_defaults_to_self(self):
  2372. """
  2373. Test not specifying a file in our extends options that the
  2374. config is valid and correctly extends from itself.
  2375. """
  2376. service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
  2377. self.assertEqual(service_sort(service_dicts), service_sort([
  2378. {
  2379. 'name': 'myweb',
  2380. 'image': 'busybox',
  2381. 'environment': {
  2382. "BAR": "1",
  2383. "BAZ": "3",
  2384. }
  2385. },
  2386. {
  2387. 'name': 'web',
  2388. 'image': 'busybox',
  2389. 'environment': {
  2390. "BAZ": "3",
  2391. }
  2392. }
  2393. ]))
  2394. def test_invalid_links_in_extended_service(self):
  2395. with pytest.raises(ConfigurationError) as excinfo:
  2396. load_from_filename('tests/fixtures/extends/invalid-links.yml')
  2397. assert "services with 'links' cannot be extended" in excinfo.exconly()
  2398. def test_invalid_volumes_from_in_extended_service(self):
  2399. with pytest.raises(ConfigurationError) as excinfo:
  2400. load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
  2401. assert "services with 'volumes_from' cannot be extended" in excinfo.exconly()
  2402. def test_invalid_net_in_extended_service(self):
  2403. with pytest.raises(ConfigurationError) as excinfo:
  2404. load_from_filename('tests/fixtures/extends/invalid-net-v2.yml')
  2405. assert 'network_mode: service' in excinfo.exconly()
  2406. assert 'cannot be extended' in excinfo.exconly()
  2407. with pytest.raises(ConfigurationError) as excinfo:
  2408. load_from_filename('tests/fixtures/extends/invalid-net.yml')
  2409. assert 'net: container' in excinfo.exconly()
  2410. assert 'cannot be extended' in excinfo.exconly()
  2411. @mock.patch.dict(os.environ)
  2412. def test_load_config_runs_interpolation_in_extended_service(self):
  2413. os.environ.update(HOSTNAME_VALUE="penguin")
  2414. expected_interpolated_value = "host-penguin"
  2415. service_dicts = load_from_filename(
  2416. 'tests/fixtures/extends/valid-interpolation.yml')
  2417. for service in service_dicts:
  2418. assert service['hostname'] == expected_interpolated_value
  2419. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2420. def test_volume_path(self):
  2421. dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
  2422. paths = [
  2423. VolumeSpec(
  2424. os.path.abspath('tests/fixtures/volume-path/common/foo'),
  2425. '/foo',
  2426. 'rw'),
  2427. VolumeSpec(
  2428. os.path.abspath('tests/fixtures/volume-path/bar'),
  2429. '/bar',
  2430. 'rw')
  2431. ]
  2432. self.assertEqual(set(dicts[0]['volumes']), set(paths))
  2433. def test_parent_build_path_dne(self):
  2434. child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
  2435. self.assertEqual(child, [
  2436. {
  2437. 'name': 'dnechild',
  2438. 'image': 'busybox',
  2439. 'command': '/bin/true',
  2440. 'environment': {
  2441. "FOO": "1",
  2442. "BAR": "2",
  2443. },
  2444. },
  2445. ])
  2446. def test_load_throws_error_when_base_service_does_not_exist(self):
  2447. with pytest.raises(ConfigurationError) as excinfo:
  2448. load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
  2449. assert "Cannot extend service 'foo'" in excinfo.exconly()
  2450. assert "Service not found" in excinfo.exconly()
  2451. def test_partial_service_config_in_extends_is_still_valid(self):
  2452. dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
  2453. self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
  2454. def test_extended_service_with_verbose_and_shorthand_way(self):
  2455. services = load_from_filename('tests/fixtures/extends/verbose-and-shorthand.yml')
  2456. self.assertEqual(service_sort(services), service_sort([
  2457. {
  2458. 'name': 'base',
  2459. 'image': 'busybox',
  2460. 'environment': {'BAR': '1'},
  2461. },
  2462. {
  2463. 'name': 'verbose',
  2464. 'image': 'busybox',
  2465. 'environment': {'BAR': '1', 'FOO': '1'},
  2466. },
  2467. {
  2468. 'name': 'shorthand',
  2469. 'image': 'busybox',
  2470. 'environment': {'BAR': '1', 'FOO': '2'},
  2471. },
  2472. ]))
  2473. @mock.patch.dict(os.environ)
  2474. def test_extends_with_environment_and_env_files(self):
  2475. tmpdir = py.test.ensuretemp('test_extends_with_environment')
  2476. self.addCleanup(tmpdir.remove)
  2477. commondir = tmpdir.mkdir('common')
  2478. commondir.join('base.yml').write("""
  2479. app:
  2480. image: 'example/app'
  2481. env_file:
  2482. - 'envs'
  2483. environment:
  2484. - SECRET
  2485. - TEST_ONE=common
  2486. - TEST_TWO=common
  2487. """)
  2488. tmpdir.join('docker-compose.yml').write("""
  2489. ext:
  2490. extends:
  2491. file: common/base.yml
  2492. service: app
  2493. env_file:
  2494. - 'envs'
  2495. environment:
  2496. - THING
  2497. - TEST_ONE=top
  2498. """)
  2499. commondir.join('envs').write("""
  2500. COMMON_ENV_FILE
  2501. TEST_ONE=common-env-file
  2502. TEST_TWO=common-env-file
  2503. TEST_THREE=common-env-file
  2504. TEST_FOUR=common-env-file
  2505. """)
  2506. tmpdir.join('envs').write("""
  2507. TOP_ENV_FILE
  2508. TEST_ONE=top-env-file
  2509. TEST_TWO=top-env-file
  2510. TEST_THREE=top-env-file
  2511. """)
  2512. expected = [
  2513. {
  2514. 'name': 'ext',
  2515. 'image': 'example/app',
  2516. 'environment': {
  2517. 'SECRET': 'secret',
  2518. 'TOP_ENV_FILE': 'secret',
  2519. 'COMMON_ENV_FILE': 'secret',
  2520. 'THING': 'thing',
  2521. 'TEST_ONE': 'top',
  2522. 'TEST_TWO': 'common',
  2523. 'TEST_THREE': 'top-env-file',
  2524. 'TEST_FOUR': 'common-env-file',
  2525. },
  2526. },
  2527. ]
  2528. os.environ['SECRET'] = 'secret'
  2529. os.environ['THING'] = 'thing'
  2530. os.environ['COMMON_ENV_FILE'] = 'secret'
  2531. os.environ['TOP_ENV_FILE'] = 'secret'
  2532. config = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2533. assert config == expected
  2534. def test_extends_with_mixed_versions_is_error(self):
  2535. tmpdir = py.test.ensuretemp('test_extends_with_mixed_version')
  2536. self.addCleanup(tmpdir.remove)
  2537. tmpdir.join('docker-compose.yml').write("""
  2538. version: "2"
  2539. services:
  2540. web:
  2541. extends:
  2542. file: base.yml
  2543. service: base
  2544. image: busybox
  2545. """)
  2546. tmpdir.join('base.yml').write("""
  2547. base:
  2548. volumes: ['/foo']
  2549. ports: ['3000:3000']
  2550. """)
  2551. with pytest.raises(ConfigurationError) as exc:
  2552. load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2553. assert 'Version mismatch' in exc.exconly()
  2554. def test_extends_with_defined_version_passes(self):
  2555. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2556. self.addCleanup(tmpdir.remove)
  2557. tmpdir.join('docker-compose.yml').write("""
  2558. version: "2"
  2559. services:
  2560. web:
  2561. extends:
  2562. file: base.yml
  2563. service: base
  2564. image: busybox
  2565. """)
  2566. tmpdir.join('base.yml').write("""
  2567. version: "2"
  2568. services:
  2569. base:
  2570. volumes: ['/foo']
  2571. ports: ['3000:3000']
  2572. command: top
  2573. """)
  2574. service = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2575. self.assertEquals(service[0]['command'], "top")
  2576. def test_extends_with_depends_on(self):
  2577. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2578. self.addCleanup(tmpdir.remove)
  2579. tmpdir.join('docker-compose.yml').write("""
  2580. version: "2"
  2581. services:
  2582. base:
  2583. image: example
  2584. web:
  2585. extends: base
  2586. image: busybox
  2587. depends_on: ['other']
  2588. other:
  2589. image: example
  2590. """)
  2591. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2592. assert service_sort(services)[2]['depends_on'] == ['other']
  2593. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2594. class ExpandPathTest(unittest.TestCase):
  2595. working_dir = '/home/user/somedir'
  2596. def test_expand_path_normal(self):
  2597. result = config.expand_path(self.working_dir, 'myfile')
  2598. self.assertEqual(result, self.working_dir + '/' + 'myfile')
  2599. def test_expand_path_absolute(self):
  2600. abs_path = '/home/user/otherdir/somefile'
  2601. result = config.expand_path(self.working_dir, abs_path)
  2602. self.assertEqual(result, abs_path)
  2603. def test_expand_path_with_tilde(self):
  2604. test_path = '~/otherdir/somefile'
  2605. with mock.patch.dict(os.environ):
  2606. os.environ['HOME'] = user_path = '/home/user/'
  2607. result = config.expand_path(self.working_dir, test_path)
  2608. self.assertEqual(result, user_path + 'otherdir/somefile')
  2609. class VolumePathTest(unittest.TestCase):
  2610. def test_split_path_mapping_with_windows_path(self):
  2611. host_path = "c:\\Users\\msamblanet\\Documents\\anvil\\connect\\config"
  2612. windows_volume_path = host_path + ":/opt/connect/config:ro"
  2613. expected_mapping = ("/opt/connect/config:ro", host_path)
  2614. mapping = config.split_path_mapping(windows_volume_path)
  2615. assert mapping == expected_mapping
  2616. def test_split_path_mapping_with_windows_path_in_container(self):
  2617. host_path = 'c:\\Users\\remilia\\data'
  2618. container_path = 'c:\\scarletdevil\\data'
  2619. expected_mapping = (container_path, host_path)
  2620. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  2621. assert mapping == expected_mapping
  2622. def test_split_path_mapping_with_root_mount(self):
  2623. host_path = '/'
  2624. container_path = '/var/hostroot'
  2625. expected_mapping = (container_path, host_path)
  2626. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  2627. assert mapping == expected_mapping
  2628. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2629. class BuildPathTest(unittest.TestCase):
  2630. def setUp(self):
  2631. self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
  2632. def test_nonexistent_path(self):
  2633. with self.assertRaises(ConfigurationError):
  2634. config.load(
  2635. build_config_details(
  2636. {
  2637. 'foo': {'build': 'nonexistent.path'},
  2638. },
  2639. 'working_dir',
  2640. 'filename.yml'
  2641. )
  2642. )
  2643. def test_relative_path(self):
  2644. relative_build_path = '../build-ctx/'
  2645. service_dict = make_service_dict(
  2646. 'relpath',
  2647. {'build': relative_build_path},
  2648. working_dir='tests/fixtures/build-path'
  2649. )
  2650. self.assertEquals(service_dict['build'], self.abs_context_path)
  2651. def test_absolute_path(self):
  2652. service_dict = make_service_dict(
  2653. 'abspath',
  2654. {'build': self.abs_context_path},
  2655. working_dir='tests/fixtures/build-path'
  2656. )
  2657. self.assertEquals(service_dict['build'], self.abs_context_path)
  2658. def test_from_file(self):
  2659. service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
  2660. self.assertEquals(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  2661. def test_valid_url_in_build_path(self):
  2662. valid_urls = [
  2663. 'git://github.com/docker/docker',
  2664. '[email protected]:docker/docker.git',
  2665. '[email protected]:atlassianlabs/atlassian-docker.git',
  2666. 'https://github.com/docker/docker.git',
  2667. 'http://github.com/docker/docker.git',
  2668. 'github.com/docker/docker.git',
  2669. ]
  2670. for valid_url in valid_urls:
  2671. service_dict = config.load(build_config_details({
  2672. 'validurl': {'build': valid_url},
  2673. }, '.', None)).services
  2674. assert service_dict[0]['build'] == {'context': valid_url}
  2675. def test_invalid_url_in_build_path(self):
  2676. invalid_urls = [
  2677. 'example.com/bogus',
  2678. 'ftp://example.com/',
  2679. '/path/does/not/exist',
  2680. ]
  2681. for invalid_url in invalid_urls:
  2682. with pytest.raises(ConfigurationError) as exc:
  2683. config.load(build_config_details({
  2684. 'invalidurl': {'build': invalid_url},
  2685. }, '.', None))
  2686. assert 'build path' in exc.exconly()
  2687. class GetDefaultConfigFilesTestCase(unittest.TestCase):
  2688. files = [
  2689. 'docker-compose.yml',
  2690. 'docker-compose.yaml',
  2691. ]
  2692. def test_get_config_path_default_file_in_basedir(self):
  2693. for index, filename in enumerate(self.files):
  2694. self.assertEqual(
  2695. filename,
  2696. get_config_filename_for_files(self.files[index:]))
  2697. with self.assertRaises(config.ComposeFileNotFound):
  2698. get_config_filename_for_files([])
  2699. def test_get_config_path_default_file_in_parent_dir(self):
  2700. """Test with files placed in the subdir"""
  2701. def get_config_in_subdir(files):
  2702. return get_config_filename_for_files(files, subdir=True)
  2703. for index, filename in enumerate(self.files):
  2704. self.assertEqual(filename, get_config_in_subdir(self.files[index:]))
  2705. with self.assertRaises(config.ComposeFileNotFound):
  2706. get_config_in_subdir([])
  2707. def get_config_filename_for_files(filenames, subdir=None):
  2708. def make_files(dirname, filenames):
  2709. for fname in filenames:
  2710. with open(os.path.join(dirname, fname), 'w') as f:
  2711. f.write('')
  2712. project_dir = tempfile.mkdtemp()
  2713. try:
  2714. make_files(project_dir, filenames)
  2715. if subdir:
  2716. base_dir = tempfile.mkdtemp(dir=project_dir)
  2717. else:
  2718. base_dir = project_dir
  2719. filename, = config.get_default_config_files(base_dir)
  2720. return os.path.basename(filename)
  2721. finally:
  2722. shutil.rmtree(project_dir)