config_test.py 125 KB

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