config_test.py 107 KB

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