config_test.py 121 KB

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