config_test.py 106 KB

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