config_test.py 109 KB

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