config_test.py 92 KB

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