config_test.py 106 KB

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