config_test.py 97 KB

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