config_test.py 111 KB

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