config_test.py 95 KB

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