config_test.py 136 KB

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