config_test.py 117 KB

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