config_test.py 99 KB

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