config_test.py 120 KB

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