config_test.py 126 KB

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