config_test.py 116 KB

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