config_test.py 125 KB

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