config_test.py 118 KB

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