config_test.py 103 KB

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