config_test.py 123 KB

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