config_test.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859
  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_merge_service_dicts_from_files_with_extends_in_base(self):
  1153. base = {
  1154. 'volumes': ['.:/app'],
  1155. 'extends': {'service': 'app'}
  1156. }
  1157. override = {
  1158. 'image': 'alpine:edge',
  1159. }
  1160. actual = config.merge_service_dicts_from_files(
  1161. base,
  1162. override,
  1163. DEFAULT_VERSION)
  1164. assert actual == {
  1165. 'image': 'alpine:edge',
  1166. 'volumes': ['.:/app'],
  1167. 'extends': {'service': 'app'}
  1168. }
  1169. def test_merge_service_dicts_from_files_with_extends_in_override(self):
  1170. base = {
  1171. 'volumes': ['.:/app'],
  1172. 'extends': {'service': 'app'}
  1173. }
  1174. override = {
  1175. 'image': 'alpine:edge',
  1176. 'extends': {'service': 'foo'}
  1177. }
  1178. actual = config.merge_service_dicts_from_files(
  1179. base,
  1180. override,
  1181. DEFAULT_VERSION)
  1182. assert actual == {
  1183. 'image': 'alpine:edge',
  1184. 'volumes': ['.:/app'],
  1185. 'extends': {'service': 'foo'}
  1186. }
  1187. def test_merge_build_args(self):
  1188. base = {
  1189. 'build': {
  1190. 'context': '.',
  1191. 'args': {
  1192. 'ONE': '1',
  1193. 'TWO': '2',
  1194. },
  1195. }
  1196. }
  1197. override = {
  1198. 'build': {
  1199. 'args': {
  1200. 'TWO': 'dos',
  1201. 'THREE': '3',
  1202. },
  1203. }
  1204. }
  1205. actual = config.merge_service_dicts(
  1206. base,
  1207. override,
  1208. DEFAULT_VERSION)
  1209. assert actual == {
  1210. 'build': {
  1211. 'context': '.',
  1212. 'args': {
  1213. 'ONE': '1',
  1214. 'TWO': 'dos',
  1215. 'THREE': '3',
  1216. },
  1217. }
  1218. }
  1219. def test_merge_logging_v1(self):
  1220. base = {
  1221. 'image': 'alpine:edge',
  1222. 'log_driver': 'something',
  1223. 'log_opt': {'foo': 'three'},
  1224. }
  1225. override = {
  1226. 'image': 'alpine:edge',
  1227. 'command': 'true',
  1228. }
  1229. actual = config.merge_service_dicts(base, override, V1)
  1230. assert actual == {
  1231. 'image': 'alpine:edge',
  1232. 'log_driver': 'something',
  1233. 'log_opt': {'foo': 'three'},
  1234. 'command': 'true',
  1235. }
  1236. def test_external_volume_config(self):
  1237. config_details = build_config_details({
  1238. 'version': '2',
  1239. 'services': {
  1240. 'bogus': {'image': 'busybox'}
  1241. },
  1242. 'volumes': {
  1243. 'ext': {'external': True},
  1244. 'ext2': {'external': {'name': 'aliased'}}
  1245. }
  1246. })
  1247. config_result = config.load(config_details)
  1248. volumes = config_result.volumes
  1249. assert 'ext' in volumes
  1250. assert volumes['ext']['external'] is True
  1251. assert 'ext2' in volumes
  1252. assert volumes['ext2']['external']['name'] == 'aliased'
  1253. def test_external_volume_invalid_config(self):
  1254. config_details = build_config_details({
  1255. 'version': '2',
  1256. 'services': {
  1257. 'bogus': {'image': 'busybox'}
  1258. },
  1259. 'volumes': {
  1260. 'ext': {'external': True, 'driver': 'foo'}
  1261. }
  1262. })
  1263. with pytest.raises(ConfigurationError):
  1264. config.load(config_details)
  1265. def test_depends_on_orders_services(self):
  1266. config_details = build_config_details({
  1267. 'version': '2',
  1268. 'services': {
  1269. 'one': {'image': 'busybox', 'depends_on': ['three', 'two']},
  1270. 'two': {'image': 'busybox', 'depends_on': ['three']},
  1271. 'three': {'image': 'busybox'},
  1272. },
  1273. })
  1274. actual = config.load(config_details)
  1275. assert (
  1276. [service['name'] for service in actual.services] ==
  1277. ['three', 'two', 'one']
  1278. )
  1279. def test_depends_on_unknown_service_errors(self):
  1280. config_details = build_config_details({
  1281. 'version': '2',
  1282. 'services': {
  1283. 'one': {'image': 'busybox', 'depends_on': ['three']},
  1284. },
  1285. })
  1286. with pytest.raises(ConfigurationError) as exc:
  1287. config.load(config_details)
  1288. assert "Service 'one' depends on service 'three'" in exc.exconly()
  1289. def test_linked_service_is_undefined(self):
  1290. with self.assertRaises(ConfigurationError):
  1291. config.load(
  1292. build_config_details({
  1293. 'version': '2',
  1294. 'services': {
  1295. 'web': {'image': 'busybox', 'links': ['db:db']},
  1296. },
  1297. })
  1298. )
  1299. def test_load_dockerfile_without_context(self):
  1300. config_details = build_config_details({
  1301. 'version': '2',
  1302. 'services': {
  1303. 'one': {'build': {'dockerfile': 'Dockerfile.foo'}},
  1304. },
  1305. })
  1306. with pytest.raises(ConfigurationError) as exc:
  1307. config.load(config_details)
  1308. assert 'has neither an image nor a build context' in exc.exconly()
  1309. class NetworkModeTest(unittest.TestCase):
  1310. def test_network_mode_standard(self):
  1311. config_data = config.load(build_config_details({
  1312. 'version': '2',
  1313. 'services': {
  1314. 'web': {
  1315. 'image': 'busybox',
  1316. 'command': "top",
  1317. 'network_mode': 'bridge',
  1318. },
  1319. },
  1320. }))
  1321. assert config_data.services[0]['network_mode'] == 'bridge'
  1322. def test_network_mode_standard_v1(self):
  1323. config_data = config.load(build_config_details({
  1324. 'web': {
  1325. 'image': 'busybox',
  1326. 'command': "top",
  1327. 'net': 'bridge',
  1328. },
  1329. }))
  1330. assert config_data.services[0]['network_mode'] == 'bridge'
  1331. assert 'net' not in config_data.services[0]
  1332. def test_network_mode_container(self):
  1333. config_data = config.load(build_config_details({
  1334. 'version': '2',
  1335. 'services': {
  1336. 'web': {
  1337. 'image': 'busybox',
  1338. 'command': "top",
  1339. 'network_mode': 'container:foo',
  1340. },
  1341. },
  1342. }))
  1343. assert config_data.services[0]['network_mode'] == 'container:foo'
  1344. def test_network_mode_container_v1(self):
  1345. config_data = config.load(build_config_details({
  1346. 'web': {
  1347. 'image': 'busybox',
  1348. 'command': "top",
  1349. 'net': 'container:foo',
  1350. },
  1351. }))
  1352. assert config_data.services[0]['network_mode'] == 'container:foo'
  1353. def test_network_mode_service(self):
  1354. config_data = config.load(build_config_details({
  1355. 'version': '2',
  1356. 'services': {
  1357. 'web': {
  1358. 'image': 'busybox',
  1359. 'command': "top",
  1360. 'network_mode': 'service:foo',
  1361. },
  1362. 'foo': {
  1363. 'image': 'busybox',
  1364. 'command': "top",
  1365. },
  1366. },
  1367. }))
  1368. assert config_data.services[1]['network_mode'] == 'service:foo'
  1369. def test_network_mode_service_v1(self):
  1370. config_data = config.load(build_config_details({
  1371. 'web': {
  1372. 'image': 'busybox',
  1373. 'command': "top",
  1374. 'net': 'container:foo',
  1375. },
  1376. 'foo': {
  1377. 'image': 'busybox',
  1378. 'command': "top",
  1379. },
  1380. }))
  1381. assert config_data.services[1]['network_mode'] == 'service:foo'
  1382. def test_network_mode_service_nonexistent(self):
  1383. with pytest.raises(ConfigurationError) as excinfo:
  1384. config.load(build_config_details({
  1385. 'version': '2',
  1386. 'services': {
  1387. 'web': {
  1388. 'image': 'busybox',
  1389. 'command': "top",
  1390. 'network_mode': 'service:foo',
  1391. },
  1392. },
  1393. }))
  1394. assert "service 'foo' which is undefined" in excinfo.exconly()
  1395. def test_network_mode_plus_networks_is_invalid(self):
  1396. with pytest.raises(ConfigurationError) as excinfo:
  1397. config.load(build_config_details({
  1398. 'version': '2',
  1399. 'services': {
  1400. 'web': {
  1401. 'image': 'busybox',
  1402. 'command': "top",
  1403. 'network_mode': 'bridge',
  1404. 'networks': ['front'],
  1405. },
  1406. },
  1407. 'networks': {
  1408. 'front': None,
  1409. }
  1410. }))
  1411. assert "'network_mode' and 'networks' cannot be combined" in excinfo.exconly()
  1412. class PortsTest(unittest.TestCase):
  1413. INVALID_PORTS_TYPES = [
  1414. {"1": "8000"},
  1415. False,
  1416. "8000",
  1417. 8000,
  1418. ]
  1419. NON_UNIQUE_SINGLE_PORTS = [
  1420. ["8000", "8000"],
  1421. ]
  1422. INVALID_PORT_MAPPINGS = [
  1423. ["8000-8001:8000"],
  1424. ]
  1425. VALID_SINGLE_PORTS = [
  1426. ["8000"],
  1427. ["8000/tcp"],
  1428. ["8000", "9000"],
  1429. [8000],
  1430. [8000, 9000],
  1431. ]
  1432. VALID_PORT_MAPPINGS = [
  1433. ["8000:8050"],
  1434. ["49153-49154:3002-3003"],
  1435. ]
  1436. def test_config_invalid_ports_type_validation(self):
  1437. for invalid_ports in self.INVALID_PORTS_TYPES:
  1438. with pytest.raises(ConfigurationError) as exc:
  1439. self.check_config({'ports': invalid_ports})
  1440. assert "contains an invalid type" in exc.value.msg
  1441. def test_config_non_unique_ports_validation(self):
  1442. for invalid_ports in self.NON_UNIQUE_SINGLE_PORTS:
  1443. with pytest.raises(ConfigurationError) as exc:
  1444. self.check_config({'ports': invalid_ports})
  1445. assert "non-unique" in exc.value.msg
  1446. def test_config_invalid_ports_format_validation(self):
  1447. for invalid_ports in self.INVALID_PORT_MAPPINGS:
  1448. with pytest.raises(ConfigurationError) as exc:
  1449. self.check_config({'ports': invalid_ports})
  1450. assert "Port ranges don't match in length" in exc.value.msg
  1451. def test_config_valid_ports_format_validation(self):
  1452. for valid_ports in self.VALID_SINGLE_PORTS + self.VALID_PORT_MAPPINGS:
  1453. self.check_config({'ports': valid_ports})
  1454. def test_config_invalid_expose_type_validation(self):
  1455. for invalid_expose in self.INVALID_PORTS_TYPES:
  1456. with pytest.raises(ConfigurationError) as exc:
  1457. self.check_config({'expose': invalid_expose})
  1458. assert "contains an invalid type" in exc.value.msg
  1459. def test_config_non_unique_expose_validation(self):
  1460. for invalid_expose in self.NON_UNIQUE_SINGLE_PORTS:
  1461. with pytest.raises(ConfigurationError) as exc:
  1462. self.check_config({'expose': invalid_expose})
  1463. assert "non-unique" in exc.value.msg
  1464. def test_config_invalid_expose_format_validation(self):
  1465. # Valid port mappings ARE NOT valid 'expose' entries
  1466. for invalid_expose in self.INVALID_PORT_MAPPINGS + self.VALID_PORT_MAPPINGS:
  1467. with pytest.raises(ConfigurationError) as exc:
  1468. self.check_config({'expose': invalid_expose})
  1469. assert "should be of the format" in exc.value.msg
  1470. def test_config_valid_expose_format_validation(self):
  1471. # Valid single ports ARE valid 'expose' entries
  1472. for valid_expose in self.VALID_SINGLE_PORTS:
  1473. self.check_config({'expose': valid_expose})
  1474. def check_config(self, cfg):
  1475. config.load(
  1476. build_config_details(
  1477. {'web': dict(image='busybox', **cfg)},
  1478. 'working_dir',
  1479. 'filename.yml'
  1480. )
  1481. )
  1482. class InterpolationTest(unittest.TestCase):
  1483. @mock.patch.dict(os.environ)
  1484. def test_config_file_with_environment_file(self):
  1485. project_dir = 'tests/fixtures/default-env-file'
  1486. service_dicts = config.load(
  1487. config.find(
  1488. project_dir, None, Environment.from_env_file(project_dir)
  1489. )
  1490. ).services
  1491. self.assertEqual(service_dicts[0], {
  1492. 'name': 'web',
  1493. 'image': 'alpine:latest',
  1494. 'ports': ['5643', '9999'],
  1495. 'command': 'true'
  1496. })
  1497. @mock.patch.dict(os.environ)
  1498. def test_config_file_with_environment_variable(self):
  1499. project_dir = 'tests/fixtures/environment-interpolation'
  1500. os.environ.update(
  1501. IMAGE="busybox",
  1502. HOST_PORT="80",
  1503. LABEL_VALUE="myvalue",
  1504. )
  1505. service_dicts = config.load(
  1506. config.find(
  1507. project_dir, None, Environment.from_env_file(project_dir)
  1508. )
  1509. ).services
  1510. self.assertEqual(service_dicts, [
  1511. {
  1512. 'name': 'web',
  1513. 'image': 'busybox',
  1514. 'ports': ['80:8000'],
  1515. 'labels': {'mylabel': 'myvalue'},
  1516. 'hostname': 'host-',
  1517. 'command': '${ESCAPED}',
  1518. }
  1519. ])
  1520. @mock.patch.dict(os.environ)
  1521. def test_unset_variable_produces_warning(self):
  1522. os.environ.pop('FOO', None)
  1523. os.environ.pop('BAR', None)
  1524. config_details = build_config_details(
  1525. {
  1526. 'web': {
  1527. 'image': '${FOO}',
  1528. 'command': '${BAR}',
  1529. 'container_name': '${BAR}',
  1530. },
  1531. },
  1532. '.',
  1533. None,
  1534. )
  1535. with mock.patch('compose.config.environment.log') as log:
  1536. config.load(config_details)
  1537. self.assertEqual(2, log.warn.call_count)
  1538. warnings = sorted(args[0][0] for args in log.warn.call_args_list)
  1539. self.assertIn('BAR', warnings[0])
  1540. self.assertIn('FOO', warnings[1])
  1541. @mock.patch.dict(os.environ)
  1542. def test_invalid_interpolation(self):
  1543. with self.assertRaises(config.ConfigurationError) as cm:
  1544. config.load(
  1545. build_config_details(
  1546. {'web': {'image': '${'}},
  1547. 'working_dir',
  1548. 'filename.yml'
  1549. )
  1550. )
  1551. self.assertIn('Invalid', cm.exception.msg)
  1552. self.assertIn('for "image" option', cm.exception.msg)
  1553. self.assertIn('in service "web"', cm.exception.msg)
  1554. self.assertIn('"${"', cm.exception.msg)
  1555. def test_empty_environment_key_allowed(self):
  1556. service_dict = config.load(
  1557. build_config_details(
  1558. {
  1559. 'web': {
  1560. 'build': '.',
  1561. 'environment': {
  1562. 'POSTGRES_PASSWORD': ''
  1563. },
  1564. },
  1565. },
  1566. '.',
  1567. None,
  1568. )
  1569. ).services[0]
  1570. self.assertEquals(service_dict['environment']['POSTGRES_PASSWORD'], '')
  1571. class VolumeConfigTest(unittest.TestCase):
  1572. def test_no_binding(self):
  1573. d = make_service_dict('foo', {'build': '.', 'volumes': ['/data']}, working_dir='.')
  1574. self.assertEqual(d['volumes'], ['/data'])
  1575. @mock.patch.dict(os.environ)
  1576. def test_volume_binding_with_environment_variable(self):
  1577. os.environ['VOLUME_PATH'] = '/host/path'
  1578. d = config.load(
  1579. build_config_details(
  1580. {'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
  1581. '.',
  1582. None,
  1583. )
  1584. ).services[0]
  1585. self.assertEqual(d['volumes'], [VolumeSpec.parse('/host/path:/container/path')])
  1586. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1587. @mock.patch.dict(os.environ)
  1588. def test_volume_binding_with_home(self):
  1589. os.environ['HOME'] = '/home/user'
  1590. d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
  1591. self.assertEqual(d['volumes'], ['/home/user:/container/path'])
  1592. def test_name_does_not_expand(self):
  1593. d = make_service_dict('foo', {'build': '.', 'volumes': ['mydatavolume:/data']}, working_dir='.')
  1594. self.assertEqual(d['volumes'], ['mydatavolume:/data'])
  1595. def test_absolute_posix_path_does_not_expand(self):
  1596. d = make_service_dict('foo', {'build': '.', 'volumes': ['/var/lib/data:/data']}, working_dir='.')
  1597. self.assertEqual(d['volumes'], ['/var/lib/data:/data'])
  1598. def test_absolute_windows_path_does_not_expand(self):
  1599. d = make_service_dict('foo', {'build': '.', 'volumes': ['c:\\data:/data']}, working_dir='.')
  1600. self.assertEqual(d['volumes'], ['c:\\data:/data'])
  1601. @pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='posix paths')
  1602. def test_relative_path_does_expand_posix(self):
  1603. d = make_service_dict(
  1604. 'foo',
  1605. {'build': '.', 'volumes': ['./data:/data']},
  1606. working_dir='/home/me/myproject')
  1607. self.assertEqual(d['volumes'], ['/home/me/myproject/data:/data'])
  1608. d = make_service_dict(
  1609. 'foo',
  1610. {'build': '.', 'volumes': ['.:/data']},
  1611. working_dir='/home/me/myproject')
  1612. self.assertEqual(d['volumes'], ['/home/me/myproject:/data'])
  1613. d = make_service_dict(
  1614. 'foo',
  1615. {'build': '.', 'volumes': ['../otherproject:/data']},
  1616. working_dir='/home/me/myproject')
  1617. self.assertEqual(d['volumes'], ['/home/me/otherproject:/data'])
  1618. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='windows paths')
  1619. def test_relative_path_does_expand_windows(self):
  1620. d = make_service_dict(
  1621. 'foo',
  1622. {'build': '.', 'volumes': ['./data:/data']},
  1623. working_dir='c:\\Users\\me\\myproject')
  1624. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject\\data:/data'])
  1625. d = make_service_dict(
  1626. 'foo',
  1627. {'build': '.', 'volumes': ['.:/data']},
  1628. working_dir='c:\\Users\\me\\myproject')
  1629. self.assertEqual(d['volumes'], ['c:\\Users\\me\\myproject:/data'])
  1630. d = make_service_dict(
  1631. 'foo',
  1632. {'build': '.', 'volumes': ['../otherproject:/data']},
  1633. working_dir='c:\\Users\\me\\myproject')
  1634. self.assertEqual(d['volumes'], ['c:\\Users\\me\\otherproject:/data'])
  1635. @mock.patch.dict(os.environ)
  1636. def test_home_directory_with_driver_does_not_expand(self):
  1637. os.environ['NAME'] = 'surprise!'
  1638. d = make_service_dict('foo', {
  1639. 'build': '.',
  1640. 'volumes': ['~:/data'],
  1641. 'volume_driver': 'foodriver',
  1642. }, working_dir='.')
  1643. self.assertEqual(d['volumes'], ['~:/data'])
  1644. def test_volume_path_with_non_ascii_directory(self):
  1645. volume = u'/Füü/data:/data'
  1646. container_path = config.resolve_volume_path(".", volume)
  1647. self.assertEqual(container_path, volume)
  1648. class MergePathMappingTest(object):
  1649. config_name = ""
  1650. def test_empty(self):
  1651. service_dict = config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1652. assert self.config_name not in service_dict
  1653. def test_no_override(self):
  1654. service_dict = config.merge_service_dicts(
  1655. {self.config_name: ['/foo:/code', '/data']},
  1656. {},
  1657. DEFAULT_VERSION)
  1658. assert set(service_dict[self.config_name]) == set(['/foo:/code', '/data'])
  1659. def test_no_base(self):
  1660. service_dict = config.merge_service_dicts(
  1661. {},
  1662. {self.config_name: ['/bar:/code']},
  1663. DEFAULT_VERSION)
  1664. assert set(service_dict[self.config_name]) == set(['/bar:/code'])
  1665. def test_override_explicit_path(self):
  1666. service_dict = config.merge_service_dicts(
  1667. {self.config_name: ['/foo:/code', '/data']},
  1668. {self.config_name: ['/bar:/code']},
  1669. DEFAULT_VERSION)
  1670. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1671. def test_add_explicit_path(self):
  1672. service_dict = config.merge_service_dicts(
  1673. {self.config_name: ['/foo:/code', '/data']},
  1674. {self.config_name: ['/bar:/code', '/quux:/data']},
  1675. DEFAULT_VERSION)
  1676. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/quux:/data'])
  1677. def test_remove_explicit_path(self):
  1678. service_dict = config.merge_service_dicts(
  1679. {self.config_name: ['/foo:/code', '/quux:/data']},
  1680. {self.config_name: ['/bar:/code', '/data']},
  1681. DEFAULT_VERSION)
  1682. assert set(service_dict[self.config_name]) == set(['/bar:/code', '/data'])
  1683. class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
  1684. config_name = 'volumes'
  1685. class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
  1686. config_name = 'devices'
  1687. class BuildOrImageMergeTest(unittest.TestCase):
  1688. def test_merge_build_or_image_no_override(self):
  1689. self.assertEqual(
  1690. config.merge_service_dicts({'build': '.'}, {}, V1),
  1691. {'build': '.'},
  1692. )
  1693. self.assertEqual(
  1694. config.merge_service_dicts({'image': 'redis'}, {}, V1),
  1695. {'image': 'redis'},
  1696. )
  1697. def test_merge_build_or_image_override_with_same(self):
  1698. self.assertEqual(
  1699. config.merge_service_dicts({'build': '.'}, {'build': './web'}, V1),
  1700. {'build': './web'},
  1701. )
  1702. self.assertEqual(
  1703. config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}, V1),
  1704. {'image': 'postgres'},
  1705. )
  1706. def test_merge_build_or_image_override_with_other(self):
  1707. self.assertEqual(
  1708. config.merge_service_dicts({'build': '.'}, {'image': 'redis'}, V1),
  1709. {'image': 'redis'},
  1710. )
  1711. self.assertEqual(
  1712. config.merge_service_dicts({'image': 'redis'}, {'build': '.'}, V1),
  1713. {'build': '.'}
  1714. )
  1715. class MergeListsTest(object):
  1716. config_name = ""
  1717. base_config = []
  1718. override_config = []
  1719. def merged_config(self):
  1720. return set(self.base_config) | set(self.override_config)
  1721. def test_empty(self):
  1722. assert self.config_name not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1723. def test_no_override(self):
  1724. service_dict = config.merge_service_dicts(
  1725. {self.config_name: self.base_config},
  1726. {},
  1727. DEFAULT_VERSION)
  1728. assert set(service_dict[self.config_name]) == set(self.base_config)
  1729. def test_no_base(self):
  1730. service_dict = config.merge_service_dicts(
  1731. {},
  1732. {self.config_name: self.base_config},
  1733. DEFAULT_VERSION)
  1734. assert set(service_dict[self.config_name]) == set(self.base_config)
  1735. def test_add_item(self):
  1736. service_dict = config.merge_service_dicts(
  1737. {self.config_name: self.base_config},
  1738. {self.config_name: self.override_config},
  1739. DEFAULT_VERSION)
  1740. assert set(service_dict[self.config_name]) == set(self.merged_config())
  1741. class MergePortsTest(unittest.TestCase, MergeListsTest):
  1742. config_name = 'ports'
  1743. base_config = ['10:8000', '9000']
  1744. override_config = ['20:8000']
  1745. def test_duplicate_port_mappings(self):
  1746. service_dict = config.merge_service_dicts(
  1747. {self.config_name: self.base_config},
  1748. {self.config_name: self.base_config},
  1749. DEFAULT_VERSION
  1750. )
  1751. assert set(service_dict[self.config_name]) == set(self.base_config)
  1752. class MergeNetworksTest(unittest.TestCase, MergeListsTest):
  1753. config_name = 'networks'
  1754. base_config = ['frontend', 'backend']
  1755. override_config = ['monitoring']
  1756. class MergeStringsOrListsTest(unittest.TestCase):
  1757. def test_no_override(self):
  1758. service_dict = config.merge_service_dicts(
  1759. {'dns': '8.8.8.8'},
  1760. {},
  1761. DEFAULT_VERSION)
  1762. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1763. def test_no_base(self):
  1764. service_dict = config.merge_service_dicts(
  1765. {},
  1766. {'dns': '8.8.8.8'},
  1767. DEFAULT_VERSION)
  1768. assert set(service_dict['dns']) == set(['8.8.8.8'])
  1769. def test_add_string(self):
  1770. service_dict = config.merge_service_dicts(
  1771. {'dns': ['8.8.8.8']},
  1772. {'dns': '9.9.9.9'},
  1773. DEFAULT_VERSION)
  1774. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1775. def test_add_list(self):
  1776. service_dict = config.merge_service_dicts(
  1777. {'dns': '8.8.8.8'},
  1778. {'dns': ['9.9.9.9']},
  1779. DEFAULT_VERSION)
  1780. assert set(service_dict['dns']) == set(['8.8.8.8', '9.9.9.9'])
  1781. class MergeLabelsTest(unittest.TestCase):
  1782. def test_empty(self):
  1783. assert 'labels' not in config.merge_service_dicts({}, {}, DEFAULT_VERSION)
  1784. def test_no_override(self):
  1785. service_dict = config.merge_service_dicts(
  1786. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1787. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1788. DEFAULT_VERSION)
  1789. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1790. def test_no_base(self):
  1791. service_dict = config.merge_service_dicts(
  1792. make_service_dict('foo', {'build': '.'}, 'tests/'),
  1793. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1794. DEFAULT_VERSION)
  1795. assert service_dict['labels'] == {'foo': '2'}
  1796. def test_override_explicit_value(self):
  1797. service_dict = config.merge_service_dicts(
  1798. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1799. make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
  1800. DEFAULT_VERSION)
  1801. assert service_dict['labels'] == {'foo': '2', 'bar': ''}
  1802. def test_add_explicit_value(self):
  1803. service_dict = config.merge_service_dicts(
  1804. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
  1805. make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
  1806. DEFAULT_VERSION)
  1807. assert service_dict['labels'] == {'foo': '1', 'bar': '2'}
  1808. def test_remove_explicit_value(self):
  1809. service_dict = config.merge_service_dicts(
  1810. make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
  1811. make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
  1812. DEFAULT_VERSION)
  1813. assert service_dict['labels'] == {'foo': '1', 'bar': ''}
  1814. class MemoryOptionsTest(unittest.TestCase):
  1815. def test_validation_fails_with_just_memswap_limit(self):
  1816. """
  1817. When you set a 'memswap_limit' it is invalid config unless you also set
  1818. a mem_limit
  1819. """
  1820. with pytest.raises(ConfigurationError) as excinfo:
  1821. config.load(
  1822. build_config_details(
  1823. {
  1824. 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
  1825. },
  1826. 'tests/fixtures/extends',
  1827. 'filename.yml'
  1828. )
  1829. )
  1830. assert "foo.memswap_limit is invalid: when defining " \
  1831. "'memswap_limit' you must set 'mem_limit' as well" \
  1832. in excinfo.exconly()
  1833. def test_validation_with_correct_memswap_values(self):
  1834. service_dict = config.load(
  1835. build_config_details(
  1836. {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
  1837. 'tests/fixtures/extends',
  1838. 'common.yml'
  1839. )
  1840. ).services
  1841. self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
  1842. def test_memswap_can_be_a_string(self):
  1843. service_dict = config.load(
  1844. build_config_details(
  1845. {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
  1846. 'tests/fixtures/extends',
  1847. 'common.yml'
  1848. )
  1849. ).services
  1850. self.assertEqual(service_dict[0]['memswap_limit'], "512M")
  1851. class EnvTest(unittest.TestCase):
  1852. def test_parse_environment_as_list(self):
  1853. environment = [
  1854. 'NORMAL=F1',
  1855. 'CONTAINS_EQUALS=F=2',
  1856. 'TRAILING_EQUALS=',
  1857. ]
  1858. self.assertEqual(
  1859. config.parse_environment(environment),
  1860. {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
  1861. )
  1862. def test_parse_environment_as_dict(self):
  1863. environment = {
  1864. 'NORMAL': 'F1',
  1865. 'CONTAINS_EQUALS': 'F=2',
  1866. 'TRAILING_EQUALS': None,
  1867. }
  1868. self.assertEqual(config.parse_environment(environment), environment)
  1869. def test_parse_environment_invalid(self):
  1870. with self.assertRaises(ConfigurationError):
  1871. config.parse_environment('a=b')
  1872. def test_parse_environment_empty(self):
  1873. self.assertEqual(config.parse_environment(None), {})
  1874. @mock.patch.dict(os.environ)
  1875. def test_resolve_environment(self):
  1876. os.environ['FILE_DEF'] = 'E1'
  1877. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1878. os.environ['ENV_DEF'] = 'E3'
  1879. service_dict = {
  1880. 'build': '.',
  1881. 'environment': {
  1882. 'FILE_DEF': 'F1',
  1883. 'FILE_DEF_EMPTY': '',
  1884. 'ENV_DEF': None,
  1885. 'NO_DEF': None
  1886. },
  1887. }
  1888. self.assertEqual(
  1889. resolve_environment(
  1890. service_dict, Environment.from_env_file(None)
  1891. ),
  1892. {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None},
  1893. )
  1894. def test_resolve_environment_from_env_file(self):
  1895. self.assertEqual(
  1896. resolve_environment({'env_file': ['tests/fixtures/env/one.env']}),
  1897. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
  1898. )
  1899. def test_resolve_environment_with_multiple_env_files(self):
  1900. service_dict = {
  1901. 'env_file': [
  1902. 'tests/fixtures/env/one.env',
  1903. 'tests/fixtures/env/two.env'
  1904. ]
  1905. }
  1906. self.assertEqual(
  1907. resolve_environment(service_dict),
  1908. {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
  1909. )
  1910. def test_resolve_environment_nonexistent_file(self):
  1911. with pytest.raises(ConfigurationError) as exc:
  1912. config.load(build_config_details(
  1913. {'foo': {'image': 'example', 'env_file': 'nonexistent.env'}},
  1914. working_dir='tests/fixtures/env'))
  1915. assert 'Couldn\'t find env file' in exc.exconly()
  1916. assert 'nonexistent.env' in exc.exconly()
  1917. @mock.patch.dict(os.environ)
  1918. def test_resolve_environment_from_env_file_with_empty_values(self):
  1919. os.environ['FILE_DEF'] = 'E1'
  1920. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1921. os.environ['ENV_DEF'] = 'E3'
  1922. self.assertEqual(
  1923. resolve_environment(
  1924. {'env_file': ['tests/fixtures/env/resolve.env']},
  1925. Environment.from_env_file(None)
  1926. ),
  1927. {
  1928. 'FILE_DEF': u'bär',
  1929. 'FILE_DEF_EMPTY': '',
  1930. 'ENV_DEF': 'E3',
  1931. 'NO_DEF': None
  1932. },
  1933. )
  1934. @mock.patch.dict(os.environ)
  1935. def test_resolve_build_args(self):
  1936. os.environ['env_arg'] = 'value2'
  1937. build = {
  1938. 'context': '.',
  1939. 'args': {
  1940. 'arg1': 'value1',
  1941. 'empty_arg': '',
  1942. 'env_arg': None,
  1943. 'no_env': None
  1944. }
  1945. }
  1946. self.assertEqual(
  1947. resolve_build_args(build, Environment.from_env_file(build['context'])),
  1948. {'arg1': 'value1', 'empty_arg': '', 'env_arg': 'value2', 'no_env': None},
  1949. )
  1950. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  1951. @mock.patch.dict(os.environ)
  1952. def test_resolve_path(self):
  1953. os.environ['HOSTENV'] = '/tmp'
  1954. os.environ['CONTAINERENV'] = '/host/tmp'
  1955. service_dict = config.load(
  1956. build_config_details(
  1957. {'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
  1958. "tests/fixtures/env",
  1959. )
  1960. ).services[0]
  1961. self.assertEqual(
  1962. set(service_dict['volumes']),
  1963. set([VolumeSpec.parse('/tmp:/host/tmp')]))
  1964. service_dict = config.load(
  1965. build_config_details(
  1966. {'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
  1967. "tests/fixtures/env",
  1968. )
  1969. ).services[0]
  1970. self.assertEqual(
  1971. set(service_dict['volumes']),
  1972. set([VolumeSpec.parse('/opt/tmp:/opt/host/tmp')]))
  1973. def load_from_filename(filename):
  1974. return config.load(
  1975. config.find('.', [filename], Environment.from_env_file('.'))
  1976. ).services
  1977. class ExtendsTest(unittest.TestCase):
  1978. def test_extends(self):
  1979. service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
  1980. self.assertEqual(service_sort(service_dicts), service_sort([
  1981. {
  1982. 'name': 'mydb',
  1983. 'image': 'busybox',
  1984. 'command': 'top',
  1985. },
  1986. {
  1987. 'name': 'myweb',
  1988. 'image': 'busybox',
  1989. 'command': 'top',
  1990. 'network_mode': 'bridge',
  1991. 'links': ['mydb:db'],
  1992. 'environment': {
  1993. "FOO": "1",
  1994. "BAR": "2",
  1995. "BAZ": "2",
  1996. },
  1997. }
  1998. ]))
  1999. def test_merging_env_labels_ulimits(self):
  2000. service_dicts = load_from_filename('tests/fixtures/extends/common-env-labels-ulimits.yml')
  2001. self.assertEqual(service_sort(service_dicts), service_sort([
  2002. {
  2003. 'name': 'web',
  2004. 'image': 'busybox',
  2005. 'command': '/bin/true',
  2006. 'network_mode': 'host',
  2007. 'environment': {
  2008. "FOO": "2",
  2009. "BAR": "1",
  2010. "BAZ": "3",
  2011. },
  2012. 'labels': {'label': 'one'},
  2013. 'ulimits': {'nproc': 65535, 'memlock': {'soft': 1024, 'hard': 2048}}
  2014. }
  2015. ]))
  2016. def test_nested(self):
  2017. service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
  2018. self.assertEqual(service_dicts, [
  2019. {
  2020. 'name': 'myweb',
  2021. 'image': 'busybox',
  2022. 'command': '/bin/true',
  2023. 'network_mode': 'host',
  2024. 'environment': {
  2025. "FOO": "2",
  2026. "BAR": "2",
  2027. },
  2028. },
  2029. ])
  2030. def test_self_referencing_file(self):
  2031. """
  2032. We specify a 'file' key that is the filename we're already in.
  2033. """
  2034. service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
  2035. self.assertEqual(service_sort(service_dicts), service_sort([
  2036. {
  2037. 'environment':
  2038. {
  2039. 'YEP': '1', 'BAR': '1', 'BAZ': '3'
  2040. },
  2041. 'image': 'busybox',
  2042. 'name': 'myweb'
  2043. },
  2044. {
  2045. 'environment':
  2046. {'YEP': '1'},
  2047. 'image': 'busybox',
  2048. 'name': 'otherweb'
  2049. },
  2050. {
  2051. 'environment':
  2052. {'YEP': '1', 'BAZ': '3'},
  2053. 'image': 'busybox',
  2054. 'name': 'web'
  2055. }
  2056. ]))
  2057. def test_circular(self):
  2058. with pytest.raises(config.CircularReference) as exc:
  2059. load_from_filename('tests/fixtures/extends/circle-1.yml')
  2060. path = [
  2061. (os.path.basename(filename), service_name)
  2062. for (filename, service_name) in exc.value.trail
  2063. ]
  2064. expected = [
  2065. ('circle-1.yml', 'web'),
  2066. ('circle-2.yml', 'other'),
  2067. ('circle-1.yml', 'web'),
  2068. ]
  2069. self.assertEqual(path, expected)
  2070. def test_extends_validation_empty_dictionary(self):
  2071. with pytest.raises(ConfigurationError) as excinfo:
  2072. config.load(
  2073. build_config_details(
  2074. {
  2075. 'web': {'image': 'busybox', 'extends': {}},
  2076. },
  2077. 'tests/fixtures/extends',
  2078. 'filename.yml'
  2079. )
  2080. )
  2081. assert 'service' in excinfo.exconly()
  2082. def test_extends_validation_missing_service_key(self):
  2083. with pytest.raises(ConfigurationError) as excinfo:
  2084. config.load(
  2085. build_config_details(
  2086. {
  2087. 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
  2088. },
  2089. 'tests/fixtures/extends',
  2090. 'filename.yml'
  2091. )
  2092. )
  2093. assert "'service' is a required property" in excinfo.exconly()
  2094. def test_extends_validation_invalid_key(self):
  2095. with pytest.raises(ConfigurationError) as excinfo:
  2096. config.load(
  2097. build_config_details(
  2098. {
  2099. 'web': {
  2100. 'image': 'busybox',
  2101. 'extends': {
  2102. 'file': 'common.yml',
  2103. 'service': 'web',
  2104. 'rogue_key': 'is not allowed'
  2105. }
  2106. },
  2107. },
  2108. 'tests/fixtures/extends',
  2109. 'filename.yml'
  2110. )
  2111. )
  2112. assert "web.extends contains unsupported option: 'rogue_key'" \
  2113. in excinfo.exconly()
  2114. def test_extends_validation_sub_property_key(self):
  2115. with pytest.raises(ConfigurationError) as excinfo:
  2116. config.load(
  2117. build_config_details(
  2118. {
  2119. 'web': {
  2120. 'image': 'busybox',
  2121. 'extends': {
  2122. 'file': 1,
  2123. 'service': 'web',
  2124. }
  2125. },
  2126. },
  2127. 'tests/fixtures/extends',
  2128. 'filename.yml'
  2129. )
  2130. )
  2131. assert "web.extends.file contains 1, which is an invalid type, it should be a string" \
  2132. in excinfo.exconly()
  2133. def test_extends_validation_no_file_key_no_filename_set(self):
  2134. dictionary = {'extends': {'service': 'web'}}
  2135. with pytest.raises(ConfigurationError) as excinfo:
  2136. make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
  2137. assert 'file' in excinfo.exconly()
  2138. def test_extends_validation_valid_config(self):
  2139. service = config.load(
  2140. build_config_details(
  2141. {
  2142. 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
  2143. },
  2144. 'tests/fixtures/extends',
  2145. 'common.yml'
  2146. )
  2147. ).services
  2148. self.assertEquals(len(service), 1)
  2149. self.assertIsInstance(service[0], dict)
  2150. self.assertEquals(service[0]['command'], "/bin/true")
  2151. def test_extended_service_with_invalid_config(self):
  2152. with pytest.raises(ConfigurationError) as exc:
  2153. load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
  2154. assert (
  2155. "myweb has neither an image nor a build context specified" in
  2156. exc.exconly()
  2157. )
  2158. def test_extended_service_with_valid_config(self):
  2159. service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
  2160. self.assertEquals(service[0]['command'], "top")
  2161. def test_extends_file_defaults_to_self(self):
  2162. """
  2163. Test not specifying a file in our extends options that the
  2164. config is valid and correctly extends from itself.
  2165. """
  2166. service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
  2167. self.assertEqual(service_sort(service_dicts), service_sort([
  2168. {
  2169. 'name': 'myweb',
  2170. 'image': 'busybox',
  2171. 'environment': {
  2172. "BAR": "1",
  2173. "BAZ": "3",
  2174. }
  2175. },
  2176. {
  2177. 'name': 'web',
  2178. 'image': 'busybox',
  2179. 'environment': {
  2180. "BAZ": "3",
  2181. }
  2182. }
  2183. ]))
  2184. def test_invalid_links_in_extended_service(self):
  2185. with pytest.raises(ConfigurationError) as excinfo:
  2186. load_from_filename('tests/fixtures/extends/invalid-links.yml')
  2187. assert "services with 'links' cannot be extended" in excinfo.exconly()
  2188. def test_invalid_volumes_from_in_extended_service(self):
  2189. with pytest.raises(ConfigurationError) as excinfo:
  2190. load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
  2191. assert "services with 'volumes_from' cannot be extended" in excinfo.exconly()
  2192. def test_invalid_net_in_extended_service(self):
  2193. with pytest.raises(ConfigurationError) as excinfo:
  2194. load_from_filename('tests/fixtures/extends/invalid-net-v2.yml')
  2195. assert 'network_mode: service' in excinfo.exconly()
  2196. assert 'cannot be extended' in excinfo.exconly()
  2197. with pytest.raises(ConfigurationError) as excinfo:
  2198. load_from_filename('tests/fixtures/extends/invalid-net.yml')
  2199. assert 'net: container' in excinfo.exconly()
  2200. assert 'cannot be extended' in excinfo.exconly()
  2201. @mock.patch.dict(os.environ)
  2202. def test_load_config_runs_interpolation_in_extended_service(self):
  2203. os.environ.update(HOSTNAME_VALUE="penguin")
  2204. expected_interpolated_value = "host-penguin"
  2205. service_dicts = load_from_filename(
  2206. 'tests/fixtures/extends/valid-interpolation.yml')
  2207. for service in service_dicts:
  2208. assert service['hostname'] == expected_interpolated_value
  2209. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2210. def test_volume_path(self):
  2211. dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
  2212. paths = [
  2213. VolumeSpec(
  2214. os.path.abspath('tests/fixtures/volume-path/common/foo'),
  2215. '/foo',
  2216. 'rw'),
  2217. VolumeSpec(
  2218. os.path.abspath('tests/fixtures/volume-path/bar'),
  2219. '/bar',
  2220. 'rw')
  2221. ]
  2222. self.assertEqual(set(dicts[0]['volumes']), set(paths))
  2223. def test_parent_build_path_dne(self):
  2224. child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
  2225. self.assertEqual(child, [
  2226. {
  2227. 'name': 'dnechild',
  2228. 'image': 'busybox',
  2229. 'command': '/bin/true',
  2230. 'environment': {
  2231. "FOO": "1",
  2232. "BAR": "2",
  2233. },
  2234. },
  2235. ])
  2236. def test_load_throws_error_when_base_service_does_not_exist(self):
  2237. with pytest.raises(ConfigurationError) as excinfo:
  2238. load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
  2239. assert "Cannot extend service 'foo'" in excinfo.exconly()
  2240. assert "Service not found" in excinfo.exconly()
  2241. def test_partial_service_config_in_extends_is_still_valid(self):
  2242. dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
  2243. self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
  2244. def test_extended_service_with_verbose_and_shorthand_way(self):
  2245. services = load_from_filename('tests/fixtures/extends/verbose-and-shorthand.yml')
  2246. self.assertEqual(service_sort(services), service_sort([
  2247. {
  2248. 'name': 'base',
  2249. 'image': 'busybox',
  2250. 'environment': {'BAR': '1'},
  2251. },
  2252. {
  2253. 'name': 'verbose',
  2254. 'image': 'busybox',
  2255. 'environment': {'BAR': '1', 'FOO': '1'},
  2256. },
  2257. {
  2258. 'name': 'shorthand',
  2259. 'image': 'busybox',
  2260. 'environment': {'BAR': '1', 'FOO': '2'},
  2261. },
  2262. ]))
  2263. @mock.patch.dict(os.environ)
  2264. def test_extends_with_environment_and_env_files(self):
  2265. tmpdir = py.test.ensuretemp('test_extends_with_environment')
  2266. self.addCleanup(tmpdir.remove)
  2267. commondir = tmpdir.mkdir('common')
  2268. commondir.join('base.yml').write("""
  2269. app:
  2270. image: 'example/app'
  2271. env_file:
  2272. - 'envs'
  2273. environment:
  2274. - SECRET
  2275. - TEST_ONE=common
  2276. - TEST_TWO=common
  2277. """)
  2278. tmpdir.join('docker-compose.yml').write("""
  2279. ext:
  2280. extends:
  2281. file: common/base.yml
  2282. service: app
  2283. env_file:
  2284. - 'envs'
  2285. environment:
  2286. - THING
  2287. - TEST_ONE=top
  2288. """)
  2289. commondir.join('envs').write("""
  2290. COMMON_ENV_FILE
  2291. TEST_ONE=common-env-file
  2292. TEST_TWO=common-env-file
  2293. TEST_THREE=common-env-file
  2294. TEST_FOUR=common-env-file
  2295. """)
  2296. tmpdir.join('envs').write("""
  2297. TOP_ENV_FILE
  2298. TEST_ONE=top-env-file
  2299. TEST_TWO=top-env-file
  2300. TEST_THREE=top-env-file
  2301. """)
  2302. expected = [
  2303. {
  2304. 'name': 'ext',
  2305. 'image': 'example/app',
  2306. 'environment': {
  2307. 'SECRET': 'secret',
  2308. 'TOP_ENV_FILE': 'secret',
  2309. 'COMMON_ENV_FILE': 'secret',
  2310. 'THING': 'thing',
  2311. 'TEST_ONE': 'top',
  2312. 'TEST_TWO': 'common',
  2313. 'TEST_THREE': 'top-env-file',
  2314. 'TEST_FOUR': 'common-env-file',
  2315. },
  2316. },
  2317. ]
  2318. os.environ['SECRET'] = 'secret'
  2319. os.environ['THING'] = 'thing'
  2320. os.environ['COMMON_ENV_FILE'] = 'secret'
  2321. os.environ['TOP_ENV_FILE'] = 'secret'
  2322. config = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2323. assert config == expected
  2324. def test_extends_with_mixed_versions_is_error(self):
  2325. tmpdir = py.test.ensuretemp('test_extends_with_mixed_version')
  2326. self.addCleanup(tmpdir.remove)
  2327. tmpdir.join('docker-compose.yml').write("""
  2328. version: "2"
  2329. services:
  2330. web:
  2331. extends:
  2332. file: base.yml
  2333. service: base
  2334. image: busybox
  2335. """)
  2336. tmpdir.join('base.yml').write("""
  2337. base:
  2338. volumes: ['/foo']
  2339. ports: ['3000:3000']
  2340. """)
  2341. with pytest.raises(ConfigurationError) as exc:
  2342. load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2343. assert 'Version mismatch' in exc.exconly()
  2344. def test_extends_with_defined_version_passes(self):
  2345. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2346. self.addCleanup(tmpdir.remove)
  2347. tmpdir.join('docker-compose.yml').write("""
  2348. version: "2"
  2349. services:
  2350. web:
  2351. extends:
  2352. file: base.yml
  2353. service: base
  2354. image: busybox
  2355. """)
  2356. tmpdir.join('base.yml').write("""
  2357. version: "2"
  2358. services:
  2359. base:
  2360. volumes: ['/foo']
  2361. ports: ['3000:3000']
  2362. command: top
  2363. """)
  2364. service = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2365. self.assertEquals(service[0]['command'], "top")
  2366. def test_extends_with_depends_on(self):
  2367. tmpdir = py.test.ensuretemp('test_extends_with_defined_version')
  2368. self.addCleanup(tmpdir.remove)
  2369. tmpdir.join('docker-compose.yml').write("""
  2370. version: "2"
  2371. services:
  2372. base:
  2373. image: example
  2374. web:
  2375. extends: base
  2376. image: busybox
  2377. depends_on: ['other']
  2378. other:
  2379. image: example
  2380. """)
  2381. services = load_from_filename(str(tmpdir.join('docker-compose.yml')))
  2382. assert service_sort(services)[2]['depends_on'] == ['other']
  2383. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2384. class ExpandPathTest(unittest.TestCase):
  2385. working_dir = '/home/user/somedir'
  2386. def test_expand_path_normal(self):
  2387. result = config.expand_path(self.working_dir, 'myfile')
  2388. self.assertEqual(result, self.working_dir + '/' + 'myfile')
  2389. def test_expand_path_absolute(self):
  2390. abs_path = '/home/user/otherdir/somefile'
  2391. result = config.expand_path(self.working_dir, abs_path)
  2392. self.assertEqual(result, abs_path)
  2393. def test_expand_path_with_tilde(self):
  2394. test_path = '~/otherdir/somefile'
  2395. with mock.patch.dict(os.environ):
  2396. os.environ['HOME'] = user_path = '/home/user/'
  2397. result = config.expand_path(self.working_dir, test_path)
  2398. self.assertEqual(result, user_path + 'otherdir/somefile')
  2399. class VolumePathTest(unittest.TestCase):
  2400. def test_split_path_mapping_with_windows_path(self):
  2401. host_path = "c:\\Users\\msamblanet\\Documents\\anvil\\connect\\config"
  2402. windows_volume_path = host_path + ":/opt/connect/config:ro"
  2403. expected_mapping = ("/opt/connect/config:ro", host_path)
  2404. mapping = config.split_path_mapping(windows_volume_path)
  2405. assert mapping == expected_mapping
  2406. def test_split_path_mapping_with_windows_path_in_container(self):
  2407. host_path = 'c:\\Users\\remilia\\data'
  2408. container_path = 'c:\\scarletdevil\\data'
  2409. expected_mapping = (container_path, host_path)
  2410. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  2411. assert mapping == expected_mapping
  2412. def test_split_path_mapping_with_root_mount(self):
  2413. host_path = '/'
  2414. container_path = '/var/hostroot'
  2415. expected_mapping = (container_path, host_path)
  2416. mapping = config.split_path_mapping('{0}:{1}'.format(host_path, container_path))
  2417. assert mapping == expected_mapping
  2418. @pytest.mark.xfail(IS_WINDOWS_PLATFORM, reason='paths use slash')
  2419. class BuildPathTest(unittest.TestCase):
  2420. def setUp(self):
  2421. self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
  2422. def test_nonexistent_path(self):
  2423. with self.assertRaises(ConfigurationError):
  2424. config.load(
  2425. build_config_details(
  2426. {
  2427. 'foo': {'build': 'nonexistent.path'},
  2428. },
  2429. 'working_dir',
  2430. 'filename.yml'
  2431. )
  2432. )
  2433. def test_relative_path(self):
  2434. relative_build_path = '../build-ctx/'
  2435. service_dict = make_service_dict(
  2436. 'relpath',
  2437. {'build': relative_build_path},
  2438. working_dir='tests/fixtures/build-path'
  2439. )
  2440. self.assertEquals(service_dict['build'], self.abs_context_path)
  2441. def test_absolute_path(self):
  2442. service_dict = make_service_dict(
  2443. 'abspath',
  2444. {'build': self.abs_context_path},
  2445. working_dir='tests/fixtures/build-path'
  2446. )
  2447. self.assertEquals(service_dict['build'], self.abs_context_path)
  2448. def test_from_file(self):
  2449. service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
  2450. self.assertEquals(service_dict, [{'name': 'foo', 'build': {'context': self.abs_context_path}}])
  2451. def test_valid_url_in_build_path(self):
  2452. valid_urls = [
  2453. 'git://github.com/docker/docker',
  2454. '[email protected]:docker/docker.git',
  2455. '[email protected]:atlassianlabs/atlassian-docker.git',
  2456. 'https://github.com/docker/docker.git',
  2457. 'http://github.com/docker/docker.git',
  2458. 'github.com/docker/docker.git',
  2459. ]
  2460. for valid_url in valid_urls:
  2461. service_dict = config.load(build_config_details({
  2462. 'validurl': {'build': valid_url},
  2463. }, '.', None)).services
  2464. assert service_dict[0]['build'] == {'context': valid_url}
  2465. def test_invalid_url_in_build_path(self):
  2466. invalid_urls = [
  2467. 'example.com/bogus',
  2468. 'ftp://example.com/',
  2469. '/path/does/not/exist',
  2470. ]
  2471. for invalid_url in invalid_urls:
  2472. with pytest.raises(ConfigurationError) as exc:
  2473. config.load(build_config_details({
  2474. 'invalidurl': {'build': invalid_url},
  2475. }, '.', None))
  2476. assert 'build path' in exc.exconly()
  2477. class GetDefaultConfigFilesTestCase(unittest.TestCase):
  2478. files = [
  2479. 'docker-compose.yml',
  2480. 'docker-compose.yaml',
  2481. ]
  2482. def test_get_config_path_default_file_in_basedir(self):
  2483. for index, filename in enumerate(self.files):
  2484. self.assertEqual(
  2485. filename,
  2486. get_config_filename_for_files(self.files[index:]))
  2487. with self.assertRaises(config.ComposeFileNotFound):
  2488. get_config_filename_for_files([])
  2489. def test_get_config_path_default_file_in_parent_dir(self):
  2490. """Test with files placed in the subdir"""
  2491. def get_config_in_subdir(files):
  2492. return get_config_filename_for_files(files, subdir=True)
  2493. for index, filename in enumerate(self.files):
  2494. self.assertEqual(filename, get_config_in_subdir(self.files[index:]))
  2495. with self.assertRaises(config.ComposeFileNotFound):
  2496. get_config_in_subdir([])
  2497. def get_config_filename_for_files(filenames, subdir=None):
  2498. def make_files(dirname, filenames):
  2499. for fname in filenames:
  2500. with open(os.path.join(dirname, fname), 'w') as f:
  2501. f.write('')
  2502. project_dir = tempfile.mkdtemp()
  2503. try:
  2504. make_files(project_dir, filenames)
  2505. if subdir:
  2506. base_dir = tempfile.mkdtemp(dir=project_dir)
  2507. else:
  2508. base_dir = project_dir
  2509. filename, = config.get_default_config_files(base_dir)
  2510. return os.path.basename(filename)
  2511. finally:
  2512. shutil.rmtree(project_dir)