config_test.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738
  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. 'web': {
  1083. 'image': 'alpine',
  1084. 'tmpfs': '/run',
  1085. }
  1086. }))
  1087. assert actual.services == [
  1088. {
  1089. 'name': 'web',
  1090. 'image': 'alpine',
  1091. 'tmpfs': ['/run'],
  1092. }
  1093. ]
  1094. def test_merge_service_dicts_from_files_with_extends_in_base(self):
  1095. base = {
  1096. 'volumes': ['.:/app'],
  1097. 'extends': {'service': 'app'}
  1098. }
  1099. override = {
  1100. 'image': 'alpine:edge',
  1101. }
  1102. actual = config.merge_service_dicts_from_files(
  1103. base,
  1104. override,
  1105. DEFAULT_VERSION)
  1106. assert actual == {
  1107. 'image': 'alpine:edge',
  1108. 'volumes': ['.:/app'],
  1109. 'extends': {'service': 'app'}
  1110. }
  1111. def test_merge_service_dicts_from_files_with_extends_in_override(self):
  1112. base = {
  1113. 'volumes': ['.:/app'],
  1114. 'extends': {'service': 'app'}
  1115. }
  1116. override = {
  1117. 'image': 'alpine:edge',
  1118. 'extends': {'service': 'foo'}
  1119. }
  1120. actual = config.merge_service_dicts_from_files(
  1121. base,
  1122. override,
  1123. DEFAULT_VERSION)
  1124. assert actual == {
  1125. 'image': 'alpine:edge',
  1126. 'volumes': ['.:/app'],
  1127. 'extends': {'service': 'foo'}
  1128. }
  1129. def test_merge_build_args(self):
  1130. base = {
  1131. 'build': {
  1132. 'context': '.',
  1133. 'args': {
  1134. 'ONE': '1',
  1135. 'TWO': '2',
  1136. },
  1137. }
  1138. }
  1139. override = {
  1140. 'build': {
  1141. 'args': {
  1142. 'TWO': 'dos',
  1143. 'THREE': '3',
  1144. },
  1145. }
  1146. }
  1147. actual = config.merge_service_dicts(
  1148. base,
  1149. override,
  1150. DEFAULT_VERSION)
  1151. assert actual == {
  1152. 'build': {
  1153. 'context': '.',
  1154. 'args': {
  1155. 'ONE': '1',
  1156. 'TWO': 'dos',
  1157. 'THREE': '3',
  1158. },
  1159. }
  1160. }
  1161. def test_merge_logging_v1(self):
  1162. base = {
  1163. 'image': 'alpine:edge',
  1164. 'log_driver': 'something',
  1165. 'log_opt': {'foo': 'three'},
  1166. }
  1167. override = {
  1168. 'image': 'alpine:edge',
  1169. 'command': 'true',
  1170. }
  1171. actual = config.merge_service_dicts(base, override, V1)
  1172. assert actual == {
  1173. 'image': 'alpine:edge',
  1174. 'log_driver': 'something',
  1175. 'log_opt': {'foo': 'three'},
  1176. 'command': 'true',
  1177. }
  1178. def test_external_volume_config(self):
  1179. config_details = build_config_details({
  1180. 'version': '2',
  1181. 'services': {
  1182. 'bogus': {'image': 'busybox'}
  1183. },
  1184. 'volumes': {
  1185. 'ext': {'external': True},
  1186. 'ext2': {'external': {'name': 'aliased'}}
  1187. }
  1188. })
  1189. config_result = config.load(config_details)
  1190. volumes = config_result.volumes
  1191. assert 'ext' in volumes
  1192. assert volumes['ext']['external'] is True
  1193. assert 'ext2' in volumes
  1194. assert volumes['ext2']['external']['name'] == 'aliased'
  1195. def test_external_volume_invalid_config(self):
  1196. config_details = build_config_details({
  1197. 'version': '2',
  1198. 'services': {
  1199. 'bogus': {'image': 'busybox'}
  1200. },
  1201. 'volumes': {
  1202. 'ext': {'external': True, 'driver': 'foo'}
  1203. }
  1204. })
  1205. with pytest.raises(ConfigurationError):
  1206. config.load(config_details)
  1207. def test_depends_on_orders_services(self):
  1208. config_details = build_config_details({
  1209. 'version': '2',
  1210. 'services': {
  1211. 'one': {'image': 'busybox', 'depends_on': ['three', 'two']},
  1212. 'two': {'image': 'busybox', 'depends_on': ['three']},
  1213. 'three': {'image': 'busybox'},
  1214. },
  1215. })
  1216. actual = config.load(config_details)
  1217. assert (
  1218. [service['name'] for service in actual.services] ==
  1219. ['three', 'two', 'one']
  1220. )
  1221. def test_depends_on_unknown_service_errors(self):
  1222. config_details = build_config_details({
  1223. 'version': '2',
  1224. 'services': {
  1225. 'one': {'image': 'busybox', 'depends_on': ['three']},
  1226. },
  1227. })
  1228. with pytest.raises(ConfigurationError) as exc:
  1229. config.load(config_details)
  1230. assert "Service 'one' depends on service 'three'" in exc.exconly()
  1231. def test_load_dockerfile_without_context(self):
  1232. config_details = build_config_details({
  1233. 'version': '2',
  1234. 'services': {
  1235. 'one': {'build': {'dockerfile': 'Dockerfile.foo'}},
  1236. },
  1237. })
  1238. with pytest.raises(ConfigurationError) as exc:
  1239. config.load(config_details)
  1240. assert 'has neither an image nor a build context' in exc.exconly()
  1241. class NetworkModeTest(unittest.TestCase):
  1242. def test_network_mode_standard(self):
  1243. config_data = config.load(build_config_details({
  1244. 'version': '2',
  1245. 'services': {
  1246. 'web': {
  1247. 'image': 'busybox',
  1248. 'command': "top",
  1249. 'network_mode': 'bridge',
  1250. },
  1251. },
  1252. }))
  1253. assert config_data.services[0]['network_mode'] == 'bridge'
  1254. def test_network_mode_standard_v1(self):
  1255. config_data = config.load(build_config_details({
  1256. 'web': {
  1257. 'image': 'busybox',
  1258. 'command': "top",
  1259. 'net': 'bridge',
  1260. },
  1261. }))
  1262. assert config_data.services[0]['network_mode'] == 'bridge'
  1263. assert 'net' not in config_data.services[0]
  1264. def test_network_mode_container(self):
  1265. config_data = config.load(build_config_details({
  1266. 'version': '2',
  1267. 'services': {
  1268. 'web': {
  1269. 'image': 'busybox',
  1270. 'command': "top",
  1271. 'network_mode': 'container:foo',
  1272. },
  1273. },
  1274. }))
  1275. assert config_data.services[0]['network_mode'] == 'container:foo'
  1276. def test_network_mode_container_v1(self):
  1277. config_data = config.load(build_config_details({
  1278. 'web': {
  1279. 'image': 'busybox',
  1280. 'command': "top",
  1281. 'net': 'container:foo',
  1282. },
  1283. }))
  1284. assert config_data.services[0]['network_mode'] == 'container:foo'
  1285. def test_network_mode_service(self):
  1286. config_data = config.load(build_config_details({
  1287. 'version': '2',
  1288. 'services': {
  1289. 'web': {
  1290. 'image': 'busybox',
  1291. 'command': "top",
  1292. 'network_mode': 'service:foo',
  1293. },
  1294. 'foo': {
  1295. 'image': 'busybox',
  1296. 'command': "top",
  1297. },
  1298. },
  1299. }))
  1300. assert config_data.services[1]['network_mode'] == 'service:foo'
  1301. def test_network_mode_service_v1(self):
  1302. config_data = config.load(build_config_details({
  1303. 'web': {
  1304. 'image': 'busybox',
  1305. 'command': "top",
  1306. 'net': 'container:foo',
  1307. },
  1308. 'foo': {
  1309. 'image': 'busybox',
  1310. 'command': "top",
  1311. },
  1312. }))
  1313. assert config_data.services[1]['network_mode'] == 'service:foo'
  1314. def test_network_mode_service_nonexistent(self):
  1315. with pytest.raises(ConfigurationError) as excinfo:
  1316. config.load(build_config_details({
  1317. 'version': '2',
  1318. 'services': {
  1319. 'web': {
  1320. 'image': 'busybox',
  1321. 'command': "top",
  1322. 'network_mode': 'service:foo',
  1323. },
  1324. },
  1325. }))
  1326. assert "service 'foo' which is undefined" in excinfo.exconly()
  1327. def test_network_mode_plus_networks_is_invalid(self):
  1328. with pytest.raises(ConfigurationError) as excinfo:
  1329. config.load(build_config_details({
  1330. 'version': '2',
  1331. 'services': {
  1332. 'web': {
  1333. 'image': 'busybox',
  1334. 'command': "top",
  1335. 'network_mode': 'bridge',
  1336. 'networks': ['front'],
  1337. },
  1338. },
  1339. 'networks': {
  1340. 'front': None,
  1341. }
  1342. }))
  1343. assert "'network_mode' and 'networks' cannot be combined" in excinfo.exconly()
  1344. class PortsTest(unittest.TestCase):
  1345. INVALID_PORTS_TYPES = [
  1346. {"1": "8000"},
  1347. False,
  1348. "8000",
  1349. 8000,
  1350. ]
  1351. NON_UNIQUE_SINGLE_PORTS = [
  1352. ["8000", "8000"],
  1353. ]
  1354. INVALID_PORT_MAPPINGS = [
  1355. ["8000-8001:8000"],
  1356. ]
  1357. VALID_SINGLE_PORTS = [
  1358. ["8000"],
  1359. ["8000/tcp"],
  1360. ["8000", "9000"],
  1361. [8000],
  1362. [8000, 9000],
  1363. ]
  1364. VALID_PORT_MAPPINGS = [
  1365. ["8000:8050"],
  1366. ["49153-49154:3002-3003"],
  1367. ]
  1368. def test_config_invalid_ports_type_validation(self):
  1369. for invalid_ports in self.INVALID_PORTS_TYPES:
  1370. with pytest.raises(ConfigurationError) as exc:
  1371. self.check_config({'ports': invalid_ports})
  1372. assert "contains an invalid type" in exc.value.msg
  1373. def test_config_non_unique_ports_validation(self):
  1374. for invalid_ports in self.NON_UNIQUE_SINGLE_PORTS:
  1375. with pytest.raises(ConfigurationError) as exc:
  1376. self.check_config({'ports': invalid_ports})
  1377. assert "non-unique" in exc.value.msg
  1378. def test_config_invalid_ports_format_validation(self):
  1379. for invalid_ports in self.INVALID_PORT_MAPPINGS:
  1380. with pytest.raises(ConfigurationError) as exc:
  1381. self.check_config({'ports': invalid_ports})
  1382. assert "Port ranges don't match in length" in exc.value.msg
  1383. def test_config_valid_ports_format_validation(self):
  1384. for valid_ports in self.VALID_SINGLE_PORTS + self.VALID_PORT_MAPPINGS:
  1385. self.check_config({'ports': valid_ports})
  1386. def test_config_invalid_expose_type_validation(self):
  1387. for invalid_expose in self.INVALID_PORTS_TYPES:
  1388. with pytest.raises(ConfigurationError) as exc:
  1389. self.check_config({'expose': invalid_expose})
  1390. assert "contains an invalid type" in exc.value.msg
  1391. def test_config_non_unique_expose_validation(self):
  1392. for invalid_expose in self.NON_UNIQUE_SINGLE_PORTS:
  1393. with pytest.raises(ConfigurationError) as exc:
  1394. self.check_config({'expose': invalid_expose})
  1395. assert "non-unique" in exc.value.msg
  1396. def test_config_invalid_expose_format_validation(self):
  1397. # Valid port mappings ARE NOT valid 'expose' entries
  1398. for invalid_expose in self.INVALID_PORT_MAPPINGS + self.VALID_PORT_MAPPINGS:
  1399. with pytest.raises(ConfigurationError) as exc:
  1400. self.check_config({'expose': invalid_expose})
  1401. assert "should be of the format" in exc.value.msg
  1402. def test_config_valid_expose_format_validation(self):
  1403. # Valid single ports ARE valid 'expose' entries
  1404. for valid_expose in self.VALID_SINGLE_PORTS:
  1405. self.check_config({'expose': valid_expose})
  1406. def check_config(self, cfg):
  1407. config.load(
  1408. build_config_details(
  1409. {'web': dict(image='busybox', **cfg)},
  1410. 'working_dir',
  1411. 'filename.yml'
  1412. )
  1413. )
  1414. class InterpolationTest(unittest.TestCase):
  1415. @mock.patch.dict(os.environ)
  1416. def test_config_file_with_environment_variable(self):
  1417. os.environ.update(
  1418. IMAGE="busybox",
  1419. HOST_PORT="80",
  1420. LABEL_VALUE="myvalue",
  1421. )
  1422. service_dicts = config.load(
  1423. config.find('tests/fixtures/environment-interpolation', None),
  1424. ).services
  1425. self.assertEqual(service_dicts, [
  1426. {
  1427. 'name': 'web',
  1428. 'image': 'busybox',
  1429. 'ports': ['80:8000'],
  1430. 'labels': {'mylabel': 'myvalue'},
  1431. 'hostname': 'host-',
  1432. 'command': '${ESCAPED}',
  1433. }
  1434. ])
  1435. @mock.patch.dict(os.environ)
  1436. def test_unset_variable_produces_warning(self):
  1437. os.environ.pop('FOO', None)
  1438. os.environ.pop('BAR', None)
  1439. config_details = build_config_details(
  1440. {
  1441. 'web': {
  1442. 'image': '${FOO}',
  1443. 'command': '${BAR}',
  1444. 'container_name': '${BAR}',
  1445. },
  1446. },
  1447. '.',
  1448. None,
  1449. )
  1450. with mock.patch('compose.config.interpolation.log') as log:
  1451. config.load(config_details)
  1452. self.assertEqual(2, log.warn.call_count)
  1453. warnings = sorted(args[0][0] for args in log.warn.call_args_list)
  1454. self.assertIn('BAR', warnings[0])
  1455. self.assertIn('FOO', warnings[1])
  1456. @mock.patch.dict(os.environ)
  1457. def test_invalid_interpolation(self):
  1458. with self.assertRaises(config.ConfigurationError) as cm:
  1459. config.load(
  1460. build_config_details(
  1461. {'web': {'image': '${'}},
  1462. 'working_dir',
  1463. 'filename.yml'
  1464. )
  1465. )
  1466. self.assertIn('Invalid', cm.exception.msg)
  1467. self.assertIn('for "image" option', cm.exception.msg)
  1468. self.assertIn('in service "web"', cm.exception.msg)
  1469. self.assertIn('"${"', cm.exception.msg)
  1470. def test_empty_environment_key_allowed(self):
  1471. service_dict = config.load(
  1472. build_config_details(
  1473. {
  1474. 'web': {
  1475. 'build': '.',
  1476. 'environment': {
  1477. 'POSTGRES_PASSWORD': ''
  1478. },
  1479. },
  1480. },
  1481. '.',
  1482. None,
  1483. )
  1484. ).services[0]
  1485. self.assertEquals(service_dict['environment']['POSTGRES_PASSWORD'], '')
  1486. class VolumeConfigTest(unittest.TestCase):
  1487. def test_no_binding(self):
  1488. d = make_service_dict('foo', {'build': '.', 'volumes': ['/data']}, working_dir='.')
  1489. self.assertEqual(d['volumes'], ['/data'])
  1490. @mock.patch.dict(os.environ)
  1491. def test_volume_binding_with_environment_variable(self):
  1492. os.environ['VOLUME_PATH'] = '/host/path'
  1493. d = config.load(
  1494. build_config_details(
  1495. {'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
  1496. '.',
  1497. None,
  1498. )
  1499. ).services[0]
  1500. self.assertEqual(d['volumes'], [VolumeSpec.parse('/host/path:/container/path')])
  1501. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1502. @mock.patch.dict(os.environ)
  1503. def test_volume_binding_with_home(self):
  1504. os.environ['HOME'] = '/home/user'
  1505. d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
  1506. self.assertEqual(d['volumes'], ['/home/user:/container/path'])
  1507. def test_name_does_not_expand(self):
  1508. d = make_service_dict('foo', {'build': '.', 'volumes': ['mydatavolume:/data']}, working_dir='.')
  1509. self.assertEqual(d['volumes'], ['mydatavolume:/data'])
  1510. def test_absolute_posix_path_does_not_expand(self):
  1511. d = make_service_dict('foo', {'build': '.', 'volumes': ['/var/lib/data:/data']}, working_dir='.')
  1512. self.assertEqual(d['volumes'], ['/var/lib/data:/data'])
  1513. def test_absolute_windows_path_does_not_expand(self):
  1514. d = make_service_dict('foo', {'build': '.', 'volumes': ['c:\\data:/data']}, working_dir='.')
  1515. self.assertEqual(d['volumes'], ['c:\\data:/data'])
  1516. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1517. def test_relative_path_does_expand_posix(self):
  1518. d = make_service_dict(
  1519. 'foo',
  1520. {'build': '.', 'volumes': ['./data:/data']},
  1521. working_dir='/home/me/myproject')
  1522. self.assertEqual(d['volumes'], ['/home/me/myproject/data:/data'])
  1523. d = make_service_dict(
  1524. 'foo',
  1525. {'build': '.', 'volumes': ['.:/data']},
  1526. working_dir='/home/me/myproject')
  1527. self.assertEqual(d['volumes'], ['/home/me/myproject:/data'])
  1528. d = make_service_dict(
  1529. 'foo',
  1530. {'build': '.', 'volumes': ['../otherproject:/data']},
  1531. working_dir='/home/me/myproject')
  1532. self.assertEqual(d['volumes'], ['/home/me/otherproject:/data'])
  1533. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='windows paths')
  1534. def test_relative_path_does_expand_windows(self):
  1535. d = make_service_dict(
  1536. 'foo',
  1537. {'build': '.', 'volumes': ['./data:/data']},
  1538. working_dir='c:\\Users\\me\\myproject')
  1539. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject\\data:/data'])
  1540. d = make_service_dict(
  1541. 'foo',
  1542. {'build': '.', 'volumes': ['.:/data']},
  1543. working_dir='c:\\Users\\me\\myproject')
  1544. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject:/data'])
  1545. d = make_service_dict(
  1546. 'foo',
  1547. {'build': '.', 'volumes': ['../otherproject:/data']},
  1548. working_dir='c:\\Users\\me\\myproject')
  1549. self.assertEqual(d['volumes'], ['c:\\Users\\me\\otherproject:/data'])
  1550. @mock.patch.dict(os.environ)
  1551. def test_home_directory_with_driver_does_not_expand(self):
  1552. os.environ['NAME'] = 'surprise!'
  1553. d = make_service_dict('foo', {
  1554. 'build': '.',
  1555. 'volumes': ['~:/data'],
  1556. 'volume_driver': 'foodriver',
  1557. }, working_dir='.')
  1558. self.assertEqual(d['volumes'], ['~:/data'])
  1559. def test_volume_path_with_non_ascii_directory(self):
  1560. volume = u'/Füü/data:/data'
  1561. container_path = config.resolve_volume_path(".", volume)
  1562. self.assertEqual(container_path, volume)
  1563. class MergePathMappingTest(object):
  1564. config_name = ""
  1565. def test_empty(self):
  1566. service_dict = config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1567. assert self.config_name not in service_dict
  1568. def test_no_override(self):
  1569. service_dict = config.merge_service_dicts(
  1570. {self.config_name: ['/foo:/code', '/data']},
  1571. {},
  1572. DEFAULT_VERSION)
  1573. assert set(service_dict[self.config_name]) == set(['/foo:/code', '/data'])
  1574. def test_no_base(self):
  1575. service_dict = config.merge_service_dicts(
  1576. {},
  1577. {self.config_name: ['/bar:/code']},
  1578. DEFAULT_VERSION)
  1579. assert set(service_dict[self.config_name]) == set(['/bar:/code'])
  1580. def test_override_explicit_path(self):
  1581. service_dict = config.merge_service_dicts(
  1582. {self.config_name: ['/foo:/code', '/data']},
  1583. {self.config_name: ['/bar:/code']},
  1584. DEFAULT_VERSION)
  1585. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1586. def test_add_explicit_path(self):
  1587. service_dict = config.merge_service_dicts(
  1588. {self.config_name: ['/foo:/code', '/data']},
  1589. {self.config_name: ['/bar:/code', '/quux:/data']},
  1590. DEFAULT_VERSION)
  1591. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/quux:/data'])
  1592. def test_remove_explicit_path(self):
  1593. service_dict = config.merge_service_dicts(
  1594. {self.config_name: ['/foo:/code', '/quux:/data']},
  1595. {self.config_name: ['/bar:/code', '/data']},
  1596. DEFAULT_VERSION)
  1597. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1598. class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
  1599. config_name = 'volumes'
  1600. class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
  1601. config_name = 'devices'
  1602. class BuildOrImageMergeTest(unittest.TestCase):
  1603. def test_merge_build_or_image_no_override(self):
  1604. self.assertEqual(
  1605. config.merge_service_dicts({'build': '.'}, {}, V1),
  1606. {'build': '.'},
  1607. )
  1608. self.assertEqual(
  1609. config.merge_service_dicts({'image': 'redis'}, {}, V1),
  1610. {'image': 'redis'},
  1611. )
  1612. def test_merge_build_or_image_override_with_same(self):
  1613. self.assertEqual(
  1614. config.merge_service_dicts({'build': '.'}, {'build': './web'}, V1),
  1615. {'build': './web'},
  1616. )
  1617. self.assertEqual(
  1618. config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}, V1),
  1619. {'image': 'postgres'},
  1620. )
  1621. def test_merge_build_or_image_override_with_other(self):
  1622. self.assertEqual(
  1623. config.merge_service_dicts({'build': '.'}, {'image': 'redis'}, V1),
  1624. {'image': 'redis'},
  1625. )
  1626. self.assertEqual(
  1627. config.merge_service_dicts({'image': 'redis'}, {'build': '.'}, V1),
  1628. {'build': '.'}
  1629. )
  1630. class MergeListsTest(object):
  1631. config_name = ""
  1632. base_config = []
  1633. override_config = []
  1634. def merged_config(self):
  1635. return set(self.base_config) | set(self.override_config)
  1636. def test_empty(self):
  1637. assert self.config_name not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1638. def test_no_override(self):
  1639. service_dict = config.merge_service_dicts(
  1640. {self.config_name: self.base_config},
  1641. {},
  1642. DEFAULT_VERSION)
  1643. assert set(service_dict[self.config_name]) == set(self.base_config)
  1644. def test_no_base(self):
  1645. service_dict = config.merge_service_dicts(
  1646. {},
  1647. {self.config_name: self.base_config},
  1648. DEFAULT_VERSION)
  1649. assert set(service_dict[self.config_name]) == set(self.base_config)
  1650. def test_add_item(self):
  1651. service_dict = config.merge_service_dicts(
  1652. {self.config_name: self.base_config},
  1653. {self.config_name: self.override_config},
  1654. DEFAULT_VERSION)
  1655. assert set(service_dict[self.config_name]) == set(self.merged_config())
  1656. class MergePortsTest(unittest.TestCase, MergeListsTest):
  1657. config_name = 'ports'
  1658. base_config = ['10:8000', '9000']
  1659. override_config = ['20:8000']
  1660. class MergeNetworksTest(unittest.TestCase, MergeListsTest):
  1661. config_name = 'networks'
  1662. base_config = ['frontend', 'backend']
  1663. override_config = ['monitoring']
  1664. class MergeStringsOrListsTest(unittest.TestCase):
  1665. def test_no_override(self):
  1666. service_dict = config.merge_service_dicts(
  1667. {'dns': '8.8.8.8'},
  1668. {},
  1669. DEFAULT_VERSION)
  1670. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1671. def test_no_base(self):
  1672. service_dict = config.merge_service_dicts(
  1673. {},
  1674. {'dns': '8.8.8.8'},
  1675. DEFAULT_VERSION)
  1676. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1677. def test_add_string(self):
  1678. service_dict = config.merge_service_dicts(
  1679. {'dns': ['8.8.8.8']},
  1680. {'dns': '9.9.9.9'},
  1681. DEFAULT_VERSION)
  1682. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1683. def test_add_list(self):
  1684. service_dict = config.merge_service_dicts(
  1685. {'dns': '8.8.8.8'},
  1686. {'dns': ['9.9.9.9']},
  1687. DEFAULT_VERSION)
  1688. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1689. class MergeLabelsTest(unittest.TestCase):
  1690. def test_empty(self):
  1691. assert 'labels' not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1692. def test_no_override(self):
  1693. service_dict = config.merge_service_dicts(
  1694. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1695. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1696. DEFAULT_VERSION)
  1697. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1698. def test_no_base(self):
  1699. service_dict = config.merge_service_dicts(
  1700. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1701. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1702. DEFAULT_VERSION)
  1703. assert service_dict['labels'] == {'foo': '2'}
  1704. def test_override_explicit_value(self):
  1705. service_dict = config.merge_service_dicts(
  1706. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1707. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1708. DEFAULT_VERSION)
  1709. assert service_dict['labels'] == {'foo': '2', 'bar': ''}
  1710. def test_add_explicit_value(self):
  1711. service_dict = config.merge_service_dicts(
  1712. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1713. make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
  1714. DEFAULT_VERSION)
  1715. assert service_dict['labels'] == {'foo': '1', 'bar': '2'}
  1716. def test_remove_explicit_value(self):
  1717. service_dict = config.merge_service_dicts(
  1718. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
  1719. make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
  1720. DEFAULT_VERSION)
  1721. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1722. class MemoryOptionsTest(unittest.TestCase):
  1723. def test_validation_fails_with_just_memswap_limit(self):
  1724. """
  1725. When you set a 'memswap_limit' it is invalid config unless you also set
  1726. a mem_limit
  1727. """
  1728. with pytest.raises(ConfigurationError) as excinfo:
  1729. config.load(
  1730. build_config_details(
  1731. {
  1732. 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
  1733. },
  1734. 'tests/fixtures/extends',
  1735. 'filename.yml'
  1736. )
  1737. )
  1738. assert "foo.memswap_limit is invalid: when defining " \
  1739. "'memswap_limit' you must set 'mem_limit' as well" \
  1740. in excinfo.exconly()
  1741. def test_validation_with_correct_memswap_values(self):
  1742. service_dict = config.load(
  1743. build_config_details(
  1744. {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
  1745. 'tests/fixtures/extends',
  1746. 'common.yml'
  1747. )
  1748. ).services
  1749. self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
  1750. def test_memswap_can_be_a_string(self):
  1751. service_dict = config.load(
  1752. build_config_details(
  1753. {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
  1754. 'tests/fixtures/extends',
  1755. 'common.yml'
  1756. )
  1757. ).services
  1758. self.assertEqual(service_dict[0]['memswap_limit'], "512M")
  1759. class EnvTest(unittest.TestCase):
  1760. def test_parse_environment_as_list(self):
  1761. environment = [
  1762. 'NORMAL=F1',
  1763. 'CONTAINS_EQUALS=F=2',
  1764. 'TRAILING_EQUALS=',
  1765. ]
  1766. self.assertEqual(
  1767. config.parse_environment(environment),
  1768. {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
  1769. )
  1770. def test_parse_environment_as_dict(self):
  1771. environment = {
  1772. 'NORMAL': 'F1',
  1773. 'CONTAINS_EQUALS': 'F=2',
  1774. 'TRAILING_EQUALS': None,
  1775. }
  1776. self.assertEqual(config.parse_environment(environment), environment)
  1777. def test_parse_environment_invalid(self):
  1778. with self.assertRaises(ConfigurationError):
  1779. config.parse_environment('a=b')
  1780. def test_parse_environment_empty(self):
  1781. self.assertEqual(config.parse_environment(None), {})
  1782. @mock.patch.dict(os.environ)
  1783. def test_resolve_environment(self):
  1784. os.environ['FILE_DEF'] = 'E1'
  1785. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1786. os.environ['ENV_DEF'] = 'E3'
  1787. service_dict = {
  1788. 'build': '.',
  1789. 'environment': {
  1790. 'FILE_DEF': 'F1',
  1791. 'FILE_DEF_EMPTY': '',
  1792. 'ENV_DEF': None,
  1793. 'NO_DEF': None
  1794. },
  1795. }
  1796. self.assertEqual(
  1797. resolve_environment(service_dict),
  1798. {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None},
  1799. )
  1800. def test_resolve_environment_from_env_file(self):
  1801. self.assertEqual(
  1802. resolve_environment({'env_file': ['tests/fixtures/env/one.env']}),
  1803. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
  1804. )
  1805. def test_resolve_environment_with_multiple_env_files(self):
  1806. service_dict = {
  1807. 'env_file': [
  1808. 'tests/fixtures/env/one.env',
  1809. 'tests/fixtures/env/two.env'
  1810. ]
  1811. }
  1812. self.assertEqual(
  1813. resolve_environment(service_dict),
  1814. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
  1815. )
  1816. def test_resolve_environment_nonexistent_file(self):
  1817. with pytest.raises(ConfigurationError) as exc:
  1818. config.load(build_config_details(
  1819. {'foo': {'image': 'example', 'env_file': 'nonexistent.env'}},
  1820. working_dir='tests/fixtures/env'))
  1821. assert 'Couldn\'t find env file' in exc.exconly()
  1822. assert 'nonexistent.env' in exc.exconly()
  1823. @mock.patch.dict(os.environ)
  1824. def test_resolve_environment_from_env_file_with_empty_values(self):
  1825. os.environ['FILE_DEF'] = 'E1'
  1826. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1827. os.environ['ENV_DEF'] = 'E3'
  1828. self.assertEqual(
  1829. resolve_environment({'env_file': ['tests/fixtures/env/resolve.env']}),
  1830. {
  1831. 'FILE_DEF': u'bär',
  1832. 'FILE_DEF_EMPTY': '',
  1833. 'ENV_DEF': 'E3',
  1834. 'NO_DEF': None
  1835. },
  1836. )
  1837. @mock.patch.dict(os.environ)
  1838. def test_resolve_build_args(self):
  1839. os.environ['env_arg'] = 'value2'
  1840. build = {
  1841. 'context': '.',
  1842. 'args': {
  1843. 'arg1': 'value1',
  1844. 'empty_arg': '',
  1845. 'env_arg': None,
  1846. 'no_env': None
  1847. }
  1848. }
  1849. self.assertEqual(
  1850. resolve_build_args(build),
  1851. {'arg1': 'value1', 'empty_arg': '', 'env_arg': 'value2', 'no_env': None},
  1852. )
  1853. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  1854. @mock.patch.dict(os.environ)
  1855. def test_resolve_path(self):
  1856. os.environ['HOSTENV'] = '/tmp'
  1857. os.environ['CONTAINERENV'] = '/host/tmp'
  1858. service_dict = config.load(
  1859. build_config_details(
  1860. {'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
  1861. "tests/fixtures/env",
  1862. )
  1863. ).services[0]
  1864. self.assertEqual(
  1865. set(service_dict['volumes']),
  1866. set([VolumeSpec.parse('/tmp:/host/tmp')]))
  1867. service_dict = config.load(
  1868. build_config_details(
  1869. {'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
  1870. "tests/fixtures/env",
  1871. )
  1872. ).services[0]
  1873. self.assertEqual(
  1874. set(service_dict['volumes']),
  1875. set([VolumeSpec.parse('/opt/tmp:/opt/host/tmp')]))
  1876. def load_from_filename(filename):
  1877. return config.load(config.find('.', [filename])).services
  1878. class ExtendsTest(unittest.TestCase):
  1879. def test_extends(self):
  1880. service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
  1881. self.assertEqual(service_sort(service_dicts), service_sort([
  1882. {
  1883. 'name': 'mydb',
  1884. 'image': 'busybox',
  1885. 'command': 'top',
  1886. },
  1887. {
  1888. 'name': 'myweb',
  1889. 'image': 'busybox',
  1890. 'command': 'top',
  1891. 'network_mode': 'bridge',
  1892. 'links': ['mydb:db'],
  1893. 'environment': {
  1894. "FOO": "1",
  1895. "BAR": "2",
  1896. "BAZ": "2",
  1897. },
  1898. }
  1899. ]))
  1900. def test_merging_env_labels_ulimits(self):
  1901. service_dicts = load_from_filename('tests/fixtures/extends/common-env-labels-ulimits.yml')
  1902. self.assertEqual(service_sort(service_dicts), service_sort([
  1903. {
  1904. 'name': 'web',
  1905. 'image': 'busybox',
  1906. 'command': '/bin/true',
  1907. 'network_mode': 'host',
  1908. 'environment': {
  1909. "FOO": "2",
  1910. "BAR": "1",
  1911. "BAZ": "3",
  1912. },
  1913. 'labels': {'label': 'one'},
  1914. 'ulimits': {'nproc': 65535, 'memlock': {'soft': 1024, 'hard': 2048}}
  1915. }
  1916. ]))
  1917. def test_nested(self):
  1918. service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
  1919. self.assertEqual(service_dicts, [
  1920. {
  1921. 'name': 'myweb',
  1922. 'image': 'busybox',
  1923. 'command': '/bin/true',
  1924. 'network_mode': 'host',
  1925. 'environment': {
  1926. "FOO": "2",
  1927. "BAR": "2",
  1928. },
  1929. },
  1930. ])
  1931. def test_self_referencing_file(self):
  1932. """
  1933. We specify a 'file' key that is the filename we're already in.
  1934. """
  1935. service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
  1936. self.assertEqual(service_sort(service_dicts), service_sort([
  1937. {
  1938. 'environment':
  1939. {
  1940. 'YEP': '1', 'BAR': '1', 'BAZ': '3'
  1941. },
  1942. 'image': 'busybox',
  1943. 'name': 'myweb'
  1944. },
  1945. {
  1946. 'environment':
  1947. {'YEP': '1'},
  1948. 'image': 'busybox',
  1949. 'name': 'otherweb'
  1950. },
  1951. {
  1952. 'environment':
  1953. {'YEP': '1', 'BAZ': '3'},
  1954. 'image': 'busybox',
  1955. 'name': 'web'
  1956. }
  1957. ]))
  1958. def test_circular(self):
  1959. with pytest.raises(config.CircularReference) as exc:
  1960. load_from_filename('tests/fixtures/extends/circle-1.yml')
  1961. path = [
  1962. (os.path.basename(filename), service_name)
  1963. for (filename, service_name) in exc.value.trail
  1964. ]
  1965. expected = [
  1966. ('circle-1.yml', 'web'),
  1967. ('circle-2.yml', 'other'),
  1968. ('circle-1.yml', 'web'),
  1969. ]
  1970. self.assertEqual(path, expected)
  1971. def test_extends_validation_empty_dictionary(self):
  1972. with pytest.raises(ConfigurationError) as excinfo:
  1973. config.load(
  1974. build_config_details(
  1975. {
  1976. 'web': {'image': 'busybox', 'extends': {}},
  1977. },
  1978. 'tests/fixtures/extends',
  1979. 'filename.yml'
  1980. )
  1981. )
  1982. assert 'service' in excinfo.exconly()
  1983. def test_extends_validation_missing_service_key(self):
  1984. with pytest.raises(ConfigurationError) as excinfo:
  1985. config.load(
  1986. build_config_details(
  1987. {
  1988. 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
  1989. },
  1990. 'tests/fixtures/extends',
  1991. 'filename.yml'
  1992. )
  1993. )
  1994. assert "'service' is a required property" in excinfo.exconly()
  1995. def test_extends_validation_invalid_key(self):
  1996. with pytest.raises(ConfigurationError) as excinfo:
  1997. config.load(
  1998. build_config_details(
  1999. {
  2000. 'web': {
  2001. 'image': 'busybox',
  2002. 'extends': {
  2003. 'file': 'common.yml',
  2004. 'service': 'web',
  2005. 'rogue_key': 'is not allowed'
  2006. }
  2007. },
  2008. },
  2009. 'tests/fixtures/extends',
  2010. 'filename.yml'
  2011. )
  2012. )
  2013. assert "web.extends contains unsupported option: 'rogue_key'" \
  2014. in excinfo.exconly()
  2015. def test_extends_validation_sub_property_key(self):
  2016. with pytest.raises(ConfigurationError) as excinfo:
  2017. config.load(
  2018. build_config_details(
  2019. {
  2020. 'web': {
  2021. 'image': 'busybox',
  2022. 'extends': {
  2023. 'file': 1,
  2024. 'service': 'web',
  2025. }
  2026. },
  2027. },
  2028. 'tests/fixtures/extends',
  2029. 'filename.yml'
  2030. )
  2031. )
  2032. assert "web.extends.file contains 1, which is an invalid type, it should be a string" \
  2033. in excinfo.exconly()
  2034. def test_extends_validation_no_file_key_no_filename_set(self):
  2035. dictionary = {'extends': {'service': 'web'}}
  2036. with pytest.raises(ConfigurationError) as excinfo:
  2037. make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
  2038. assert 'file' in excinfo.exconly()
  2039. def test_extends_validation_valid_config(self):
  2040. service = config.load(
  2041. build_config_details(
  2042. {
  2043. 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
  2044. },
  2045. 'tests/fixtures/extends',
  2046. 'common.yml'
  2047. )
  2048. ).services
  2049. self.assertEquals(len(service), 1)
  2050. self.assertIsInstance(service[0], dict)
  2051. self.assertEquals(service[0]['command'], "/bin/true")
  2052. def test_extended_service_with_invalid_config(self):
  2053. with pytest.raises(ConfigurationError) as exc:
  2054. load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
  2055. assert (
  2056. "myweb has neither an image nor a build context specified" in
  2057. exc.exconly()
  2058. )
  2059. def test_extended_service_with_valid_config(self):
  2060. service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
  2061. self.assertEquals(service[0]['command'], "top")
  2062. def test_extends_file_defaults_to_self(self):
  2063. """
  2064. Test not specifying a file in our extends options that the
  2065. config is valid and correctly extends from itself.
  2066. """
  2067. service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
  2068. self.assertEqual(service_sort(service_dicts), service_sort([
  2069. {
  2070. 'name': 'myweb',
  2071. 'image': 'busybox',
  2072. 'environment': {
  2073. "BAR": "1",
  2074. "BAZ": "3",
  2075. }
  2076. },
  2077. {
  2078. 'name': 'web',
  2079. 'image': 'busybox',
  2080. 'environment': {
  2081. "BAZ": "3",
  2082. }
  2083. }
  2084. ]))
  2085. def test_invalid_links_in_extended_service(self):
  2086. with pytest.raises(ConfigurationError) as excinfo:
  2087. load_from_filename('tests/fixtures/extends/invalid-links.yml')
  2088. assert "services with 'links' cannot be extended" in excinfo.exconly()
  2089. def test_invalid_volumes_from_in_extended_service(self):
  2090. with pytest.raises(ConfigurationError) as excinfo:
  2091. load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
  2092. assert "services with 'volumes_from' cannot be extended" in excinfo.exconly()
  2093. def test_invalid_net_in_extended_service(self):
  2094. with pytest.raises(ConfigurationError) as excinfo:
  2095. load_from_filename('tests/fixtures/extends/invalid-net-v2.yml')
  2096. assert 'network_mode: service' in excinfo.exconly()
  2097. assert 'cannot be extended' in excinfo.exconly()
  2098. with pytest.raises(ConfigurationError) as excinfo:
  2099. load_from_filename('tests/fixtures/extends/invalid-net.yml')
  2100. assert 'net: container' in excinfo.exconly()
  2101. assert 'cannot be extended' in excinfo.exconly()
  2102. @mock.patch.dict(os.environ)
  2103. def test_load_config_runs_interpolation_in_extended_service(self):
  2104. os.environ.update(HOSTNAME_VALUE="penguin")
  2105. expected_interpolated_value = "host-penguin"
  2106. service_dicts = load_from_filename(
  2107. 'tests/fixtures/extends/valid-interpolation.yml')
  2108. for service in service_dicts:
  2109. assert service['hostname'] == expected_interpolated_value
  2110. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2111. def test_volume_path(self):
  2112. dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
  2113. paths = [
  2114. VolumeSpec(
  2115. os.path.abspath('tests/fixtures/volume-path/common/foo'),
  2116. '/foo',
  2117. 'rw'),
  2118. VolumeSpec(
  2119. os.path.abspath('tests/fixtures/volume-path/bar'),
  2120. '/bar',
  2121. 'rw')
  2122. ]
  2123. self.assertEqual(set(dicts[0]['volumes']), set(paths))
  2124. def test_parent_build_path_dne(self):
  2125. child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
  2126. self.assertEqual(child, [
  2127. {
  2128. 'name': 'dnechild',
  2129. 'image': 'busybox',
  2130. 'command': '/bin/true',
  2131. 'environment': {
  2132. "FOO": "1",
  2133. "BAR": "2",
  2134. },
  2135. },
  2136. ])
  2137. def test_load_throws_error_when_base_service_does_not_exist(self):
  2138. with pytest.raises(ConfigurationError) as excinfo:
  2139. load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
  2140. assert "Cannot extend service 'foo'" in excinfo.exconly()
  2141. assert "Service not found" in excinfo.exconly()
  2142. def test_partial_service_config_in_extends_is_still_valid(self):
  2143. dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
  2144. self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
  2145. def test_extended_service_with_verbose_and_shorthand_way(self):
  2146. services = load_from_filename('tests/fixtures/extends/verbose-and-shorthand.yml')
  2147. self.assertEqual(service_sort(services), service_sort([
  2148. {
  2149. 'name': 'base',
  2150. 'image': 'busybox',
  2151. 'environment': {'BAR': '1'},
  2152. },
  2153. {
  2154. 'name': 'verbose',
  2155. 'image': 'busybox',
  2156. 'environment': {'BAR': '1', 'FOO': '1'},
  2157. },
  2158. {
  2159. 'name': 'shorthand',
  2160. 'image': 'busybox',
  2161. 'environment': {'BAR': '1', 'FOO': '2'},
  2162. },
  2163. ]))
  2164. def test_extends_with_environment_and_env_files(self):
  2165. tmpdir = py.test.ensuretemp('test_extends_with_environment')
  2166. self.addCleanup(tmpdir.remove)
  2167. commondir = tmpdir.mkdir('common')
  2168. commondir.join('base.yml').write("""
  2169. app:
  2170. image: 'example/app'
  2171. env_file:
  2172. - 'envs'
  2173. environment:
  2174. - SECRET
  2175. - TEST_ONE=common
  2176. - TEST_TWO=common
  2177. """)
  2178. tmpdir.join('docker-compose.yml').write("""
  2179. ext:
  2180. extends:
  2181. file: common/base.yml
  2182. service: app
  2183. env_file:
  2184. - 'envs'
  2185. environment:
  2186. - THING
  2187. - TEST_ONE=top
  2188. """)
  2189. commondir.join('envs').write("""
  2190. COMMON_ENV_FILE
  2191. TEST_ONE=common-env-file
  2192. TEST_TWO=common-env-file
  2193. TEST_THREE=common-env-file
  2194. TEST_FOUR=common-env-file
  2195. """)
  2196. tmpdir.join('envs').write("""
  2197. TOP_ENV_FILE
  2198. TEST_ONE=top-env-file
  2199. TEST_TWO=top-env-file
  2200. TEST_THREE=top-env-file
  2201. """)
  2202. expected = [
  2203. {
  2204. 'name': 'ext',
  2205. 'image': 'example/app',
  2206. 'environment': {
  2207. 'SECRET': 'secret',
  2208. 'TOP_ENV_FILE': 'secret',
  2209. 'COMMON_ENV_FILE': 'secret',
  2210. 'THING': 'thing',
  2211. 'TEST_ONE': 'top',
  2212. 'TEST_TWO': 'common',
  2213. 'TEST_THREE': 'top-env-file',
  2214. 'TEST_FOUR': 'common-env-file',
  2215. },
  2216. },
  2217. ]
  2218. with mock.patch.dict(os.environ):
  2219. os.environ['SECRET'] = 'secret'
  2220. os.environ['THING'] = 'thing'
  2221. os.environ['COMMON_ENV_FILE'] = 'secret'
  2222. os.environ['TOP_ENV_FILE'] = 'secret'
  2223. config = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2224. assert config == expected
  2225. def test_extends_with_mixed_versions_is_error(self):
  2226. tmpdir = py.test.ensuretemp('test_extends_with_mixed_version')
  2227. self.addCleanup(tmpdir.remove)
  2228. tmpdir.join('docker-compose.yml').write("""
  2229. version: "2"
  2230. services:
  2231. web:
  2232. extends:
  2233. file: base.yml
  2234. service: base
  2235. image: busybox
  2236. """)
  2237. tmpdir.join('base.yml').write("""
  2238. base:
  2239. volumes: ['/foo']
  2240. ports: ['3000:3000']
  2241. """)
  2242. with pytest.raises(ConfigurationError) as exc:
  2243. load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2244. assert 'Version mismatch' in exc.exconly()
  2245. def test_extends_with_defined_version_passes(self):
  2246. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2247. self.addCleanup(tmpdir.remove)
  2248. tmpdir.join('docker-compose.yml').write("""
  2249. version: "2"
  2250. services:
  2251. web:
  2252. extends:
  2253. file: base.yml
  2254. service: base
  2255. image: busybox
  2256. """)
  2257. tmpdir.join('base.yml').write("""
  2258. version: "2"
  2259. services:
  2260. base:
  2261. volumes: ['/foo']
  2262. ports: ['3000:3000']
  2263. command: top
  2264. """)
  2265. service = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2266. self.assertEquals(service[0]['command'], "top")
  2267. def test_extends_with_depends_on(self):
  2268. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2269. self.addCleanup(tmpdir.remove)
  2270. tmpdir.join('docker-compose.yml').write("""
  2271. version: "2"
  2272. services:
  2273. base:
  2274. image: example
  2275. web:
  2276. extends: base
  2277. image: busybox
  2278. depends_on: ['other']
  2279. other:
  2280. image: example
  2281. """)
  2282. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2283. assert service_sort(services)[2]['depends_on'] == ['other']
  2284. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2285. class ExpandPathTest(unittest.TestCase):
  2286. working_dir = '/home/user/somedir'
  2287. def test_expand_path_normal(self):
  2288. result = config.expand_path(self.working_dir, 'myfile')
  2289. self.assertEqual(result, self.working_dir + '/' + 'myfile')
  2290. def test_expand_path_absolute(self):
  2291. abs_path = '/home/user/otherdir/somefile'
  2292. result = config.expand_path(self.working_dir, abs_path)
  2293. self.assertEqual(result, abs_path)
  2294. def test_expand_path_with_tilde(self):
  2295. test_path = '~/otherdir/somefile'
  2296. with mock.patch.dict(os.environ):
  2297. os.environ['HOME'] = user_path = '/home/user/'
  2298. result = config.expand_path(self.working_dir, test_path)
  2299. self.assertEqual(result, user_path + 'otherdir/somefile')
  2300. class VolumePathTest(unittest.TestCase):
  2301. @pytest.mark.xfail((not IS_WINDOWS_PLATFORM), reason='does not have a drive')
  2302. def test_split_path_mapping_with_windows_path(self):
  2303. host_path = "c:\\Users\\msamblanet\\Documents\\anvil\\connect\\config"
  2304. windows_volume_path = host_path + ":/opt/connect/config:ro"
  2305. expected_mapping = ("/opt/connect/config:ro", host_path)
  2306. mapping = config.split_path_mapping(windows_volume_path)
  2307. self.assertEqual(mapping, expected_mapping)
  2308. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2309. class BuildPathTest(unittest.TestCase):
  2310. def setUp(self):
  2311. self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
  2312. def test_nonexistent_path(self):
  2313. with self.assertRaises(ConfigurationError):
  2314. config.load(
  2315. build_config_details(
  2316. {
  2317. 'foo': {'build': 'nonexistent.path'},
  2318. },
  2319. 'working_dir',
  2320. 'filename.yml'
  2321. )
  2322. )
  2323. def test_relative_path(self):
  2324. relative_build_path = '../build-ctx/'
  2325. service_dict = make_service_dict(
  2326. 'relpath',
  2327. {'build': relative_build_path},
  2328. working_dir='tests/fixtures/build-path'
  2329. )
  2330. self.assertEquals(service_dict['build'], self.abs_context_path)
  2331. def test_absolute_path(self):
  2332. service_dict = make_service_dict(
  2333. 'abspath',
  2334. {'build': self.abs_context_path},
  2335. working_dir='tests/fixtures/build-path'
  2336. )
  2337. self.assertEquals(service_dict['build'], self.abs_context_path)
  2338. def test_from_file(self):
  2339. service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
  2340. self.assertEquals(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  2341. def test_valid_url_in_build_path(self):
  2342. valid_urls = [
  2343. 'git://github.com/docker/docker',
  2344. '[email protected]:docker/docker.git',
  2345. '[email protected]:atlassianlabs/atlassian-docker.git',
  2346. 'https://github.com/docker/docker.git',
  2347. 'http://github.com/docker/docker.git',
  2348. 'github.com/docker/docker.git',
  2349. ]
  2350. for valid_url in valid_urls:
  2351. service_dict = config.load(build_config_details({
  2352. 'validurl': {'build': valid_url},
  2353. }, '.', None)).services
  2354. assert service_dict[0]['build'] == {'context': valid_url}
  2355. def test_invalid_url_in_build_path(self):
  2356. invalid_urls = [
  2357. 'example.com/bogus',
  2358. 'ftp://example.com/',
  2359. '/path/does/not/exist',
  2360. ]
  2361. for invalid_url in invalid_urls:
  2362. with pytest.raises(ConfigurationError) as exc:
  2363. config.load(build_config_details({
  2364. 'invalidurl': {'build': invalid_url},
  2365. }, '.', None))
  2366. assert 'build path' in exc.exconly()
  2367. class GetDefaultConfigFilesTestCase(unittest.TestCase):
  2368. files = [
  2369. 'docker-compose.yml',
  2370. 'docker-compose.yaml',
  2371. ]
  2372. def test_get_config_path_default_file_in_basedir(self):
  2373. for index, filename in enumerate(self.files):
  2374. self.assertEqual(
  2375. filename,
  2376. get_config_filename_for_files(self.files[index:]))
  2377. with self.assertRaises(config.ComposeFileNotFound):
  2378. get_config_filename_for_files([])
  2379. def test_get_config_path_default_file_in_parent_dir(self):
  2380. """Test with files placed in the subdir"""
  2381. def get_config_in_subdir(files):
  2382. return get_config_filename_for_files(files, subdir=True)
  2383. for index, filename in enumerate(self.files):
  2384. self.assertEqual(filename, get_config_in_subdir(self.files[index:]))
  2385. with self.assertRaises(config.ComposeFileNotFound):
  2386. get_config_in_subdir([])
  2387. def get_config_filename_for_files(filenames, subdir=None):
  2388. def make_files(dirname, filenames):
  2389. for fname in filenames:
  2390. with open(os.path.join(dirname, fname), 'w') as f:
  2391. f.write('')
  2392. project_dir = tempfile.mkdtemp()
  2393. try:
  2394. make_files(project_dir, filenames)
  2395. if subdir:
  2396. base_dir = tempfile.mkdtemp(dir=project_dir)
  2397. else:
  2398. base_dir = project_dir
  2399. filename, = config.get_default_config_files(base_dir)
  2400. return os.path.basename(filename)
  2401. finally:
  2402. shutil.rmtree(project_dir)