config_test.py 128 KB

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