config_test.py 110 KB

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