OpenStack library for config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

5029 lines
192 KiB

  1. # Copyright 2014 Red Hat, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. import argparse
  15. import errno
  16. import functools
  17. import logging
  18. import os
  19. import shutil
  20. import sys
  21. import tempfile
  22. import fixtures
  23. import mock
  24. from oslotest import base
  25. import six
  26. from six import moves
  27. import testscenarios
  28. from oslo_config import cfg
  29. from oslo_config import types
  30. load_tests = testscenarios.load_tests_apply_scenarios
  31. class ExceptionsTestCase(base.BaseTestCase):
  32. def test_error(self):
  33. msg = str(cfg.Error('foobar'))
  34. self.assertEqual('foobar', msg)
  35. def test_args_already_parsed_error(self):
  36. msg = str(cfg.ArgsAlreadyParsedError('foobar'))
  37. self.assertEqual('arguments already parsed: foobar', msg)
  38. def test_no_such_opt_error(self):
  39. msg = str(cfg.NoSuchOptError('foo'))
  40. self.assertEqual('no such option foo in group [DEFAULT]', msg)
  41. def test_no_such_opt_error_with_group(self):
  42. msg = str(cfg.NoSuchOptError('foo', cfg.OptGroup('bar')))
  43. self.assertEqual('no such option foo in group [bar]', msg)
  44. def test_no_such_group_error(self):
  45. msg = str(cfg.NoSuchGroupError('bar'))
  46. self.assertEqual('no such group [bar]', msg)
  47. def test_duplicate_opt_error(self):
  48. msg = str(cfg.DuplicateOptError('foo'))
  49. self.assertEqual('duplicate option: foo', msg)
  50. def test_required_opt_error(self):
  51. msg = str(cfg.RequiredOptError('foo'))
  52. self.assertEqual('value required for option foo in group [DEFAULT]',
  53. msg)
  54. def test_required_opt_error_with_group(self):
  55. msg = str(cfg.RequiredOptError('foo', cfg.OptGroup('bar')))
  56. self.assertEqual('value required for option foo in group [bar]', msg)
  57. def test_template_substitution_error(self):
  58. msg = str(cfg.TemplateSubstitutionError('foobar'))
  59. self.assertEqual('template substitution error: foobar', msg)
  60. def test_config_files_not_found_error(self):
  61. msg = str(cfg.ConfigFilesNotFoundError(['foo', 'bar']))
  62. self.assertEqual('Failed to find some config files: foo,bar', msg)
  63. def test_config_files_permission_denied_error(self):
  64. msg = str(cfg.ConfigFilesPermissionDeniedError(['foo', 'bar']))
  65. self.assertEqual('Failed to open some config files: foo,bar', msg)
  66. def test_config_dir_not_found_error(self):
  67. msg = str(cfg.ConfigDirNotFoundError('foobar'))
  68. self.assertEqual('Failed to read config file directory: foobar', msg)
  69. def test_config_file_parse_error(self):
  70. msg = str(cfg.ConfigFileParseError('foo', 'foobar'))
  71. self.assertEqual('Failed to parse foo: foobar', msg)
  72. class BaseTestCase(base.BaseTestCase):
  73. class TestConfigOpts(cfg.ConfigOpts):
  74. def __call__(self, args=None, default_config_files=[],
  75. default_config_dirs=[]):
  76. return cfg.ConfigOpts.__call__(
  77. self,
  78. args=args,
  79. prog='test',
  80. version='1.0',
  81. usage='%(prog)s FOO BAR',
  82. description='somedesc',
  83. epilog='tepilog',
  84. default_config_files=default_config_files,
  85. default_config_dirs=default_config_dirs,
  86. validate_default_values=True)
  87. def setUp(self):
  88. super(BaseTestCase, self).setUp()
  89. self.useFixture(fixtures.NestedTempfile())
  90. self.conf = self.TestConfigOpts()
  91. self.tempdirs = []
  92. def create_tempfiles(self, files, ext='.conf'):
  93. tempfiles = []
  94. for (basename, contents) in files:
  95. if not os.path.isabs(basename):
  96. # create all the tempfiles in a tempdir
  97. tmpdir = tempfile.mkdtemp()
  98. path = os.path.join(tmpdir, basename + ext)
  99. # the path can start with a subdirectory so create
  100. # it if it doesn't exist yet
  101. if not os.path.exists(os.path.dirname(path)):
  102. os.makedirs(os.path.dirname(path))
  103. else:
  104. path = basename + ext
  105. fd = os.open(path, os.O_CREAT | os.O_WRONLY)
  106. tempfiles.append(path)
  107. try:
  108. os.write(fd, contents.encode('utf-8'))
  109. finally:
  110. os.close(fd)
  111. return tempfiles
  112. class UsageTestCase(BaseTestCase):
  113. def test_print_usage(self):
  114. f = moves.StringIO()
  115. self.conf([])
  116. self.conf.print_usage(file=f)
  117. self.assertIn('usage: test FOO BAR', f.getvalue())
  118. self.assertNotIn('somedesc', f.getvalue())
  119. self.assertNotIn('tepilog', f.getvalue())
  120. self.assertNotIn('optional:', f.getvalue())
  121. def test_print_help(self):
  122. f = moves.StringIO()
  123. self.conf([])
  124. self.conf.print_help(file=f)
  125. self.assertIn('usage: test FOO BAR', f.getvalue())
  126. self.assertIn('somedesc', f.getvalue())
  127. self.assertIn('tepilog', f.getvalue())
  128. self.assertNotIn('optional:', f.getvalue())
  129. class HelpTestCase(BaseTestCase):
  130. def test_print_help(self):
  131. f = moves.StringIO()
  132. self.conf([])
  133. self.conf.print_help(file=f)
  134. self.assertIn('usage: test FOO BAR', f.getvalue())
  135. self.assertIn('optional', f.getvalue())
  136. self.assertIn('-h, --help', f.getvalue())
  137. def test_print_sorted_help(self):
  138. f = moves.StringIO()
  139. self.conf.register_cli_opt(cfg.StrOpt('abc'))
  140. self.conf.register_cli_opt(cfg.StrOpt('zba'))
  141. self.conf.register_cli_opt(cfg.StrOpt('ghi'))
  142. self.conf.register_cli_opt(cfg.StrOpt('deb'))
  143. self.conf([])
  144. self.conf.print_help(file=f)
  145. zba = f.getvalue().find('--zba')
  146. abc = f.getvalue().find('--abc')
  147. ghi = f.getvalue().find('--ghi')
  148. deb = f.getvalue().find('--deb')
  149. list = [abc, deb, ghi, zba]
  150. self.assertEqual(sorted(list), list)
  151. def test_print_sorted_help_with_positionals(self):
  152. f = moves.StringIO()
  153. self.conf.register_cli_opt(cfg.StrOpt('pst', positional=True))
  154. self.conf.register_cli_opt(cfg.StrOpt('abc'))
  155. self.conf.register_cli_opt(cfg.StrOpt('zba'))
  156. self.conf.register_cli_opt(cfg.StrOpt('ghi'))
  157. self.conf([])
  158. self.conf.print_help(file=f)
  159. zba = f.getvalue().find('--zba')
  160. abc = f.getvalue().find('--abc')
  161. ghi = f.getvalue().find('--ghi')
  162. list = [abc, ghi, zba]
  163. self.assertEqual(sorted(list), list)
  164. def test_print_help_with_deprecated(self):
  165. f = moves.StringIO()
  166. abc = cfg.StrOpt('a-bc',
  167. deprecated_opts=[cfg.DeprecatedOpt('d-ef')])
  168. uvw = cfg.StrOpt('u-vw',
  169. deprecated_name='x-yz')
  170. self.conf.register_cli_opt(abc)
  171. self.conf.register_cli_opt(uvw)
  172. self.conf([])
  173. self.conf.print_help(file=f)
  174. self.assertIn('--a-bc A_BC, --d-ef A_BC, --d_ef A_BC', f.getvalue())
  175. self.assertIn('--u-vw U_VW, --x-yz U_VW, --x_yz U_VW', f.getvalue())
  176. class FindConfigFilesTestCase(BaseTestCase):
  177. def test_find_config_files(self):
  178. config_files = [os.path.expanduser('~/.blaa/blaa.conf'),
  179. '/etc/foo.conf']
  180. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo']))
  181. self.useFixture(fixtures.MonkeyPatch('os.path.exists',
  182. lambda p: p in config_files))
  183. self.assertEqual(cfg.find_config_files(project='blaa'), config_files)
  184. def test_find_config_files_snap(self):
  185. config_files = ['/snap/nova/current/etc/blaa/blaa.conf']
  186. fake_env = {'SNAP': '/snap/nova/current/',
  187. 'SNAP_COMMON': '/var/snap/nova/common/'}
  188. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo']))
  189. self.useFixture(fixtures.MonkeyPatch('os.path.exists',
  190. lambda p: p in config_files))
  191. self.useFixture(fixtures.MonkeyPatch('os.environ', fake_env))
  192. self.assertEqual(cfg.find_config_files(project='blaa'), config_files)
  193. def test_find_config_files_with_extension(self):
  194. config_files = ['/etc/foo.json']
  195. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo']))
  196. self.useFixture(fixtures.MonkeyPatch('os.path.exists',
  197. lambda p: p in config_files))
  198. self.assertEqual(cfg.find_config_files(project='blaa'), [])
  199. self.assertEqual(cfg.find_config_files(project='blaa',
  200. extension='.json'),
  201. config_files)
  202. class FindConfigDirsTestCase(BaseTestCase):
  203. def test_find_config_dirs(self):
  204. config_dirs = [os.path.expanduser('~/.blaa/blaa.conf.d'),
  205. '/etc/foo.conf.d']
  206. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo']))
  207. self.useFixture(fixtures.MonkeyPatch('os.path.exists',
  208. lambda p: p in config_dirs))
  209. self.assertEqual(cfg.find_config_dirs(project='blaa'), config_dirs)
  210. def test_find_config_dirs_snap(self):
  211. config_dirs = ['/var/snap/nova/common/etc/blaa/blaa.conf.d']
  212. fake_env = {'SNAP': '/snap/nova/current/',
  213. 'SNAP_COMMON': '/var/snap/nova/common/'}
  214. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo']))
  215. self.useFixture(fixtures.MonkeyPatch('os.path.exists',
  216. lambda p: p in config_dirs))
  217. self.useFixture(fixtures.MonkeyPatch('os.environ', fake_env))
  218. self.assertEqual(cfg.find_config_dirs(project='blaa'), config_dirs)
  219. def test_find_config_dirs_non_exists(self):
  220. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo']))
  221. self.assertEqual(cfg.find_config_dirs(project='blaa'), [])
  222. def test_find_config_dirs_with_extension(self):
  223. config_dirs = ['/etc/foo.json.d']
  224. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo']))
  225. self.useFixture(fixtures.MonkeyPatch('os.path.exists',
  226. lambda p: p in config_dirs))
  227. self.assertEqual(cfg.find_config_dirs(project='blaa'), [])
  228. self.assertEqual(cfg.find_config_dirs(project='blaa',
  229. extension='.json.d'),
  230. config_dirs)
  231. class DefaultConfigFilesTestCase(BaseTestCase):
  232. def test_use_default(self):
  233. self.conf.register_opt(cfg.StrOpt('foo'))
  234. paths = self.create_tempfiles([('foo-', '[DEFAULT]\n''foo = bar\n')])
  235. self.conf.register_cli_opt(cfg.StrOpt('config-file-foo'))
  236. self.conf(args=['--config-file-foo', 'foo.conf'],
  237. default_config_files=[paths[0]])
  238. self.assertEqual([paths[0]], self.conf.config_file)
  239. self.assertEqual('bar', self.conf.foo)
  240. def test_do_not_use_default_multi_arg(self):
  241. self.conf.register_opt(cfg.StrOpt('foo'))
  242. paths = self.create_tempfiles([('foo-', '[DEFAULT]\n''foo = bar\n')])
  243. self.conf(args=['--config-file', paths[0]],
  244. default_config_files=['bar.conf'])
  245. self.assertEqual([paths[0]], self.conf.config_file)
  246. self.assertEqual('bar', self.conf.foo)
  247. def test_do_not_use_default_single_arg(self):
  248. self.conf.register_opt(cfg.StrOpt('foo'))
  249. paths = self.create_tempfiles([('foo-', '[DEFAULT]\n''foo = bar\n')])
  250. self.conf(args=['--config-file=' + paths[0]],
  251. default_config_files=['bar.conf'])
  252. self.assertEqual([paths[0]], self.conf.config_file)
  253. self.assertEqual('bar', self.conf.foo)
  254. def test_no_default_config_file(self):
  255. self.conf(args=[])
  256. self.assertEqual([], self.conf.config_file)
  257. def test_find_default_config_file(self):
  258. paths = self.create_tempfiles([('def', '[DEFAULT]')])
  259. self.useFixture(fixtures.MonkeyPatch(
  260. 'oslo_config.cfg.find_config_files',
  261. lambda project, prog: paths))
  262. self.conf(args=[], default_config_files=None)
  263. self.assertEqual(paths, self.conf.config_file)
  264. def test_default_config_file(self):
  265. paths = self.create_tempfiles([('def', '[DEFAULT]')])
  266. self.conf(args=[], default_config_files=paths)
  267. self.assertEqual(paths, self.conf.config_file)
  268. def test_default_config_file_with_value(self):
  269. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  270. paths = self.create_tempfiles([('def', '[DEFAULT]\n''foo = bar\n')])
  271. self.conf(args=[], default_config_files=paths)
  272. self.assertEqual(paths, self.conf.config_file)
  273. self.assertEqual('bar', self.conf.foo)
  274. def test_default_config_file_priority(self):
  275. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  276. paths = self.create_tempfiles([('def', '[DEFAULT]\n''foo = bar\n')])
  277. self.conf(args=['--foo=blaa'], default_config_files=paths)
  278. self.assertEqual(paths, self.conf.config_file)
  279. self.assertEqual('blaa', self.conf.foo)
  280. class DefaultConfigDirsTestCase(BaseTestCase):
  281. def test_use_default(self):
  282. self.conf.register_opt(cfg.StrOpt('foo'))
  283. paths = self.create_tempfiles([('foo.conf.d/foo',
  284. '[DEFAULT]\n''foo = bar\n')])
  285. p = os.path.dirname(paths[0])
  286. self.conf.register_cli_opt(cfg.StrOpt('config-dir-foo'))
  287. self.conf(args=['--config-dir-foo', 'foo.conf.d'],
  288. default_config_dirs=[p])
  289. self.assertEqual([p], self.conf.config_dir)
  290. self.assertEqual('bar', self.conf.foo)
  291. def test_do_not_use_default_multi_arg(self):
  292. self.conf.register_opt(cfg.StrOpt('foo'))
  293. paths = self.create_tempfiles([('foo.conf.d/foo',
  294. '[DEFAULT]\n''foo = bar\n')])
  295. p = os.path.dirname(paths[0])
  296. self.conf(args=['--config-dir', p],
  297. default_config_dirs=['bar.conf.d'])
  298. self.assertEqual([p], self.conf.config_dirs)
  299. self.assertEqual('bar', self.conf.foo)
  300. def test_do_not_use_default_single_arg(self):
  301. self.conf.register_opt(cfg.StrOpt('foo'))
  302. paths = self.create_tempfiles([('foo.conf.d/foo',
  303. '[DEFAULT]\n''foo = bar\n')])
  304. p = os.path.dirname(paths[0])
  305. self.conf(args=['--config-dir=' + p],
  306. default_config_dirs=['bar.conf.d'])
  307. self.assertEqual([p], self.conf.config_dir)
  308. self.assertEqual('bar', self.conf.foo)
  309. def test_no_default_config_dir(self):
  310. self.conf(args=[])
  311. self.assertEqual([], self.conf.config_dir)
  312. def test_find_default_config_dir(self):
  313. paths = self.create_tempfiles([('def.conf.d/def',
  314. '[DEFAULT]')])
  315. p = os.path.dirname(paths[0])
  316. self.useFixture(fixtures.MonkeyPatch(
  317. 'oslo_config.cfg.find_config_dirs',
  318. lambda project, prog: p))
  319. self.conf(args=[], default_config_dirs=None)
  320. self.assertEqual([p], self.conf.config_dir)
  321. def test_default_config_dir(self):
  322. paths = self.create_tempfiles([('def.conf.d/def',
  323. '[DEFAULT]')])
  324. p = os.path.dirname(paths[0])
  325. self.conf(args=[], default_config_dirs=[p])
  326. self.assertEqual([p], self.conf.config_dir)
  327. def test_default_config_dir_with_value(self):
  328. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  329. paths = self.create_tempfiles([('def.conf.d/def',
  330. '[DEFAULT]\n''foo = bar\n')])
  331. p = os.path.dirname(paths[0])
  332. self.conf(args=[], default_config_dirs=[p])
  333. self.assertEqual([p], self.conf.config_dir)
  334. self.assertEqual('bar', self.conf.foo)
  335. def test_default_config_dir_priority(self):
  336. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  337. paths = self.create_tempfiles([('def.conf.d/def',
  338. '[DEFAULT]\n''foo = bar\n')])
  339. p = os.path.dirname(paths[0])
  340. self.conf(args=['--foo=blaa'], default_config_dirs=[p])
  341. self.assertEqual([p], self.conf.config_dir)
  342. self.assertEqual('blaa', self.conf.foo)
  343. class CliOptsTestCase(BaseTestCase):
  344. """Test CLI Options.
  345. Each test scenario takes a name for the scenarios, as well as a dict:
  346. opt_class - class of the type of option that should be tested
  347. default - a default value for the option
  348. cli_args - a list containing a representation of an input command line
  349. value - the result value that is expected to be found
  350. deps - a tuple of deprecated name/group
  351. """
  352. IPv4Opt = functools.partial(cfg.IPOpt, version=4)
  353. IPv6Opt = functools.partial(cfg.IPOpt, version=6)
  354. multi_int = functools.partial(cfg.MultiOpt, item_type=types.Integer())
  355. multi_float = functools.partial(cfg.MultiOpt, item_type=types.Float())
  356. multi_string = functools.partial(cfg.MultiOpt, item_type=types.String())
  357. scenarios = [
  358. ('str_default',
  359. dict(opt_class=cfg.StrOpt, default=None, cli_args=[], value=None,
  360. deps=(None, None))),
  361. ('str_arg',
  362. dict(opt_class=cfg.StrOpt, default=None, cli_args=['--foo', 'bar'],
  363. value='bar', deps=(None, None))),
  364. ('str_arg_deprecated_name',
  365. dict(opt_class=cfg.StrOpt, default=None,
  366. cli_args=['--oldfoo', 'bar'], value='bar',
  367. deps=('oldfoo', None))),
  368. ('str_arg_deprecated_group',
  369. dict(opt_class=cfg.StrOpt, default=None,
  370. cli_args=['--old-foo', 'bar'], value='bar',
  371. deps=(None, 'old'))),
  372. ('str_arg_deprecated_group_default',
  373. dict(opt_class=cfg.StrOpt, default=None, cli_args=['--foo', 'bar'],
  374. value='bar', deps=(None, 'DEFAULT'))),
  375. ('str_arg_deprecated_group_and_name',
  376. dict(opt_class=cfg.StrOpt, default=None,
  377. cli_args=['--old-oof', 'bar'], value='bar',
  378. deps=('oof', 'old'))),
  379. ('bool_default',
  380. dict(opt_class=cfg.BoolOpt, default=False,
  381. cli_args=[], value=False, deps=(None, None))),
  382. ('bool_arg',
  383. dict(opt_class=cfg.BoolOpt, default=None,
  384. cli_args=['--foo'], value=True, deps=(None, None))),
  385. ('bool_arg_deprecated_name',
  386. dict(opt_class=cfg.BoolOpt, default=None,
  387. cli_args=['--oldfoo'], value=True,
  388. deps=('oldfoo', None))),
  389. ('bool_arg_deprecated_group',
  390. dict(opt_class=cfg.BoolOpt, default=None,
  391. cli_args=['--old-foo'], value=True,
  392. deps=(None, 'old'))),
  393. ('bool_arg_deprecated_group_default',
  394. dict(opt_class=cfg.BoolOpt, default=None,
  395. cli_args=['--foo'], value=True,
  396. deps=(None, 'DEFAULT'))),
  397. ('bool_arg_deprecated_group_and_name',
  398. dict(opt_class=cfg.BoolOpt, default=None,
  399. cli_args=['--old-oof'], value=True,
  400. deps=('oof', 'old'))),
  401. ('bool_arg_inverse',
  402. dict(opt_class=cfg.BoolOpt, default=None,
  403. cli_args=['--foo', '--nofoo'], value=False, deps=(None, None))),
  404. ('bool_arg_inverse_deprecated_name',
  405. dict(opt_class=cfg.BoolOpt, default=None,
  406. cli_args=['--oldfoo', '--nooldfoo'], value=False,
  407. deps=('oldfoo', None))),
  408. ('bool_arg_inverse_deprecated_group',
  409. dict(opt_class=cfg.BoolOpt, default=None,
  410. cli_args=['--old-foo', '--old-nofoo'], value=False,
  411. deps=(None, 'old'))),
  412. ('bool_arg_inverse_deprecated_group_default',
  413. dict(opt_class=cfg.BoolOpt, default=None,
  414. cli_args=['--foo', '--nofoo'], value=False,
  415. deps=(None, 'DEFAULT'))),
  416. ('bool_arg_inverse_deprecated_group_and_name',
  417. dict(opt_class=cfg.BoolOpt, default=None,
  418. cli_args=['--old-oof', '--old-nooof'], value=False,
  419. deps=('oof', 'old'))),
  420. ('int_default',
  421. dict(opt_class=cfg.IntOpt, default=10,
  422. cli_args=[], value=10, deps=(None, None))),
  423. ('int_arg',
  424. dict(opt_class=cfg.IntOpt, default=None,
  425. cli_args=['--foo=20'], value=20, deps=(None, None))),
  426. ('int_arg_deprecated_name',
  427. dict(opt_class=cfg.IntOpt, default=None,
  428. cli_args=['--oldfoo=20'], value=20, deps=('oldfoo', None))),
  429. ('int_arg_deprecated_group',
  430. dict(opt_class=cfg.IntOpt, default=None,
  431. cli_args=['--old-foo=20'], value=20, deps=(None, 'old'))),
  432. ('int_arg_deprecated_group_default',
  433. dict(opt_class=cfg.IntOpt, default=None,
  434. cli_args=['--foo=20'], value=20, deps=(None, 'DEFAULT'))),
  435. ('int_arg_deprecated_group_and_name',
  436. dict(opt_class=cfg.IntOpt, default=None,
  437. cli_args=['--old-oof=20'], value=20, deps=('oof', 'old'))),
  438. ('float_default',
  439. dict(opt_class=cfg.FloatOpt, default=1.0,
  440. cli_args=[], value=1.0, deps=(None, None))),
  441. ('float_arg',
  442. dict(opt_class=cfg.FloatOpt, default=None,
  443. cli_args=['--foo', '2.0'], value=2.0, deps=(None, None))),
  444. ('float_arg_deprecated_name',
  445. dict(opt_class=cfg.FloatOpt, default=None,
  446. cli_args=['--oldfoo', '2.0'], value=2.0, deps=('oldfoo', None))),
  447. ('float_arg_deprecated_group',
  448. dict(opt_class=cfg.FloatOpt, default=None,
  449. cli_args=['--old-foo', '2.0'], value=2.0, deps=(None, 'old'))),
  450. ('float_arg_deprecated_group_default',
  451. dict(opt_class=cfg.FloatOpt, default=None,
  452. cli_args=['--foo', '2.0'], value=2.0, deps=(None, 'DEFAULT'))),
  453. ('float_arg_deprecated_group_and_name',
  454. dict(opt_class=cfg.FloatOpt, default=None,
  455. cli_args=['--old-oof', '2.0'], value=2.0, deps=('oof', 'old'))),
  456. ('float_default_as_integer',
  457. dict(opt_class=cfg.FloatOpt, default=2,
  458. cli_args=['--old-oof', '2.0'], value=2.0, deps=('oof', 'old'))),
  459. ('ipv4addr_arg',
  460. dict(opt_class=IPv4Opt, default=None,
  461. cli_args=['--foo', '192.168.0.1'], value='192.168.0.1',
  462. deps=(None, None))),
  463. ('ipaddr_arg_implicitv4',
  464. dict(opt_class=cfg.IPOpt, default=None,
  465. cli_args=['--foo', '192.168.0.1'], value='192.168.0.1',
  466. deps=(None, None))),
  467. ('ipaddr_arg_implicitv6',
  468. dict(opt_class=cfg.IPOpt, default=None,
  469. cli_args=['--foo', 'abcd:ef::1'], value='abcd:ef::1',
  470. deps=(None, None))),
  471. ('ipv6addr_arg',
  472. dict(opt_class=IPv6Opt, default=None,
  473. cli_args=['--foo', 'abcd:ef::1'], value='abcd:ef::1',
  474. deps=(None, None))),
  475. ('list_default',
  476. dict(opt_class=cfg.ListOpt, default=['bar'],
  477. cli_args=[], value=['bar'], deps=(None, None))),
  478. ('list_arg',
  479. dict(opt_class=cfg.ListOpt, default=None,
  480. cli_args=['--foo', 'blaa,bar'], value=['blaa', 'bar'],
  481. deps=(None, None))),
  482. ('list_arg_with_spaces',
  483. dict(opt_class=cfg.ListOpt, default=None,
  484. cli_args=['--foo', 'blaa ,bar'], value=['blaa', 'bar'],
  485. deps=(None, None))),
  486. ('list_arg_deprecated_name',
  487. dict(opt_class=cfg.ListOpt, default=None,
  488. cli_args=['--oldfoo', 'blaa,bar'], value=['blaa', 'bar'],
  489. deps=('oldfoo', None))),
  490. ('list_arg_deprecated_group',
  491. dict(opt_class=cfg.ListOpt, default=None,
  492. cli_args=['--old-foo', 'blaa,bar'], value=['blaa', 'bar'],
  493. deps=(None, 'old'))),
  494. ('list_arg_deprecated_group_default',
  495. dict(opt_class=cfg.ListOpt, default=None,
  496. cli_args=['--foo', 'blaa,bar'], value=['blaa', 'bar'],
  497. deps=(None, 'DEFAULT'))),
  498. ('list_arg_deprecated_group_and_name',
  499. dict(opt_class=cfg.ListOpt, default=None,
  500. cli_args=['--old-oof', 'blaa,bar'], value=['blaa', 'bar'],
  501. deps=('oof', 'old'))),
  502. ('dict_default',
  503. dict(opt_class=cfg.DictOpt, default={'foo': 'bar'},
  504. cli_args=[], value={'foo': 'bar'}, deps=(None, None))),
  505. ('dict_arg',
  506. dict(opt_class=cfg.DictOpt, default=None,
  507. cli_args=['--foo', 'key1:blaa,key2:bar'],
  508. value={'key1': 'blaa', 'key2': 'bar'}, deps=(None, None))),
  509. ('dict_arg_multiple_keys_last_wins',
  510. dict(opt_class=cfg.DictOpt, default=None,
  511. cli_args=['--foo', 'key1:blaa', '--foo', 'key2:bar'],
  512. value={'key2': 'bar'}, deps=(None, None))),
  513. ('dict_arg_with_spaces',
  514. dict(opt_class=cfg.DictOpt, default=None,
  515. cli_args=['--foo', 'key1:blaa ,key2:bar'],
  516. value={'key1': 'blaa', 'key2': 'bar'}, deps=(None, None))),
  517. ('dict_arg_deprecated_name',
  518. dict(opt_class=cfg.DictOpt, default=None,
  519. cli_args=['--oldfoo', 'key1:blaa', '--oldfoo', 'key2:bar'],
  520. value={'key2': 'bar'}, deps=('oldfoo', None))),
  521. ('dict_arg_deprecated_group',
  522. dict(opt_class=cfg.DictOpt, default=None,
  523. cli_args=['--old-foo', 'key1:blaa,key2:bar'],
  524. value={'key1': 'blaa', 'key2': 'bar'}, deps=(None, 'old'))),
  525. ('dict_arg_deprecated_group2',
  526. dict(opt_class=cfg.DictOpt, default=None,
  527. cli_args=['--old-foo', 'key1:blaa', '--old-foo', 'key2:bar'],
  528. value={'key2': 'bar'}, deps=(None, 'old'))),
  529. ('dict_arg_deprecated_group_default',
  530. dict(opt_class=cfg.DictOpt, default=None,
  531. cli_args=['--foo', 'key1:blaa', '--foo', 'key2:bar'],
  532. value={'key2': 'bar'}, deps=(None, 'DEFAULT'))),
  533. ('dict_arg_deprecated_group_and_name',
  534. dict(opt_class=cfg.DictOpt, default=None,
  535. cli_args=['--old-oof', 'key1:blaa,key2:bar'],
  536. value={'key1': 'blaa', 'key2': 'bar'}, deps=('oof', 'old'))),
  537. ('dict_arg_deprecated_group_and_name2',
  538. dict(opt_class=cfg.DictOpt, default=None,
  539. cli_args=['--old-oof', 'key1:blaa', '--old-oof', 'key2:bar'],
  540. value={'key2': 'bar'}, deps=('oof', 'old'))),
  541. ('port_default',
  542. dict(opt_class=cfg.PortOpt, default=80,
  543. cli_args=[], value=80, deps=(None, None))),
  544. ('port_arg',
  545. dict(opt_class=cfg.PortOpt, default=None,
  546. cli_args=['--foo=80'], value=80, deps=(None, None))),
  547. ('port_arg_deprecated_name',
  548. dict(opt_class=cfg.PortOpt, default=None,
  549. cli_args=['--oldfoo=80'], value=80, deps=('oldfoo', None))),
  550. ('port_arg_deprecated_group',
  551. dict(opt_class=cfg.PortOpt, default=None,
  552. cli_args=['--old-foo=80'], value=80, deps=(None, 'old'))),
  553. ('port_arg_deprecated_group_default',
  554. dict(opt_class=cfg.PortOpt, default=None,
  555. cli_args=['--foo=80'], value=80, deps=(None, 'DEFAULT'))),
  556. ('port_arg_deprecated_group_and_name',
  557. dict(opt_class=cfg.PortOpt, default=None,
  558. cli_args=['--old-oof=80'], value=80, deps=('oof', 'old'))),
  559. ('uri_default',
  560. dict(opt_class=cfg.URIOpt, default='http://example.com',
  561. cli_args=[], value='http://example.com', deps=(None, None))),
  562. ('uri_arg',
  563. dict(opt_class=cfg.URIOpt, default=None,
  564. cli_args=['--foo', 'http://example.com'],
  565. value='http://example.com', deps=(None, None))),
  566. ('multistr_default',
  567. dict(opt_class=cfg.MultiStrOpt, default=['bar'], cli_args=[],
  568. value=['bar'], deps=(None, None))),
  569. ('multistr_arg',
  570. dict(opt_class=cfg.MultiStrOpt, default=None,
  571. cli_args=['--foo', 'blaa', '--foo', 'bar'],
  572. value=['blaa', 'bar'], deps=(None, None))),
  573. ('multistr_arg_deprecated_name',
  574. dict(opt_class=cfg.MultiStrOpt, default=None,
  575. cli_args=['--oldfoo', 'blaa', '--oldfoo', 'bar'],
  576. value=['blaa', 'bar'], deps=('oldfoo', None))),
  577. ('multistr_arg_deprecated_group',
  578. dict(opt_class=cfg.MultiStrOpt, default=None,
  579. cli_args=['--old-foo', 'blaa', '--old-foo', 'bar'],
  580. value=['blaa', 'bar'], deps=(None, 'old'))),
  581. ('multistr_arg_deprecated_group_default',
  582. dict(opt_class=cfg.MultiStrOpt, default=None,
  583. cli_args=['--foo', 'blaa', '--foo', 'bar'],
  584. value=['blaa', 'bar'], deps=(None, 'DEFAULT'))),
  585. ('multistr_arg_deprecated_group_and_name',
  586. dict(opt_class=cfg.MultiStrOpt, default=None,
  587. cli_args=['--old-oof', 'blaa', '--old-oof', 'bar'],
  588. value=['blaa', 'bar'], deps=('oof', 'old'))),
  589. ('multiopt_arg_int',
  590. dict(opt_class=multi_int, default=None,
  591. cli_args=['--foo', '1', '--foo', '2'],
  592. value=[1, 2], deps=(None, None))),
  593. ('multiopt_float_int',
  594. dict(opt_class=multi_float, default=None,
  595. cli_args=['--foo', '1.2', '--foo', '2.3'],
  596. value=[1.2, 2.3], deps=(None, None))),
  597. ('multiopt_string',
  598. dict(opt_class=multi_string, default=None,
  599. cli_args=['--foo', 'bar', '--foo', 'baz'],
  600. value=["bar", "baz"], deps=(None, None))),
  601. ]
  602. def test_cli(self):
  603. self.conf.register_cli_opt(
  604. self.opt_class('foo', default=self.default,
  605. deprecated_name=self.deps[0],
  606. deprecated_group=self.deps[1]))
  607. self.conf(self.cli_args)
  608. self.assertTrue(hasattr(self.conf, 'foo'))
  609. self.assertEqual(self.value, self.conf.foo)
  610. class CliSpecialOptsTestCase(BaseTestCase):
  611. def test_help(self):
  612. self.useFixture(fixtures.MonkeyPatch('sys.stdout', moves.StringIO()))
  613. self.assertRaises(SystemExit, self.conf, ['--help'])
  614. self.assertIn('FOO BAR', sys.stdout.getvalue())
  615. self.assertIn('--version', sys.stdout.getvalue())
  616. self.assertIn('--help', sys.stdout.getvalue())
  617. self.assertIn('--config-file', sys.stdout.getvalue())
  618. def test_version(self):
  619. # In Python 3.4+, argparse prints the version on stdout; before 3.4, it
  620. # printed it on stderr.
  621. if sys.version_info >= (3, 4):
  622. stream_name = 'stdout'
  623. else:
  624. stream_name = 'stderr'
  625. self.useFixture(fixtures.MonkeyPatch("sys.%s" % stream_name,
  626. moves.StringIO()))
  627. self.assertRaises(SystemExit, self.conf, ['--version'])
  628. self.assertIn('1.0', getattr(sys, stream_name).getvalue())
  629. def test_config_file(self):
  630. paths = self.create_tempfiles([('1', '[DEFAULT]'),
  631. ('2', '[DEFAULT]')])
  632. self.conf(['--config-file', paths[0], '--config-file', paths[1]])
  633. self.assertEqual(paths, self.conf.config_file)
  634. class PositionalTestCase(BaseTestCase):
  635. def _do_pos_test(self, opt_class, default, cli_args, value):
  636. self.conf.register_cli_opt(opt_class('foo',
  637. default=default,
  638. positional=True))
  639. self.conf(cli_args)
  640. self.assertTrue(hasattr(self.conf, 'foo'))
  641. self.assertEqual(value, self.conf.foo)
  642. def test_positional_str_none_default(self):
  643. self._do_pos_test(cfg.StrOpt, None, [], None)
  644. def test_positional_str_default(self):
  645. self._do_pos_test(cfg.StrOpt, 'bar', [], 'bar')
  646. def test_positional_str_arg(self):
  647. self._do_pos_test(cfg.StrOpt, None, ['bar'], 'bar')
  648. def test_positional_int_none_default(self):
  649. self._do_pos_test(cfg.IntOpt, None, [], None)
  650. def test_positional_int_default(self):
  651. self._do_pos_test(cfg.IntOpt, 10, [], 10)
  652. def test_positional_int_arg(self):
  653. self._do_pos_test(cfg.IntOpt, None, ['20'], 20)
  654. def test_positional_float_none_default(self):
  655. self._do_pos_test(cfg.FloatOpt, None, [], None)
  656. def test_positional_float_default(self):
  657. self._do_pos_test(cfg.FloatOpt, 1.0, [], 1.0)
  658. def test_positional_float_arg(self):
  659. self._do_pos_test(cfg.FloatOpt, None, ['2.0'], 2.0)
  660. def test_positional_list_none_default(self):
  661. self._do_pos_test(cfg.ListOpt, None, [], None)
  662. def test_positional_list_empty_default(self):
  663. self._do_pos_test(cfg.ListOpt, [], [], [])
  664. def test_positional_list_default(self):
  665. self._do_pos_test(cfg.ListOpt, ['bar'], [], ['bar'])
  666. def test_positional_list_arg(self):
  667. self._do_pos_test(cfg.ListOpt, None,
  668. ['blaa,bar'], ['blaa', 'bar'])
  669. def test_positional_dict_none_default(self):
  670. self._do_pos_test(cfg.DictOpt, None, [], None)
  671. def test_positional_dict_empty_default(self):
  672. self._do_pos_test(cfg.DictOpt, {}, [], {})
  673. def test_positional_dict_default(self):
  674. self._do_pos_test(cfg.DictOpt, {'key1': 'bar'}, [], {'key1': 'bar'})
  675. def test_positional_dict_arg(self):
  676. self._do_pos_test(cfg.DictOpt, None,
  677. ['key1:blaa,key2:bar'],
  678. {'key1': 'blaa', 'key2': 'bar'})
  679. def test_positional_ip_none_default(self):
  680. self._do_pos_test(cfg.IPOpt, None, [], None)
  681. def test_positional_ip_default(self):
  682. self._do_pos_test(cfg.IPOpt, '127.0.0.1', [], '127.0.0.1')
  683. def test_positional_ip_arg(self):
  684. self._do_pos_test(cfg.IPOpt, None, ['127.0.0.1'], '127.0.0.1')
  685. def test_positional_port_none_default(self):
  686. self._do_pos_test(cfg.PortOpt, None, [], None)
  687. def test_positional_port_default(self):
  688. self._do_pos_test(cfg.PortOpt, 80, [], 80)
  689. def test_positional_port_arg(self):
  690. self._do_pos_test(cfg.PortOpt, None, ['443'], 443)
  691. def test_positional_uri_default(self):
  692. self._do_pos_test(cfg.URIOpt, 'http://example.com', [],
  693. 'http://example.com')
  694. def test_positional_uri_none_default(self):
  695. self._do_pos_test(cfg.URIOpt, None, [], None)
  696. def test_positional_uri_arg(self):
  697. self._do_pos_test(cfg.URIOpt, None, ['http://example.com'],
  698. 'http://example.com')
  699. def test_positional_multistr_none_default(self):
  700. self._do_pos_test(cfg.MultiStrOpt, None, [], None)
  701. def test_positional_multistr_empty_default(self):
  702. self._do_pos_test(cfg.MultiStrOpt, [], [], [])
  703. def test_positional_multistr_default(self):
  704. self._do_pos_test(cfg.MultiStrOpt, ['bar'], [], ['bar'])
  705. def test_positional_multistr_arg(self):
  706. self._do_pos_test(cfg.MultiStrOpt, None,
  707. ['blaa', 'bar'], ['blaa', 'bar'])
  708. def test_positional_bool(self):
  709. self.assertRaises(ValueError, cfg.BoolOpt, 'foo', positional=True)
  710. def test_required_positional_opt(self):
  711. self.conf.register_cli_opt(
  712. cfg.StrOpt('foo', required=True, positional=True))
  713. self.conf(['bar'])
  714. self.assertTrue(hasattr(self.conf, 'foo'))
  715. self.assertEqual('bar', self.conf.foo)
  716. def test_missing_required_cli_opt(self):
  717. self.conf.register_cli_opt(
  718. cfg.StrOpt('foo', required=True, positional=True))
  719. self.assertRaises(cfg.RequiredOptError, self.conf, [])
  720. def test_positional_opts_order(self):
  721. self.conf.register_cli_opts((
  722. cfg.StrOpt('command', positional=True),
  723. cfg.StrOpt('arg1', positional=True),
  724. cfg.StrOpt('arg2', positional=True))
  725. )
  726. self.conf(['command', 'arg1', 'arg2'])
  727. self.assertEqual('command', self.conf.command)
  728. self.assertEqual('arg1', self.conf.arg1)
  729. self.assertEqual('arg2', self.conf.arg2)
  730. def test_positional_opt_order(self):
  731. self.conf.register_cli_opt(
  732. cfg.StrOpt('command', positional=True))
  733. self.conf.register_cli_opt(
  734. cfg.StrOpt('arg1', positional=True))
  735. self.conf.register_cli_opt(
  736. cfg.StrOpt('arg2', positional=True))
  737. self.conf(['command', 'arg1', 'arg2'])
  738. self.assertEqual('command', self.conf.command)
  739. self.assertEqual('arg1', self.conf.arg1)
  740. self.assertEqual('arg2', self.conf.arg2)
  741. def test_positional_opt_unregister(self):
  742. command = cfg.StrOpt('command', positional=True)
  743. arg1 = cfg.StrOpt('arg1', positional=True)
  744. arg2 = cfg.StrOpt('arg2', positional=True)
  745. self.conf.register_cli_opt(command)
  746. self.conf.register_cli_opt(arg1)
  747. self.conf.register_cli_opt(arg2)
  748. self.conf(['command', 'arg1', 'arg2'])
  749. self.assertEqual('command', self.conf.command)
  750. self.assertEqual('arg1', self.conf.arg1)
  751. self.assertEqual('arg2', self.conf.arg2)
  752. self.conf.reset()
  753. self.conf.unregister_opt(arg1)
  754. self.conf.unregister_opt(arg2)
  755. arg0 = cfg.StrOpt('arg0', positional=True)
  756. self.conf.register_cli_opt(arg0)
  757. self.conf.register_cli_opt(arg1)
  758. self.conf(['command', 'arg0', 'arg1'])
  759. self.assertEqual('command', self.conf.command)
  760. self.assertEqual('arg0', self.conf.arg0)
  761. self.assertEqual('arg1', self.conf.arg1)
  762. class ConfigFileOptsTestCase(BaseTestCase):
  763. def setUp(self):
  764. super(ConfigFileOptsTestCase, self).setUp()
  765. self.logger = self.useFixture(
  766. fixtures.FakeLogger(
  767. format='%(message)s',
  768. level=logging.WARNING,
  769. nuke_handlers=True,
  770. )
  771. )
  772. def _do_deprecated_test(self, opt_class, value, result, key,
  773. section='DEFAULT',
  774. dname=None, dgroup=None):
  775. self.conf.register_opt(opt_class('newfoo',
  776. deprecated_name=dname,
  777. deprecated_group=dgroup))
  778. paths = self.create_tempfiles([('test',
  779. '[' + section + ']\n' +
  780. key + ' = ' + value + '\n')])
  781. self.conf(['--config-file', paths[0]])
  782. self.assertTrue(hasattr(self.conf, 'newfoo'))
  783. self.assertEqual(result, self.conf.newfoo)
  784. def _do_dname_test_use(self, opt_class, value, result):
  785. self._do_deprecated_test(opt_class, value, result, 'oldfoo',
  786. dname='oldfoo')
  787. def _do_dgroup_test_use(self, opt_class, value, result):
  788. self._do_deprecated_test(opt_class, value, result, 'newfoo',
  789. section='old', dgroup='old')
  790. def _do_default_dgroup_test_use(self, opt_class, value, result):
  791. self._do_deprecated_test(opt_class, value, result, 'newfoo',
  792. section='DEFAULT', dgroup='DEFAULT')
  793. def _do_dgroup_and_dname_test_use(self, opt_class, value, result):
  794. self._do_deprecated_test(opt_class, value, result, 'oof',
  795. section='old', dgroup='old', dname='oof')
  796. def _do_dname_test_ignore(self, opt_class, value, result):
  797. self._do_deprecated_test(opt_class, value, result, 'newfoo',
  798. dname='oldfoo')
  799. def _do_dgroup_test_ignore(self, opt_class, value, result):
  800. self._do_deprecated_test(opt_class, value, result, 'newfoo',
  801. section='DEFAULT', dgroup='old')
  802. def _do_dgroup_and_dname_test_ignore(self, opt_class, value, result):
  803. self._do_deprecated_test(opt_class, value, result, 'oof',
  804. section='old', dgroup='old', dname='oof')
  805. def test_conf_file_str_default(self):
  806. self.conf.register_opt(cfg.StrOpt('foo', default='bar'))
  807. paths = self.create_tempfiles([('test', '[DEFAULT]\n')])
  808. self.conf(['--config-file', paths[0]])
  809. self.assertTrue(hasattr(self.conf, 'foo'))
  810. self.assertEqual('bar', self.conf.foo)
  811. def test_conf_file_str_value(self):
  812. self.conf.register_opt(cfg.StrOpt('foo'))
  813. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = bar\n')])
  814. self.conf(['--config-file', paths[0]])
  815. self.assertTrue(hasattr(self.conf, 'foo'))
  816. self.assertEqual('bar', self.conf.foo)
  817. def test_conf_file_str_value_override(self):
  818. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  819. paths = self.create_tempfiles([('1',
  820. '[DEFAULT]\n'
  821. 'foo = baar\n'),
  822. ('2',
  823. '[DEFAULT]\n'
  824. 'foo = baaar\n')])
  825. self.conf(['--foo', 'bar',
  826. '--config-file', paths[0],
  827. '--config-file', paths[1]])
  828. self.assertTrue(hasattr(self.conf, 'foo'))
  829. self.assertEqual('baaar', self.conf.foo)
  830. def test_conf_file_str_value_override_use_deprecated(self):
  831. """last option should always win, even if last uses deprecated."""
  832. self.conf.register_cli_opt(
  833. cfg.StrOpt('newfoo', deprecated_name='oldfoo'))
  834. paths = self.create_tempfiles([('0',
  835. '[DEFAULT]\n'
  836. 'newfoo = middle\n'),
  837. ('1',
  838. '[DEFAULT]\n'
  839. 'oldfoo = last\n')])
  840. self.conf(['--newfoo', 'first',
  841. '--config-file', paths[0],
  842. '--config-file', paths[1]])
  843. self.assertTrue(hasattr(self.conf, 'newfoo'))
  844. self.assertTrue(hasattr(self.conf, 'oldfoo'))
  845. self.assertEqual('last', self.conf.newfoo)
  846. log_out = self.logger.output
  847. self.assertIn('is deprecated', log_out)
  848. self.assertIn('Use option "newfoo"', log_out)
  849. def test_use_deprecated_for_removal_without_reason(self):
  850. self.conf.register_cli_opt(
  851. cfg.StrOpt('oldfoo',
  852. deprecated_for_removal=True))
  853. paths = self.create_tempfiles([('0',
  854. '[DEFAULT]\n'
  855. 'oldfoo = middle\n')])
  856. self.conf(['--oldfoo', 'first',
  857. '--config-file', paths[0]])
  858. log_out = self.logger.output
  859. self.assertIn('deprecated for removal.', log_out)
  860. def test_use_deprecated_for_removal_with_reason(self):
  861. self.conf.register_cli_opt(
  862. cfg.StrOpt('oldfoo',
  863. deprecated_for_removal=True,
  864. deprecated_reason='a very good reason'))
  865. paths = self.create_tempfiles([('0',
  866. '[DEFAULT]\n'
  867. 'oldfoo = middle\n')])
  868. self.conf(['--oldfoo', 'first',
  869. '--config-file', paths[0]])
  870. log_out = self.logger.output
  871. self.assertIn('deprecated for removal (a very good reason).', log_out)
  872. def test_conf_file_str_use_dname(self):
  873. self._do_dname_test_use(cfg.StrOpt, 'value1', 'value1')
  874. def test_conf_file_str_use_dgroup(self):
  875. self._do_dgroup_test_use(cfg.StrOpt, 'value1', 'value1')
  876. def test_conf_file_str_use_default_dgroup(self):
  877. self._do_default_dgroup_test_use(cfg.StrOpt, 'value1', 'value1')
  878. def test_conf_file_str_use_dgroup_and_dname(self):
  879. self._do_dgroup_and_dname_test_use(cfg.StrOpt, 'value1', 'value1')
  880. def test_conf_file_str_ignore_dname(self):
  881. self._do_dname_test_ignore(cfg.StrOpt, 'value2', 'value2')
  882. def test_conf_file_str_ignore_dgroup(self):
  883. self._do_dgroup_test_ignore(cfg.StrOpt, 'value2', 'value2')
  884. def test_conf_file_str_ignore_dgroup_and_dname(self):
  885. self._do_dgroup_and_dname_test_ignore(cfg.StrOpt, 'value2', 'value2')
  886. def test_conf_file_str_value_with_good_choice_value(self):
  887. self.conf.register_opt(cfg.StrOpt('foo', choices=['bar', 'baz']))
  888. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = bar\n')])
  889. self.conf(['--config-file', paths[0]])
  890. self.assertTrue(hasattr(self.conf, 'foo'))
  891. self.assertEqual('bar', self.conf.foo)
  892. def test_conf_file_bool_default_none(self):
  893. self.conf.register_opt(cfg.BoolOpt('foo'))
  894. paths = self.create_tempfiles([('test',
  895. '[DEFAULT]\n')])
  896. self.conf(['--config-file', paths[0]])
  897. self.assertTrue(hasattr(self.conf, 'foo'))
  898. self.assertIsNone(self.conf.foo)
  899. def test_conf_file_bool_default_false(self):
  900. self.conf.register_opt(cfg.BoolOpt('foo', default=False))
  901. paths = self.create_tempfiles([('test',
  902. '[DEFAULT]\n')])
  903. self.conf(['--config-file', paths[0]])
  904. self.assertTrue(hasattr(self.conf, 'foo'))
  905. self.assertFalse(self.conf.foo)
  906. def test_conf_file_bool_value(self):
  907. self.conf.register_opt(cfg.BoolOpt('foo'))
  908. paths = self.create_tempfiles([('test',
  909. '[DEFAULT]\n'
  910. 'foo = true\n')])
  911. self.conf(['--config-file', paths[0]])
  912. self.assertTrue(hasattr(self.conf, 'foo'))
  913. self.assertTrue(self.conf.foo)
  914. def test_conf_file_bool_cli_value_override(self):
  915. self.conf.register_cli_opt(cfg.BoolOpt('foo'))
  916. paths = self.create_tempfiles([('1',
  917. '[DEFAULT]\n'
  918. 'foo = 0\n')])
  919. self.conf(['--foo',
  920. '--config-file', paths[0]])
  921. self.assertTrue(hasattr(self.conf, 'foo'))
  922. self.assertFalse(self.conf.foo)
  923. def test_conf_file_bool_cli_inverse_override(self):
  924. self.conf.register_cli_opt(cfg.BoolOpt('foo'))
  925. paths = self.create_tempfiles([('1',
  926. '[DEFAULT]\n'
  927. 'foo = true\n')])
  928. self.conf(['--nofoo',
  929. '--config-file', paths[0]])
  930. self.assertTrue(hasattr(self.conf, 'foo'))
  931. self.assertTrue(self.conf.foo)
  932. def test_conf_file_bool_cli_order_override(self):
  933. self.conf.register_cli_opt(cfg.BoolOpt('foo'))
  934. paths = self.create_tempfiles([('1',
  935. '[DEFAULT]\n'
  936. 'foo = false\n')])
  937. self.conf(['--config-file', paths[0],
  938. '--foo'])
  939. self.assertTrue(hasattr(self.conf, 'foo'))
  940. self.assertTrue(self.conf.foo)
  941. def test_conf_file_bool_file_value_override(self):
  942. self.conf.register_cli_opt(cfg.BoolOpt('foo'))
  943. paths = self.create_tempfiles([('1',
  944. '[DEFAULT]\n'
  945. 'foo = 0\n'),
  946. ('2',
  947. '[DEFAULT]\n'
  948. 'foo = yes\n')])
  949. self.conf(['--config-file', paths[0],
  950. '--config-file', paths[1]])
  951. self.assertTrue(hasattr(self.conf, 'foo'))
  952. self.assertTrue(self.conf.foo)
  953. def test_conf_file_bool_use_dname(self):
  954. self._do_dname_test_use(cfg.BoolOpt, 'yes', True)
  955. def test_conf_file_bool_use_dgroup(self):
  956. self._do_dgroup_test_use(cfg.BoolOpt, 'yes', True)
  957. def test_conf_file_bool_use_default_dgroup(self):
  958. self._do_default_dgroup_test_use(cfg.BoolOpt, 'yes', True)
  959. def test_conf_file_bool_use_dgroup_and_dname(self):
  960. self._do_dgroup_and_dname_test_use(cfg.BoolOpt, 'yes', True)
  961. def test_conf_file_bool_ignore_dname(self):
  962. self._do_dname_test_ignore(cfg.BoolOpt, 'no', False)
  963. def test_conf_file_bool_ignore_dgroup(self):
  964. self._do_dgroup_test_ignore(cfg.BoolOpt, 'no', False)
  965. def test_conf_file_bool_ignore_group_and_dname(self):
  966. self._do_dgroup_and_dname_test_ignore(cfg.BoolOpt, 'no', False)
  967. def test_conf_file_int_default(self):
  968. self.conf.register_opt(cfg.IntOpt('foo', default=666))
  969. paths = self.create_tempfiles([('test',
  970. '[DEFAULT]\n')])
  971. self.conf(['--config-file', paths[0]])
  972. self.assertTrue(hasattr(self.conf, 'foo'))
  973. self.assertEqual(666, self.conf.foo)
  974. def test_conf_file_int_string_default_type(self):
  975. self.conf.register_opt(cfg.IntOpt('foo', default='666'))
  976. self.conf([])
  977. self.assertEqual(666, self.conf.foo)
  978. def test_conf_file_int_value(self):
  979. self.conf.register_opt(cfg.IntOpt('foo'))
  980. paths = self.create_tempfiles([('test',
  981. '[DEFAULT]\n'
  982. 'foo = 666\n')])
  983. self.conf(['--config-file', paths[0]])
  984. self.assertTrue(hasattr(self.conf, 'foo'))
  985. self.assertEqual(666, self.conf.foo)
  986. def test_conf_file_int_value_override(self):
  987. self.conf.register_cli_opt(cfg.IntOpt('foo'))
  988. paths = self.create_tempfiles([('1',
  989. '[DEFAULT]\n'
  990. 'foo = 66\n'),
  991. ('2',
  992. '[DEFAULT]\n'
  993. 'foo = 666\n')])
  994. self.conf(['--foo', '6',
  995. '--config-file', paths[0],
  996. '--config-file', paths[1]])
  997. self.assertTrue(hasattr(self.conf, 'foo'))
  998. self.assertEqual(666, self.conf.foo)
  999. def test_conf_file_int_min_max(self):
  1000. self.conf.register_opt(cfg.IntOpt('foo', min=1, max=5))
  1001. paths = self.create_tempfiles([('test',
  1002. '[DEFAULT]\n'
  1003. 'foo = 10\n')])
  1004. self.conf(['--config-file', paths[0]])
  1005. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1006. def test_conf_file_int_min_greater_max(self):
  1007. self.assertRaises(ValueError, cfg.IntOpt, 'foo', min=5, max=1)
  1008. def test_conf_file_int_use_dname(self):
  1009. self._do_dname_test_use(cfg.IntOpt, '66', 66)
  1010. def test_conf_file_int_use_dgroup(self):
  1011. self._do_dgroup_test_use(cfg.IntOpt, '66', 66)
  1012. def test_conf_file_int_use_default_dgroup(self):
  1013. self._do_default_dgroup_test_use(cfg.IntOpt, '66', 66)
  1014. def test_conf_file_int_use_dgroup_and_dname(self):
  1015. self._do_dgroup_and_dname_test_use(cfg.IntOpt, '66', 66)
  1016. def test_conf_file_int_ignore_dname(self):
  1017. self._do_dname_test_ignore(cfg.IntOpt, '64', 64)
  1018. def test_conf_file_int_ignore_dgroup(self):
  1019. self._do_dgroup_test_ignore(cfg.IntOpt, '64', 64)
  1020. def test_conf_file_int_ignore_dgroup_and_dname(self):
  1021. self._do_dgroup_and_dname_test_ignore(cfg.IntOpt, '64', 64)
  1022. def test_conf_file_float_default(self):
  1023. self.conf.register_opt(cfg.FloatOpt('foo', default=6.66))
  1024. paths = self.create_tempfiles([('test',
  1025. '[DEFAULT]\n')])
  1026. self.conf(['--config-file', paths[0]])
  1027. self.assertTrue(hasattr(self.conf, 'foo'))
  1028. self.assertEqual(6.66, self.conf.foo)
  1029. def test_conf_file_float_default_wrong_type(self):
  1030. self.assertRaises(cfg.DefaultValueError, cfg.FloatOpt, 'foo',
  1031. default='foobar6.66')
  1032. def test_conf_file_float_value(self):
  1033. self.conf.register_opt(cfg.FloatOpt('foo'))
  1034. paths = self.create_tempfiles([('test',
  1035. '[DEFAULT]\n'
  1036. 'foo = 6.66\n')])
  1037. self.conf(['--config-file', paths[0]])
  1038. self.assertTrue(hasattr(self.conf, 'foo'))
  1039. self.assertEqual(6.66, self.conf.foo)
  1040. def test_conf_file_float_value_override(self):
  1041. self.conf.register_cli_opt(cfg.FloatOpt('foo'))
  1042. paths = self.create_tempfiles([('1',
  1043. '[DEFAULT]\n'
  1044. 'foo = 6.6\n'),
  1045. ('2',
  1046. '[DEFAULT]\n'
  1047. 'foo = 6.66\n')])
  1048. self.conf(['--foo', '6',
  1049. '--config-file', paths[0],
  1050. '--config-file', paths[1]])
  1051. self.assertTrue(hasattr(self.conf, 'foo'))
  1052. self.assertEqual(6.66, self.conf.foo)
  1053. def test_conf_file_float_use_dname(self):
  1054. self._do_dname_test_use(cfg.FloatOpt, '66.54', 66.54)
  1055. def test_conf_file_float_use_dgroup(self):
  1056. self._do_dgroup_test_use(cfg.FloatOpt, '66.54', 66.54)
  1057. def test_conf_file_float_use_default_dgroup(self):
  1058. self._do_default_dgroup_test_use(cfg.FloatOpt, '66.54', 66.54)
  1059. def test_conf_file_float_use_dgroup_and_dname(self):
  1060. self._do_dgroup_and_dname_test_use(cfg.FloatOpt, '66.54', 66.54)
  1061. def test_conf_file_float_ignore_dname(self):
  1062. self._do_dname_test_ignore(cfg.FloatOpt, '64.54', 64.54)
  1063. def test_conf_file_float_ignore_dgroup(self):
  1064. self._do_dgroup_test_ignore(cfg.FloatOpt, '64.54', 64.54)
  1065. def test_conf_file_float_ignore_dgroup_and_dname(self):
  1066. self._do_dgroup_and_dname_test_ignore(cfg.FloatOpt, '64.54', 64.54)
  1067. def test_conf_file_float_min_max_above_max(self):
  1068. self.conf.register_opt(cfg.FloatOpt('foo', min=1.1, max=5.5))
  1069. paths = self.create_tempfiles([('test',
  1070. '[DEFAULT]\n'
  1071. 'foo = 10.5\n')])
  1072. self.conf(['--config-file', paths[0]])
  1073. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1074. def test_conf_file_float_only_max_above_max(self):
  1075. self.conf.register_opt(cfg.FloatOpt('foo', max=5.5))
  1076. paths = self.create_tempfiles([('test',
  1077. '[DEFAULT]\n'
  1078. 'foo = 10.5\n')])
  1079. self.conf(['--config-file', paths[0]])
  1080. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1081. def test_conf_file_float_min_max_below_min(self):
  1082. self.conf.register_opt(cfg.FloatOpt('foo', min=1.1, max=5.5))
  1083. paths = self.create_tempfiles([('test',
  1084. '[DEFAULT]\n'
  1085. 'foo = 0.5\n')])
  1086. self.conf(['--config-file', paths[0]])
  1087. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1088. def test_conf_file_float_only_min_below_min(self):
  1089. self.conf.register_opt(cfg.FloatOpt('foo', min=1.1))
  1090. paths = self.create_tempfiles([('test',
  1091. '[DEFAULT]\n'
  1092. 'foo = 0.5\n')])
  1093. self.conf(['--config-file', paths[0]])
  1094. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1095. def test_conf_file_float_min_max_in_range(self):
  1096. self.conf.register_opt(cfg.FloatOpt('foo', min=1.1, max=5.5))
  1097. paths = self.create_tempfiles([('test',
  1098. '[DEFAULT]\n'
  1099. 'foo = 4.5\n')])
  1100. self.conf(['--config-file', paths[0]])
  1101. self.assertTrue(hasattr(self.conf, 'foo'))
  1102. self.assertEqual(4.5, self.conf.foo)
  1103. def test_conf_file_float_only_max_in_range(self):
  1104. self.conf.register_opt(cfg.FloatOpt('foo', max=5.5))
  1105. paths = self.create_tempfiles([('test',
  1106. '[DEFAULT]\n'
  1107. 'foo = 4.5\n')])
  1108. self.conf(['--config-file', paths[0]])
  1109. self.assertTrue(hasattr(self.conf, 'foo'))
  1110. self.assertEqual(4.5, self.conf.foo)
  1111. def test_conf_file_float_only_min_in_range(self):
  1112. self.conf.register_opt(cfg.FloatOpt('foo', min=3.5))
  1113. paths = self.create_tempfiles([('test',
  1114. '[DEFAULT]\n'
  1115. 'foo = 4.5\n')])
  1116. self.conf(['--config-file', paths[0]])
  1117. self.assertTrue(hasattr(self.conf, 'foo'))
  1118. self.assertEqual(4.5, self.conf.foo)
  1119. def test_conf_file_float_min_greater_max(self):
  1120. self.assertRaises(ValueError, cfg.FloatOpt, 'foo', min=5.5, max=1.5)
  1121. def test_conf_file_list_default(self):
  1122. self.conf.register_opt(cfg.ListOpt('foo', default=['bar']))
  1123. paths = self.create_tempfiles([('test',
  1124. '[DEFAULT]\n')])
  1125. self.conf(['--config-file', paths[0]])
  1126. self.assertTrue(hasattr(self.conf, 'foo'))
  1127. self.assertEqual(['bar'], self.conf.foo)
  1128. def test_conf_file_list_default_wrong_type(self):
  1129. self.assertRaises(cfg.DefaultValueError, cfg.ListOpt, 'foo',
  1130. default=25)
  1131. def test_conf_file_list_value(self):
  1132. self.conf.register_opt(cfg.ListOpt('foo'))
  1133. paths = self.create_tempfiles([('test',
  1134. '[DEFAULT]\n'
  1135. 'foo = bar\n')])
  1136. self.conf(['--config-file', paths[0]])
  1137. self.assertTrue(hasattr(self.conf, 'foo'))
  1138. self.assertEqual(['bar'], self.conf.foo)
  1139. def test_conf_file_list_value_override(self):
  1140. self.conf.register_cli_opt(cfg.ListOpt('foo'))
  1141. paths = self.create_tempfiles([('1',
  1142. '[DEFAULT]\n'
  1143. 'foo = bar,bar\n'),
  1144. ('2',
  1145. '[DEFAULT]\n'
  1146. 'foo = b,a,r\n')])
  1147. self.conf(['--foo', 'bar',
  1148. '--config-file', paths[0],
  1149. '--config-file', paths[1]])
  1150. self.assertTrue(hasattr(self.conf, 'foo'))
  1151. self.assertEqual(['b', 'a', 'r'], self.conf.foo)
  1152. def test_conf_file_list_item_type(self):
  1153. self.conf.register_cli_opt(cfg.ListOpt('foo',
  1154. item_type=types.Integer()))
  1155. paths = self.create_tempfiles([('1',
  1156. '[DEFAULT]\n'
  1157. 'foo = 1,2\n')])
  1158. self.conf(['--config-file', paths[0]])
  1159. self.assertTrue(hasattr(self.conf, 'foo'))
  1160. self.assertEqual([1, 2], self.conf.foo)
  1161. def test_conf_file_list_item_wrong_type(self):
  1162. self.assertRaises(cfg.DefaultValueError, cfg.ListOpt, 'foo',
  1163. default="bar", item_type=types.Integer())
  1164. def test_conf_file_list_bounds(self):
  1165. self.conf.register_cli_opt(cfg.ListOpt('foo',
  1166. item_type=types.Integer(),
  1167. default="[1,2]",
  1168. bounds=True))
  1169. self.conf([])
  1170. self.assertEqual([1, 2], self.conf.foo)
  1171. def test_conf_file_list_use_dname(self):
  1172. self._do_dname_test_use(cfg.ListOpt, 'a,b,c', ['a', 'b', 'c'])
  1173. def test_conf_file_list_use_dgroup(self):
  1174. self._do_dgroup_test_use(cfg.ListOpt, 'a,b,c', ['a', 'b', 'c'])
  1175. def test_conf_file_list_use_default_dgroup(self):
  1176. self._do_default_dgroup_test_use(cfg.ListOpt, 'a,b,c', ['a', 'b', 'c'])
  1177. def test_conf_file_list_use_dgroup_and_dname(self):
  1178. self._do_dgroup_and_dname_test_use(cfg.ListOpt, 'a,b,c',
  1179. ['a', 'b', 'c'])
  1180. def test_conf_file_list_ignore_dname(self):
  1181. self._do_dname_test_ignore(cfg.ListOpt, 'd,e,f', ['d', 'e', 'f'])
  1182. def test_conf_file_list_ignore_dgroup(self):
  1183. self._do_dgroup_test_ignore(cfg.ListOpt, 'd,e,f', ['d', 'e', 'f'])
  1184. def test_conf_file_list_ignore_dgroup_and_dname(self):
  1185. self._do_dgroup_and_dname_test_ignore(
  1186. cfg.ListOpt, 'd,e,f', ['d', 'e', 'f'])
  1187. def test_conf_file_list_spaces_use_dname(self):
  1188. self._do_dname_test_use(cfg.ListOpt, 'a, b, c', ['a', 'b', 'c'])
  1189. def test_conf_file_list_spaces_use_dgroup(self):
  1190. self._do_dgroup_test_use(cfg.ListOpt, 'a, b, c', ['a', 'b', 'c'])
  1191. def test_conf_file_list_spaces_use_default_dgroup(self):
  1192. self._do_default_dgroup_test_use(
  1193. cfg.ListOpt, 'a, b, c', ['a', 'b', 'c'])
  1194. def test_conf_file_list_spaces_use_dgroup_and_dname(self):
  1195. self._do_dgroup_and_dname_test_use(
  1196. cfg.ListOpt, 'a, b, c', ['a', 'b', 'c'])
  1197. def test_conf_file_list_spaces_ignore_dname(self):
  1198. self._do_dname_test_ignore(cfg.ListOpt, 'd, e, f', ['d', 'e', 'f'])
  1199. def test_conf_file_list_spaces_ignore_dgroup(self):
  1200. self._do_dgroup_test_ignore(cfg.ListOpt, 'd, e, f', ['d', 'e', 'f'])
  1201. def test_conf_file_list_spaces_ignore_dgroup_and_dname(self):
  1202. self._do_dgroup_and_dname_test_ignore(cfg.ListOpt, 'd, e, f',
  1203. ['d', 'e', 'f'])
  1204. def test_conf_file_dict_default(self):
  1205. self.conf.register_opt(cfg.DictOpt('foo', default={'key': 'bar'}))
  1206. paths = self.create_tempfiles([('test',
  1207. '[DEFAULT]\n')])
  1208. self.conf(['--config-file', paths[0]])
  1209. self.assertTrue(hasattr(self.conf, 'foo'))
  1210. self.assertEqual({'key': 'bar'}, self.conf.foo)
  1211. def test_conf_file_dict_value(self):
  1212. self.conf.register_opt(cfg.DictOpt('foo'))
  1213. paths = self.create_tempfiles([('test',
  1214. '[DEFAULT]\n'
  1215. 'foo = key:bar\n')])
  1216. self.conf(['--config-file', paths[0]])
  1217. self.assertTrue(hasattr(self.conf, 'foo'))
  1218. self.assertEqual({'key': 'bar'}, self.conf.foo)
  1219. def test_conf_file_dict_colon_in_value(self):
  1220. self.conf.register_opt(cfg.DictOpt('foo'))
  1221. paths = self.create_tempfiles([('test',
  1222. '[DEFAULT]\n'
  1223. 'foo = key:bar:baz\n')])
  1224. self.conf(['--config-file', paths[0]])
  1225. self.assertTrue(hasattr(self.conf, 'foo'))
  1226. self.assertEqual({'key': 'bar:baz'}, self.conf.foo)
  1227. def test_conf_file_dict_value_no_colon(self):
  1228. self.conf.register_opt(cfg.DictOpt('foo'))
  1229. paths = self.create_tempfiles([('test',
  1230. '[DEFAULT]\n'
  1231. 'foo = key:bar,baz\n')])
  1232. self.conf(['--config-file', paths[0]])
  1233. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1234. self.assertRaises(ValueError, getattr, self.conf, 'foo')
  1235. def test_conf_file_dict_value_duplicate_key(self):
  1236. self.conf.register_opt(cfg.DictOpt('foo'))
  1237. paths = self.create_tempfiles([('test',
  1238. '[DEFAULT]\n'
  1239. 'foo = key:bar,key:baz\n')])
  1240. self.conf(['--config-file', paths[0]])
  1241. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1242. self.assertRaises(ValueError, getattr, self.conf, 'foo')
  1243. def test_conf_file_dict_values_override_deprecated(self):
  1244. self.conf.register_cli_opt(cfg.DictOpt('foo',
  1245. deprecated_name='oldfoo'))
  1246. paths = self.create_tempfiles([('1',
  1247. '[DEFAULT]\n'
  1248. 'foo = key1:bar1\n'),
  1249. ('2',
  1250. '[DEFAULT]\n'
  1251. 'oldfoo = key2:bar2\n'
  1252. 'oldfoo = key3:bar3\n')])
  1253. self.conf(['--foo', 'key0:bar0',
  1254. '--config-file', paths[0],
  1255. '--config-file', paths[1]])
  1256. self.assertTrue(hasattr(self.conf, 'foo'))
  1257. self.assertEqual({'key3': 'bar3'}, self.conf.foo)
  1258. def test_conf_file_dict_deprecated(self):
  1259. self.conf.register_opt(cfg.DictOpt('newfoo', deprecated_name='oldfoo'))
  1260. paths = self.create_tempfiles([('test',
  1261. '[DEFAULT]\n'
  1262. 'oldfoo= key1:bar1\n'
  1263. 'oldfoo = key2:bar2\n')])
  1264. self.conf(['--config-file', paths[0]])
  1265. self.assertTrue(hasattr(self.conf, 'newfoo'))
  1266. self.assertEqual({'key2': 'bar2'}, self.conf.newfoo)
  1267. def test_conf_file_dict_value_override(self):
  1268. self.conf.register_cli_opt(cfg.DictOpt('foo'))
  1269. paths = self.create_tempfiles([('1',
  1270. '[DEFAULT]\n'
  1271. 'foo = key:bar,key2:bar\n'),
  1272. ('2',
  1273. '[DEFAULT]\n'
  1274. 'foo = k1:v1,k2:v2\n')])
  1275. self.conf(['--foo', 'x:y,x2:y2',
  1276. '--config-file', paths[0],
  1277. '--config-file', paths[1]])
  1278. self.assertTrue(hasattr(self.conf, 'foo'))
  1279. self.assertEqual({'k1': 'v1', 'k2': 'v2'}, self.conf.foo)
  1280. def test_conf_file_dict_use_dname(self):
  1281. self._do_dname_test_use(cfg.DictOpt,
  1282. 'k1:a,k2:b,k3:c',
  1283. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1284. def test_conf_file_dict_use_dgroup(self):
  1285. self._do_dgroup_test_use(cfg.DictOpt,
  1286. 'k1:a,k2:b,k3:c',
  1287. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1288. def test_conf_file_dict_use_default_dgroup(self):
  1289. self._do_default_dgroup_test_use(cfg.DictOpt,
  1290. 'k1:a,k2:b,k3:c',
  1291. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1292. def test_conf_file_dict_use_dgroup_and_dname(self):
  1293. self._do_dgroup_and_dname_test_use(cfg.DictOpt,
  1294. 'k1:a,k2:b,k3:c',
  1295. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1296. def test_conf_file_dict_ignore_dname(self):
  1297. self._do_dname_test_ignore(cfg.DictOpt,
  1298. 'k1:d,k2:e,k3:f',
  1299. {'k1': 'd', 'k2': 'e', 'k3': 'f'})
  1300. def test_conf_file_dict_ignore_dgroup(self):
  1301. self._do_dgroup_test_ignore(cfg.DictOpt,
  1302. 'k1:d,k2:e,k3:f',
  1303. {'k1': 'd', 'k2': 'e', 'k3': 'f'})
  1304. def test_conf_file_dict_ignore_dgroup_and_dname(self):
  1305. self._do_dgroup_and_dname_test_ignore(cfg.DictOpt,
  1306. 'k1:d,k2:e,k3:f',
  1307. {'k1': 'd',
  1308. 'k2': 'e',
  1309. 'k3': 'f'})
  1310. def test_conf_file_dict_spaces_use_dname(self):
  1311. self._do_dname_test_use(cfg.DictOpt,
  1312. 'k1:a,k2:b,k3:c',
  1313. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1314. def test_conf_file_dict_spaces_use_dgroup(self):
  1315. self._do_dgroup_test_use(cfg.DictOpt,
  1316. 'k1:a,k2:b,k3:c',
  1317. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1318. def test_conf_file_dict_spaces_use_default_dgroup(self):
  1319. self._do_default_dgroup_test_use(cfg.DictOpt,
  1320. 'k1:a,k2:b,k3:c',
  1321. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1322. def test_conf_file_dict_spaces_use_dgroup_and_dname(self):
  1323. self._do_dgroup_and_dname_test_use(cfg.DictOpt,
  1324. 'k1:a,k2:b,k3:c',
  1325. {'k1': 'a', 'k2': 'b', 'k3': 'c'})
  1326. def test_conf_file_dict_spaces_ignore_dname(self):
  1327. self._do_dname_test_ignore(cfg.DictOpt,
  1328. 'k1:d,k2:e,k3:f',
  1329. {'k1': 'd', 'k2': 'e', 'k3': 'f'})
  1330. def test_conf_file_dict_spaces_ignore_dgroup(self):
  1331. self._do_dgroup_test_ignore(cfg.DictOpt,
  1332. 'k1:d,k2:e,k3:f',
  1333. {'k1': 'd', 'k2': 'e', 'k3': 'f'})
  1334. def test_conf_file_dict_spaces_ignore_dgroup_and_dname(self):
  1335. self._do_dgroup_and_dname_test_ignore(cfg.DictOpt,
  1336. 'k1:d,k2:e,k3:f',
  1337. {'k1': 'd',
  1338. 'k2': 'e',
  1339. 'k3': 'f'})
  1340. def test_conf_file_port_outside_range(self):
  1341. self.conf.register_opt(cfg.PortOpt('foo'))
  1342. paths = self.create_tempfiles([('test',
  1343. '[DEFAULT]\n'
  1344. 'foo = 65536\n')])
  1345. self.conf(['--config-file', paths[0]])
  1346. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1347. def test_conf_file_port_list(self):
  1348. self.conf.register_opt(cfg.ListOpt('foo', item_type=types.Port()))
  1349. paths = self.create_tempfiles([('test',
  1350. '[DEFAULT]\n'
  1351. 'foo = 22, 80\n')])
  1352. self.conf(['--config-file', paths[0]])
  1353. self.assertTrue(hasattr(self.conf, 'foo'))
  1354. self.assertEqual([22, 80], self.conf.foo)
  1355. def test_conf_file_port_list_default(self):
  1356. self.conf.register_opt(cfg.ListOpt('foo', item_type=types.Port(),
  1357. default=[55, 77]))
  1358. paths = self.create_tempfiles([('test',
  1359. '[DEFAULT]\n'
  1360. 'foo = 22, 80\n')])
  1361. self.conf(['--config-file', paths[0]])
  1362. self.assertTrue(hasattr(self.conf, 'foo'))
  1363. self.assertEqual([22, 80], self.conf.foo)
  1364. def test_conf_file_port_list_only_default(self):
  1365. self.conf.register_opt(cfg.ListOpt('foo', item_type=types.Port(),
  1366. default=[55, 77]))
  1367. paths = self.create_tempfiles([('test',
  1368. '[DEFAULT]\n')])
  1369. self.conf(['--config-file', paths[0]])
  1370. self.assertTrue(hasattr(self.conf, 'foo'))
  1371. self.assertEqual([55, 77], self.conf.foo)
  1372. def test_conf_file_port_list_outside_range(self):
  1373. self.conf.register_opt(cfg.ListOpt('foo', item_type=types.Port()))
  1374. paths = self.create_tempfiles([('test',
  1375. '[DEFAULT]\n'
  1376. 'foo = 1,65536\n')])
  1377. self.conf(['--config-file', paths[0]])
  1378. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1379. def test_conf_file_port_min_max_above_max(self):
  1380. self.conf.register_opt(cfg.PortOpt('foo', min=1, max=5))
  1381. paths = self.create_tempfiles([('test',
  1382. '[DEFAULT]\n'
  1383. 'foo = 10\n')])
  1384. self.conf(['--config-file', paths[0]])
  1385. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1386. def test_conf_file_port_only_max_above_max(self):
  1387. self.conf.register_opt(cfg.PortOpt('foo', max=500))
  1388. paths = self.create_tempfiles([('test',
  1389. '[DEFAULT]\n'
  1390. 'foo = 600\n')])
  1391. self.conf(['--config-file', paths[0]])
  1392. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1393. def test_conf_file_port_min_max_below_min(self):
  1394. self.conf.register_opt(cfg.PortOpt('foo', min=100, max=500))
  1395. paths = self.create_tempfiles([('test',
  1396. '[DEFAULT]\n'
  1397. 'foo = 99\n')])
  1398. self.conf(['--config-file', paths[0]])
  1399. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1400. def test_conf_file_port_only_min_below_min(self):
  1401. self.conf.register_opt(cfg.PortOpt('foo', min=1025))
  1402. paths = self.create_tempfiles([('test',
  1403. '[DEFAULT]\n'
  1404. 'foo = 1024\n')])
  1405. self.conf(['--config-file', paths[0]])
  1406. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  1407. def test_conf_file_port_min_max_in_range(self):
  1408. self.conf.register_opt(cfg.PortOpt('foo', min=1025, max=6000))
  1409. paths = self.create_tempfiles([('test',
  1410. '[DEFAULT]\n'
  1411. 'foo = 2500\n')])
  1412. self.conf(['--config-file', paths[0]])
  1413. self.assertTrue(hasattr(self.conf, 'foo'))
  1414. self.assertEqual(2500, self.conf.foo)
  1415. def test_conf_file_port_only_max_in_range(self):
  1416. self.conf.register_opt(cfg.PortOpt('foo', max=5000))
  1417. paths = self.create_tempfiles([('test',
  1418. '[DEFAULT]\n'
  1419. 'foo = 45\n')])
  1420. self.conf(['--config-file', paths[0]])
  1421. self.assertTrue(hasattr(self.conf, 'foo'))
  1422. self.assertEqual(45, self.conf.foo)
  1423. def test_conf_file_port_only_min_in_range(self):
  1424. self.conf.register_opt(cfg.PortOpt('foo', min=35))
  1425. paths = self.create_tempfiles([('test',
  1426. '[DEFAULT]\n'
  1427. 'foo = 45\n')])
  1428. self.conf(['--config-file', paths[0]])
  1429. self.assertTrue(hasattr(self.conf, 'foo'))
  1430. self.assertEqual(45, self.conf.foo)
  1431. def test_conf_file_port_min_greater_max(self):
  1432. self.assertRaises(ValueError, cfg.PortOpt, 'foo', min=55, max=15)
  1433. def test_conf_file_multistr_default(self):
  1434. self.conf.register_opt(cfg.MultiStrOpt('foo', default=['bar']))
  1435. paths = self.create_tempfiles([('test',
  1436. '[DEFAULT]\n')])
  1437. self.conf(['--config-file', paths[0]])
  1438. self.assertTrue(hasattr(self.conf, 'foo'))
  1439. self.assertEqual(['bar'], self.conf.foo)
  1440. def test_conf_file_multistr_value(self):
  1441. self.conf.register_opt(cfg.MultiStrOpt('foo'))
  1442. paths = self.create_tempfiles([('test',
  1443. '[DEFAULT]\n'
  1444. 'foo = bar\n')])
  1445. self.conf(['--config-file', paths[0]])
  1446. self.assertTrue(hasattr(self.conf, 'foo'))
  1447. self.assertEqual(['bar'], self.conf.foo)
  1448. def test_conf_file_multistr_values_append_deprecated(self):
  1449. self.conf.register_cli_opt(cfg.MultiStrOpt('foo',
  1450. deprecated_name='oldfoo'))
  1451. paths = self.create_tempfiles([('1',
  1452. '[DEFAULT]\n'
  1453. 'foo = bar1\n'),
  1454. ('2',
  1455. '[DEFAULT]\n'
  1456. 'oldfoo = bar2\n'
  1457. 'oldfoo = bar3\n')])
  1458. self.conf(['--foo', 'bar0',
  1459. '--config-file', paths[0],
  1460. '--config-file', paths[1]])
  1461. self.assertTrue(hasattr(self.conf, 'foo'))
  1462. self.assertEqual(['bar0', 'bar1', 'bar2', 'bar3'], self.conf.foo)
  1463. def test_conf_file_multistr_values_append(self):
  1464. self.conf.register_cli_opt(cfg.MultiStrOpt('foo'))
  1465. paths = self.create_tempfiles([('1',
  1466. '[DEFAULT]\n'
  1467. 'foo = bar1\n'),
  1468. ('2',
  1469. '[DEFAULT]\n'
  1470. 'foo = bar2\n'
  1471. 'foo = bar3\n')])
  1472. self.conf(['--foo', 'bar0',
  1473. '--config-file', paths[0],
  1474. '--config-file', paths[1]])
  1475. self.assertTrue(hasattr(self.conf, 'foo'))
  1476. self.assertEqual(['bar0', 'bar1', 'bar2', 'bar3'], self.conf.foo)
  1477. def test_conf_file_multistr_deprecated(self):
  1478. self.conf.register_opt(
  1479. cfg.MultiStrOpt('newfoo', deprecated_name='oldfoo'))
  1480. paths = self.create_tempfiles([('test',
  1481. '[DEFAULT]\n'
  1482. 'oldfoo= bar1\n'
  1483. 'oldfoo = bar2\n')])
  1484. self.conf(['--config-file', paths[0]])
  1485. self.assertTrue(hasattr(self.conf, 'newfoo'))
  1486. self.assertEqual(['bar1', 'bar2'], self.conf.newfoo)
  1487. def test_conf_file_multiple_opts(self):
  1488. self.conf.register_opts([cfg.StrOpt('foo'), cfg.StrOpt('bar')])
  1489. paths = self.create_tempfiles([('test',
  1490. '[DEFAULT]\n'
  1491. 'foo = bar\n'
  1492. 'bar = foo\n')])
  1493. self.conf(['--config-file', paths[0]])
  1494. self.assertTrue(hasattr(self.conf, 'foo'))
  1495. self.assertEqual('bar', self.conf.foo)
  1496. self.assertTrue(hasattr(self.conf, 'bar'))
  1497. self.assertEqual('foo', self.conf.bar)
  1498. def test_conf_file_raw_value(self):
  1499. self.conf.register_opt(cfg.StrOpt('foo'))
  1500. paths = self.create_tempfiles([('test',
  1501. '[DEFAULT]\n'
  1502. 'foo = bar-%08x\n')])
  1503. self.conf(['--config-file', paths[0]])
  1504. self.assertTrue(hasattr(self.conf, 'foo'))
  1505. self.assertEqual('bar-%08x', self.conf.foo)
  1506. def test_conf_file_sorted_group(self):
  1507. # Create enough groups for the sorted problem to appear
  1508. for i in range(10):
  1509. group = cfg.OptGroup('group%s' % i, 'options')
  1510. self.conf.register_group(group)
  1511. self.conf.register_cli_opt(cfg.StrOpt('opt1'), group=group)
  1512. paths = self.create_tempfiles(
  1513. [('test', '[group1]\nopt1 = foo\n[group2]\nopt2 = bar\n')])
  1514. self.conf(['--config-file', paths[0]])
  1515. self.assertEqual('foo', self.conf.group1.opt1)
  1516. class ConfigFileReloadTestCase(BaseTestCase):
  1517. def test_conf_files_reload(self):
  1518. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  1519. paths = self.create_tempfiles([('1',
  1520. '[DEFAULT]\n'
  1521. 'foo = baar\n'),
  1522. ('2',
  1523. '[DEFAULT]\n'
  1524. 'foo = baaar\n')])
  1525. self.conf(['--config-file', paths[0]])
  1526. self.assertTrue(hasattr(self.conf, 'foo'))
  1527. self.assertEqual('baar', self.conf.foo)
  1528. shutil.copy(paths[1], paths[0])
  1529. self.conf.reload_config_files()
  1530. self.assertTrue(hasattr(self.conf, 'foo'))
  1531. self.assertEqual('baaar', self.conf.foo)
  1532. def test_conf_files_reload_default(self):
  1533. self.conf.register_cli_opt(cfg.StrOpt('foo1'))
  1534. self.conf.register_cli_opt(cfg.StrOpt('foo2'))
  1535. paths = self.create_tempfiles([('1',
  1536. '[DEFAULT]\n'
  1537. 'foo1 = default1\n'),
  1538. ('2',
  1539. '[DEFAULT]\n'
  1540. 'foo2 = default2\n')])
  1541. paths_change = self.create_tempfiles([('1',
  1542. '[DEFAULT]\n'
  1543. 'foo1 = change_default1\n'),
  1544. ('2',
  1545. '[DEFAULT]\n'
  1546. 'foo2 = change_default2\n')])
  1547. self.conf(args=[], default_config_files=paths)
  1548. self.assertTrue(hasattr(self.conf, 'foo1'))
  1549. self.assertEqual('default1', self.conf.foo1)
  1550. self.assertTrue(hasattr(self.conf, 'foo2'))
  1551. self.assertEqual('default2', self.conf.foo2)
  1552. shutil.copy(paths_change[0], paths[0])
  1553. shutil.copy(paths_change[1], paths[1])
  1554. self.conf.reload_config_files()
  1555. self.assertTrue(hasattr(self.conf, 'foo1'))
  1556. self.assertEqual('change_default1', self.conf.foo1)
  1557. self.assertTrue(hasattr(self.conf, 'foo2'))
  1558. self.assertEqual('change_default2', self.conf.foo2)
  1559. def test_conf_files_reload_file_not_found(self):
  1560. self.conf.register_cli_opt(cfg.StrOpt('foo', required=True))
  1561. paths = self.create_tempfiles([('1',
  1562. '[DEFAULT]\n'
  1563. 'foo = baar\n')])
  1564. self.conf(['--config-file', paths[0]])
  1565. self.assertTrue(hasattr(self.conf, 'foo'))
  1566. self.assertEqual('baar', self.conf.foo)
  1567. os.remove(paths[0])
  1568. self.conf.reload_config_files()
  1569. self.assertTrue(hasattr(self.conf, 'foo'))
  1570. self.assertEqual('baar', self.conf.foo)
  1571. def test_conf_files_reload_error(self):
  1572. self.conf.register_cli_opt(cfg.StrOpt('foo', required=True))
  1573. self.conf.register_cli_opt(cfg.StrOpt('foo1', required=True))
  1574. paths = self.create_tempfiles([('1',
  1575. '[DEFAULT]\n'
  1576. 'foo = test1\n'
  1577. 'foo1 = test11\n'),
  1578. ('2',
  1579. '[DEFAULT]\n'
  1580. 'foo2 = test2\n'
  1581. 'foo3 = test22\n')])
  1582. self.conf(['--config-file', paths[0]])
  1583. self.assertTrue(hasattr(self.conf, 'foo'))
  1584. self.assertEqual('test1', self.conf.foo)
  1585. self.assertTrue(hasattr(self.conf, 'foo1'))
  1586. self.assertEqual('test11', self.conf.foo1)
  1587. shutil.copy(paths[1], paths[0])
  1588. self.conf.reload_config_files()
  1589. self.assertTrue(hasattr(self.conf, 'foo'))
  1590. self.assertEqual('test1', self.conf.foo)
  1591. self.assertTrue(hasattr(self.conf, 'foo1'))
  1592. self.assertEqual('test11', self.conf.foo1)
  1593. class ConfigFileMutateTestCase(BaseTestCase):
  1594. def setUp(self):
  1595. super(ConfigFileMutateTestCase, self).setUp()
  1596. self.my_group = cfg.OptGroup('group', 'group options')
  1597. self.conf.register_group(self.my_group)
  1598. def _test_conf_files_mutate(self):
  1599. paths = self.create_tempfiles([
  1600. ('1', '[DEFAULT]\n'
  1601. 'foo = old_foo\n'
  1602. '[group]\n'
  1603. 'boo = old_boo\n'),
  1604. ('2', '[DEFAULT]\n'
  1605. 'foo = new_foo\n'
  1606. '[group]\n'
  1607. 'boo = new_boo\n')])
  1608. self.conf(['--config-file', paths[0]])
  1609. shutil.copy(paths[1], paths[0])
  1610. return self.conf.mutate_config_files()
  1611. def test_conf_files_mutate_none(self):
  1612. """Test that immutable opts are not reloaded"""
  1613. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  1614. self._test_conf_files_mutate()
  1615. self.assertTrue(hasattr(self.conf, 'foo'))
  1616. self.assertEqual('old_foo', self.conf.foo)
  1617. def test_conf_files_mutate_foo(self):
  1618. """Test that a mutable opt can be reloaded."""
  1619. self.conf.register_cli_opt(cfg.StrOpt('foo', mutable=True))
  1620. self._test_conf_files_mutate()
  1621. self.assertTrue(hasattr(self.conf, 'foo'))
  1622. self.assertEqual('new_foo', self.conf.foo)
  1623. def test_conf_files_mutate_group(self):
  1624. """Test that mutable opts in groups can be reloaded."""
  1625. self.conf.register_cli_opt(cfg.StrOpt('boo', mutable=True),
  1626. group=self.my_group)
  1627. self._test_conf_files_mutate()
  1628. self.assertTrue(hasattr(self.conf, 'group'))
  1629. self.assertTrue(hasattr(self.conf.group, 'boo'))
  1630. self.assertEqual('new_boo', self.conf.group.boo)
  1631. def test_warn_immutability(self):
  1632. self.log_fixture = self.useFixture(fixtures.FakeLogger())
  1633. self.conf.register_cli_opt(cfg.StrOpt('foo', mutable=True))
  1634. self.conf.register_cli_opt(cfg.StrOpt('boo'), group=self.my_group)
  1635. self._test_conf_files_mutate()
  1636. self.assertEqual(
  1637. "Ignoring change to immutable option group.boo\n"
  1638. "Option DEFAULT.foo changed from [old_foo] to [new_foo]\n",
  1639. self.log_fixture.output)
  1640. def test_diff(self):
  1641. self.log_fixture = self.useFixture(fixtures.FakeLogger())
  1642. self.conf.register_cli_opt(cfg.StrOpt('imm'))
  1643. self.conf.register_cli_opt(cfg.StrOpt('blank', mutable=True))
  1644. self.conf.register_cli_opt(cfg.StrOpt('foo', mutable=True))
  1645. self.conf.register_cli_opt(cfg.StrOpt('boo', mutable=True),
  1646. group=self.my_group)
  1647. diff = self._test_conf_files_mutate()
  1648. self.assertEqual(
  1649. {(None, 'foo'): ('old_foo', 'new_foo'),
  1650. ('group', 'boo'): ('old_boo', 'new_boo')},
  1651. diff)
  1652. expected = ("Option DEFAULT.foo changed from [old_foo] to [new_foo]\n"
  1653. "Option group.boo changed from [old_boo] to [new_boo]\n")
  1654. self.assertEqual(expected, self.log_fixture.output)
  1655. def test_hooks_invoked_once(self):
  1656. fresh = {}
  1657. result = [0]
  1658. def foo(conf, foo_fresh):
  1659. self.assertEqual(conf, self.conf)
  1660. self.assertEqual(fresh, foo_fresh)
  1661. result[0] += 1
  1662. self.conf.register_mutate_hook(foo)
  1663. self.conf.register_mutate_hook(foo)
  1664. self._test_conf_files_mutate()
  1665. self.assertEqual(1, result[0])
  1666. def test_hooks_see_new_values(self):
  1667. def foo(conf, fresh):
  1668. # Verify that we see the new value inside the mutate hook.
  1669. self.assertEqual('new_foo', conf.foo)
  1670. self.conf.register_cli_opt(cfg.StrOpt('foo', mutable=True))
  1671. self.conf.register_mutate_hook(foo)
  1672. paths = self.create_tempfiles([
  1673. ('1', '[DEFAULT]\n'
  1674. 'foo = old_foo\n'
  1675. '[group]\n'
  1676. 'boo = old_boo\n'),
  1677. ('2', '[DEFAULT]\n'
  1678. 'foo = new_foo\n'
  1679. '[group]\n'
  1680. 'boo = new_boo\n')])
  1681. self.conf(['--config-file', paths[0]])
  1682. # We access the value once before mutating it to ensure the
  1683. # cache is populated.
  1684. self.assertEqual('old_foo', self.conf.foo)
  1685. shutil.copy(paths[1], paths[0])
  1686. self.conf.mutate_config_files()
  1687. # Verify that we see the new value after mutation is complete.
  1688. self.assertEqual('new_foo', self.conf.foo)
  1689. def test_clear(self):
  1690. """Show that #clear doesn't undeclare opts.
  1691. This justifies not clearing mutate_hooks either. ResetAndClearTestCase
  1692. shows that values are cleared.
  1693. """
  1694. self.conf.register_cli_opt(cfg.StrOpt('cli'))
  1695. self.conf.register_opt(cfg.StrOpt('foo'))
  1696. dests = [info['opt'].dest for info, _ in self.conf._all_opt_infos()]
  1697. self.assertIn('cli', dests)
  1698. self.assertIn('foo', dests)
  1699. self.conf.clear()
  1700. dests = [info['opt'].dest for info, _ in self.conf._all_opt_infos()]
  1701. self.assertIn('cli', dests)
  1702. self.assertIn('foo', dests)
  1703. class OptGroupsTestCase(BaseTestCase):
  1704. def test_arg_group(self):
  1705. blaa_group = cfg.OptGroup('blaa', 'blaa options')
  1706. self.conf.register_group(blaa_group)
  1707. self.conf.register_cli_opt(cfg.StrOpt('foo'), group=blaa_group)
  1708. self.conf(['--blaa-foo', 'bar'])
  1709. self.assertTrue(hasattr(self.conf, 'blaa'))
  1710. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1711. self.assertEqual('bar', self.conf.blaa.foo)
  1712. def test_autocreate_group_by_name(self):
  1713. self.conf.register_cli_opt(cfg.StrOpt('foo'), group='blaa')
  1714. self.conf(['--blaa-foo', 'bar'])
  1715. self.assertTrue(hasattr(self.conf, 'blaa'))
  1716. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1717. self.assertEqual('bar', self.conf.blaa.foo)
  1718. def test_autocreate_group_by_group(self):
  1719. group = cfg.OptGroup(name='blaa', title='Blaa options')
  1720. self.conf.register_cli_opt(cfg.StrOpt('foo'), group=group)
  1721. self.conf(['--blaa-foo', 'bar'])
  1722. self.assertTrue(hasattr(self.conf, 'blaa'))
  1723. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1724. self.assertEqual('bar', self.conf.blaa.foo)
  1725. def test_autocreate_title(self):
  1726. blaa_group = cfg.OptGroup('blaa')
  1727. self.assertEqual(blaa_group.title, 'blaa options')
  1728. def test_arg_group_by_name(self):
  1729. self.conf.register_group(cfg.OptGroup('blaa'))
  1730. self.conf.register_cli_opt(cfg.StrOpt('foo'), group='blaa')
  1731. self.conf(['--blaa-foo', 'bar'])
  1732. self.assertTrue(hasattr(self.conf, 'blaa'))
  1733. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1734. self.assertEqual('bar', self.conf.blaa.foo)
  1735. def test_arg_group_with_default(self):
  1736. self.conf.register_group(cfg.OptGroup('blaa'))
  1737. self.conf.register_cli_opt(
  1738. cfg.StrOpt('foo', default='bar'), group='blaa')
  1739. self.conf([])
  1740. self.assertTrue(hasattr(self.conf, 'blaa'))
  1741. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1742. self.assertEqual('bar', self.conf.blaa.foo)
  1743. def test_arg_group_with_conf_and_group_opts(self):
  1744. self.conf.register_cli_opt(cfg.StrOpt('conf'), group='blaa')
  1745. self.conf.register_cli_opt(cfg.StrOpt('group'), group='blaa')
  1746. self.conf(['--blaa-conf', 'foo', '--blaa-group', 'bar'])
  1747. self.assertTrue(hasattr(self.conf, 'blaa'))
  1748. self.assertTrue(hasattr(self.conf.blaa, 'conf'))
  1749. self.assertEqual('foo', self.conf.blaa.conf)
  1750. self.assertTrue(hasattr(self.conf.blaa, 'group'))
  1751. self.assertEqual('bar', self.conf.blaa.group)
  1752. def test_arg_group_in_config_file(self):
  1753. self.conf.register_group(cfg.OptGroup('blaa'))
  1754. self.conf.register_opt(cfg.StrOpt('foo'), group='blaa')
  1755. paths = self.create_tempfiles([('test',
  1756. '[blaa]\n'
  1757. 'foo = bar\n')])
  1758. self.conf(['--config-file', paths[0]])
  1759. self.assertTrue(hasattr(self.conf, 'blaa'))
  1760. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1761. self.assertEqual('bar', self.conf.blaa.foo)
  1762. def test_arg_group_in_config_file_with_deprecated_name(self):
  1763. self.conf.register_group(cfg.OptGroup('blaa'))
  1764. self.conf.register_opt(cfg.StrOpt('foo', deprecated_name='oldfoo'),
  1765. group='blaa')
  1766. paths = self.create_tempfiles([('test',
  1767. '[blaa]\n'
  1768. 'oldfoo = bar\n')])
  1769. self.conf(['--config-file', paths[0]])
  1770. self.assertTrue(hasattr(self.conf, 'blaa'))
  1771. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1772. self.assertEqual('bar', self.conf.blaa.foo)
  1773. def test_arg_group_in_config_file_with_deprecated_group(self):
  1774. self.conf.register_group(cfg.OptGroup('blaa'))
  1775. self.conf.register_opt(cfg.StrOpt('foo', deprecated_group='DEFAULT'),
  1776. group='blaa')
  1777. paths = self.create_tempfiles([('test',
  1778. '[DEFAULT]\n'
  1779. 'foo = bar\n')])
  1780. self.conf(['--config-file', paths[0]])
  1781. self.assertTrue(hasattr(self.conf, 'blaa'))
  1782. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1783. self.assertEqual('bar', self.conf.blaa.foo)
  1784. def test_arg_group_in_config_file_with_deprecated_group_and_name(self):
  1785. self.conf.register_group(cfg.OptGroup('blaa'))
  1786. self.conf.register_opt(
  1787. cfg.StrOpt('foo', deprecated_group='DEFAULT',
  1788. deprecated_name='oldfoo'), group='blaa')
  1789. paths = self.create_tempfiles([('test',
  1790. '[DEFAULT]\n'
  1791. 'oldfoo = bar\n')])
  1792. self.conf(['--config-file', paths[0]])
  1793. self.assertTrue(hasattr(self.conf, 'blaa'))
  1794. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1795. self.assertEqual('bar', self.conf.blaa.foo)
  1796. def test_arg_group_in_config_file_override_deprecated_name(self):
  1797. self.conf.register_group(cfg.OptGroup('blaa'))
  1798. self.conf.register_opt(cfg.StrOpt('foo', deprecated_name='oldfoo'),
  1799. group='blaa')
  1800. paths = self.create_tempfiles([('test',
  1801. '[blaa]\n'
  1802. 'foo = bar\n'
  1803. 'oldfoo = blabla\n')])
  1804. self.conf(['--config-file', paths[0]])
  1805. self.assertTrue(hasattr(self.conf, 'blaa'))
  1806. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1807. self.assertEqual('bar', self.conf.blaa.foo)
  1808. def test_arg_group_in_config_file_override_deprecated_group(self):
  1809. self.conf.register_group(cfg.OptGroup('blaa'))
  1810. self.conf.register_opt(cfg.StrOpt('foo', deprecated_group='DEFAULT'),
  1811. group='blaa')
  1812. paths = self.create_tempfiles([('test',
  1813. '[DEFAULT]\n'
  1814. 'foo = blabla\n'
  1815. '[blaa]\n'
  1816. 'foo = bar\n')])
  1817. self.conf(['--config-file', paths[0]])
  1818. self.assertTrue(hasattr(self.conf, 'blaa'))
  1819. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1820. self.assertEqual('bar', self.conf.blaa.foo)
  1821. def test_arg_group_in_config_file_override_deprecated_group_and_name(self):
  1822. self.conf.register_group(cfg.OptGroup('blaa'))
  1823. self.conf.register_opt(
  1824. cfg.StrOpt('foo', deprecated_group='DEFAULT',
  1825. deprecated_name='oldfoo'), group='blaa')
  1826. paths = self.create_tempfiles([('test',
  1827. '[DEFAULT]\n'
  1828. 'oldfoo = blabla\n'
  1829. '[blaa]\n'
  1830. 'foo = bar\n')])
  1831. self.conf(['--config-file', paths[0]])
  1832. self.assertTrue(hasattr(self.conf, 'blaa'))
  1833. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1834. self.assertEqual('bar', self.conf.blaa.foo)
  1835. def test_arg_group_in_config_file_with_capital_name(self):
  1836. self.conf.register_group(cfg.OptGroup('blaa'))
  1837. self.conf.register_opt(cfg.StrOpt('foo'), group='blaa')
  1838. paths = self.create_tempfiles([('test',
  1839. '[BLAA]\n'
  1840. 'foo = bar\n')])
  1841. self.conf(['--config-file', paths[0]])
  1842. self.assertFalse(hasattr(self.conf, 'BLAA'))
  1843. self.assertTrue(hasattr(self.conf, 'blaa'))
  1844. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  1845. self.assertEqual('bar', self.conf.blaa.foo)
  1846. def test_arg_group_in_config_file_with_capital_name_on_legacy_code(self):
  1847. self.conf.register_group(cfg.OptGroup('BLAA'))
  1848. self.conf.register_opt(cfg.StrOpt('foo'), group='BLAA')
  1849. paths = self.create_tempfiles([('test',
  1850. '[BLAA]\n'
  1851. 'foo = bar\n')])
  1852. self.conf(['--config-file', paths[0]])
  1853. self.assertFalse(hasattr(self.conf, 'blaa'))
  1854. self.assertTrue(hasattr(self.conf, 'BLAA'))
  1855. self.assertTrue(hasattr(self.conf.BLAA, 'foo'))
  1856. self.assertEqual('bar', self.conf.BLAA.foo)
  1857. class MappingInterfaceTestCase(BaseTestCase):
  1858. def test_mapping_interface(self):
  1859. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  1860. self.conf(['--foo', 'bar'])
  1861. self.assertIn('foo', self.conf)
  1862. self.assertIn('config_file', self.conf)
  1863. self.assertEqual(len(self.conf), 3)
  1864. self.assertEqual('bar', self.conf['foo'])
  1865. self.assertEqual('bar', self.conf.get('foo'))
  1866. self.assertIn('bar', list(self.conf.values()))
  1867. def test_mapping_interface_with_group(self):
  1868. self.conf.register_group(cfg.OptGroup('blaa'))
  1869. self.conf.register_cli_opt(cfg.StrOpt('foo'), group='blaa')
  1870. self.conf(['--blaa-foo', 'bar'])
  1871. self.assertIn('blaa', self.conf)
  1872. self.assertIn('foo', list(self.conf['blaa']))
  1873. self.assertEqual(len(self.conf['blaa']), 1)
  1874. self.assertEqual('bar', self.conf['blaa']['foo'])
  1875. self.assertEqual('bar', self.conf['blaa'].get('foo'))
  1876. self.assertIn('bar', self.conf['blaa'].values())
  1877. self.assertEqual(self.conf['blaa'], self.conf.blaa)
  1878. class OptNameSeparatorTestCase(BaseTestCase):
  1879. # NOTE(bnemec): The broken* values in these scenarios are opt dests or
  1880. # config file names that are not actually valid, but can be added via a
  1881. # DeprecatedOpt. The tests only verify that those values do not end up
  1882. # in the final config object.
  1883. scenarios = [
  1884. ('hyphen',
  1885. dict(opt_name='foo-bar',
  1886. opt_dest='foo_bar',
  1887. broken_opt_dest='foo-bar',
  1888. cf_name='foo_bar',
  1889. broken_cf_name='foo-bar',
  1890. cli_name='foo-bar',
  1891. hyphen=True)),
  1892. ('underscore',
  1893. dict(opt_name='foo_bar',
  1894. opt_dest='foo_bar',
  1895. broken_opt_dest='foo-bar',
  1896. cf_name='foo_bar',
  1897. broken_cf_name='foo-bar',
  1898. cli_name='foo_bar',
  1899. hyphen=False)),
  1900. ]
  1901. def test_attribute_and_key_name(self):
  1902. self.conf.register_opt(cfg.StrOpt(self.opt_name))
  1903. self.assertTrue(hasattr(self.conf, self.opt_dest))
  1904. self.assertFalse(hasattr(self.conf, self.broken_opt_dest))
  1905. self.assertIn(self.opt_dest, self.conf)
  1906. self.assertNotIn(self.broken_opt_dest, self.conf)
  1907. def test_cli_opt_name(self):
  1908. self.conf.register_cli_opt(cfg.BoolOpt(self.opt_name))
  1909. self.conf(['--' + self.cli_name])
  1910. self.assertTrue(getattr(self.conf, self.opt_dest))
  1911. def test_config_file_opt_name(self):
  1912. self.conf.register_opt(cfg.BoolOpt(self.opt_name))
  1913. paths = self.create_tempfiles([('test',
  1914. '[DEFAULT]\n' +
  1915. self.cf_name + ' = True\n' +
  1916. self.broken_cf_name + ' = False\n')])
  1917. self.conf(['--config-file', paths[0]])
  1918. self.assertTrue(getattr(self.conf, self.opt_dest))
  1919. def test_deprecated_name(self):
  1920. self.conf.register_opt(cfg.StrOpt('foobar',
  1921. deprecated_name=self.opt_name))
  1922. self.assertTrue(hasattr(self.conf, 'foobar'))
  1923. # TODO(mtreinish): Add a check on the log message
  1924. self.assertTrue(hasattr(self.conf, self.opt_dest))
  1925. self.assertFalse(hasattr(self.conf, self.broken_opt_dest))
  1926. self.assertIn('foobar', self.conf)
  1927. self.assertNotIn(self.opt_dest, self.conf)
  1928. self.assertNotIn(self.broken_opt_dest, self.conf)
  1929. def test_deprecated_name_cli(self):
  1930. self.conf.register_cli_opt(cfg.BoolOpt('foobar',
  1931. deprecated_name=self.opt_name))
  1932. self.conf(['--' + self.cli_name])
  1933. self.assertTrue(self.conf.foobar)
  1934. def test_deprecated_name_config_file(self):
  1935. self.conf.register_opt(cfg.BoolOpt('foobar',
  1936. deprecated_name=self.opt_name))
  1937. paths = self.create_tempfiles([('test',
  1938. '[DEFAULT]\n' +
  1939. self.cf_name + ' = True\n')])
  1940. self.conf(['--config-file', paths[0]])
  1941. self.assertTrue(self.conf.foobar)
  1942. def test_deprecated_opts(self):
  1943. oldopts = [cfg.DeprecatedOpt(self.opt_name)]
  1944. self.conf.register_opt(cfg.StrOpt('foobar',
  1945. deprecated_opts=oldopts))
  1946. self.assertTrue(hasattr(self.conf, 'foobar'))
  1947. # TODO(mtreinish): Add check for the log message
  1948. self.assertTrue(hasattr(self.conf, self.opt_dest))
  1949. self.assertFalse(hasattr(self.conf, self.broken_opt_dest))
  1950. self.assertIn('foobar', self.conf)
  1951. self.assertNotIn(self.opt_dest, self.conf)
  1952. self.assertNotIn(self.broken_opt_dest, self.conf)
  1953. def test_deprecated_opts_cli(self):
  1954. oldopts = [cfg.DeprecatedOpt(self.opt_name)]
  1955. self.conf.register_cli_opt(cfg.BoolOpt('foobar',
  1956. deprecated_opts=oldopts))
  1957. self.conf(['--' + self.cli_name])
  1958. self.assertTrue(self.conf.foobar)
  1959. def test_deprecated_opts_config_file(self):
  1960. oldopts = [cfg.DeprecatedOpt(self.opt_name)]
  1961. self.conf.register_opt(cfg.BoolOpt('foobar',
  1962. deprecated_opts=oldopts))
  1963. paths = self.create_tempfiles([('test',
  1964. '[DEFAULT]\n' +
  1965. self.cf_name + ' = True\n')])
  1966. self.conf(['--config-file', paths[0]])
  1967. self.assertTrue(self.conf.foobar)
  1968. class ReRegisterOptTestCase(BaseTestCase):
  1969. def test_conf_file_re_register_opt(self):
  1970. opt = cfg.StrOpt('foo')
  1971. self.assertTrue(self.conf.register_opt(opt))
  1972. self.assertFalse(self.conf.register_opt(opt))
  1973. def test_conf_file_re_register_opt_in_group(self):
  1974. group = cfg.OptGroup('blaa')
  1975. self.conf.register_group(group)
  1976. self.conf.register_group(group) # not an error
  1977. opt = cfg.StrOpt('foo')
  1978. self.assertTrue(self.conf.register_opt(opt, group=group))
  1979. self.assertFalse(self.conf.register_opt(opt, group='blaa'))
  1980. class RegisterOptNameTestCase(BaseTestCase):
  1981. def test_register_opt_with_disallow_name(self):
  1982. for name in cfg.ConfigOpts.disallow_names:
  1983. opt = cfg.StrOpt(name)
  1984. self.assertRaises(ValueError, self.conf.register_opt, opt)
  1985. class TemplateSubstitutionTestCase(BaseTestCase):
  1986. def _prep_test_str_sub(self, foo_default=None, bar_default=None):
  1987. self.conf.register_cli_opt(cfg.StrOpt('foo', default=foo_default))
  1988. self.conf.register_cli_opt(cfg.StrOpt('bar', default=bar_default))
  1989. def _assert_str_sub(self):
  1990. self.assertTrue(hasattr(self.conf, 'bar'))
  1991. self.assertEqual('blaa', self.conf.bar)
  1992. def test_str_sub_default_from_default(self):
  1993. self._prep_test_str_sub(foo_default='blaa', bar_default='$foo')
  1994. self.conf([])
  1995. self._assert_str_sub()
  1996. def test_str_sub_default_from_default_recurse(self):
  1997. self.conf.register_cli_opt(cfg.StrOpt('blaa', default='blaa'))
  1998. self._prep_test_str_sub(foo_default='$blaa', bar_default='$foo')
  1999. self.conf([])
  2000. self._assert_str_sub()
  2001. def test_str_sub_default_from_arg(self):
  2002. self._prep_test_str_sub(bar_default='$foo')
  2003. self.conf(['--foo', 'blaa'])
  2004. self._assert_str_sub()
  2005. def test_str_sub_default_from_config_file(self):
  2006. self._prep_test_str_sub(bar_default='$foo')
  2007. paths = self.create_tempfiles([('test',
  2008. '[DEFAULT]\n'
  2009. 'foo = blaa\n')])
  2010. self.conf(['--config-file', paths[0]])
  2011. self._assert_str_sub()
  2012. def test_str_sub_arg_from_default(self):
  2013. self._prep_test_str_sub(foo_default='blaa')
  2014. self.conf(['--bar', '$foo'])
  2015. self._assert_str_sub()
  2016. def test_str_sub_arg_from_arg(self):
  2017. self._prep_test_str_sub()
  2018. self.conf(['--foo', 'blaa', '--bar', '$foo'])
  2019. self._assert_str_sub()
  2020. def test_str_sub_arg_from_config_file(self):
  2021. self._prep_test_str_sub()
  2022. paths = self.create_tempfiles([('test',
  2023. '[DEFAULT]\n'
  2024. 'foo = blaa\n')])
  2025. self.conf(['--config-file', paths[0], '--bar=$foo'])
  2026. self._assert_str_sub()
  2027. def test_str_sub_config_file_from_default(self):
  2028. self._prep_test_str_sub(foo_default='blaa')
  2029. paths = self.create_tempfiles([('test',
  2030. '[DEFAULT]\n'
  2031. 'bar = $foo\n')])
  2032. self.conf(['--config-file', paths[0]])
  2033. self._assert_str_sub()
  2034. def test_str_sub_config_file_from_arg(self):
  2035. self._prep_test_str_sub()
  2036. paths = self.create_tempfiles([('test',
  2037. '[DEFAULT]\n'
  2038. 'bar = $foo\n')])
  2039. self.conf(['--config-file', paths[0], '--foo=blaa'])
  2040. self._assert_str_sub()
  2041. def test_str_sub_config_file_from_config_file(self):
  2042. self._prep_test_str_sub()
  2043. paths = self.create_tempfiles([('test',
  2044. '[DEFAULT]\n'
  2045. 'bar = $foo\n'
  2046. 'foo = blaa\n')])
  2047. self.conf(['--config-file', paths[0]])
  2048. self._assert_str_sub()
  2049. def test_str_sub_with_dollar_escape_char(self):
  2050. self._prep_test_str_sub()
  2051. paths = self.create_tempfiles([('test',
  2052. '[DEFAULT]\n'
  2053. 'bar=foo-somethin$$k2\n')])
  2054. self.conf(['--config-file', paths[0]])
  2055. self.assertTrue(hasattr(self.conf, 'bar'))
  2056. self.assertEqual('foo-somethin$k2', self.conf.bar)
  2057. def test_str_sub_with_backslash_escape_char(self):
  2058. self._prep_test_str_sub()
  2059. paths = self.create_tempfiles([('test',
  2060. '[DEFAULT]\n'
  2061. 'bar=foo-somethin\$k2\n')])
  2062. self.conf(['--config-file', paths[0]])
  2063. self.assertTrue(hasattr(self.conf, 'bar'))
  2064. self.assertEqual('foo-somethin$k2', self.conf.bar)
  2065. def test_str_sub_group_from_default(self):
  2066. self.conf.register_cli_opt(cfg.StrOpt('foo', default='blaa'))
  2067. self.conf.register_group(cfg.OptGroup('ba'))
  2068. self.conf.register_cli_opt(cfg.StrOpt('r', default='$foo'), group='ba')
  2069. self.conf([])
  2070. self.assertTrue(hasattr(self.conf, 'ba'))
  2071. self.assertTrue(hasattr(self.conf.ba, 'r'))
  2072. self.assertEqual('blaa', self.conf.ba.r)
  2073. def test_str_sub_set_default(self):
  2074. self._prep_test_str_sub()
  2075. self.conf.set_default('bar', '$foo')
  2076. self.conf.set_default('foo', 'blaa')
  2077. self.conf([])
  2078. self._assert_str_sub()
  2079. def test_str_sub_set_override(self):
  2080. self._prep_test_str_sub()
  2081. self.conf.set_override('bar', '$foo')
  2082. self.conf.set_override('foo', 'blaa')
  2083. self.conf([])
  2084. self._assert_str_sub()
  2085. def _prep_test_str_int_sub(self, foo_default=None, bar_default=None):
  2086. self.conf.register_cli_opt(cfg.StrOpt('foo', default=foo_default))
  2087. self.conf.register_cli_opt(cfg.IntOpt('bar', default=bar_default))
  2088. def _assert_int_sub(self):
  2089. self.assertTrue(hasattr(self.conf, 'bar'))
  2090. self.assertEqual(123, self.conf.bar)
  2091. def test_sub_default_from_default(self):
  2092. self._prep_test_str_int_sub(foo_default='123', bar_default='$foo')
  2093. self.conf([])
  2094. self._assert_int_sub()
  2095. def test_sub_default_from_default_recurse(self):
  2096. self.conf.register_cli_opt(cfg.StrOpt('blaa', default='123'))
  2097. self._prep_test_str_int_sub(foo_default='$blaa', bar_default='$foo')
  2098. self.conf([])
  2099. self._assert_int_sub()
  2100. def test_sub_default_from_arg(self):
  2101. self._prep_test_str_int_sub(bar_default='$foo')
  2102. self.conf(['--foo', '123'])
  2103. self._assert_int_sub()
  2104. def test_sub_default_from_config_file(self):
  2105. self._prep_test_str_int_sub(bar_default='$foo')
  2106. paths = self.create_tempfiles([('test',
  2107. '[DEFAULT]\n'
  2108. 'foo = 123\n')])
  2109. self.conf(['--config-file', paths[0]])
  2110. self._assert_int_sub()
  2111. def test_sub_arg_from_default(self):
  2112. self._prep_test_str_int_sub(foo_default='123')
  2113. self.conf(['--bar', '$foo'])
  2114. self._assert_int_sub()
  2115. def test_sub_arg_from_arg(self):
  2116. self._prep_test_str_int_sub()
  2117. self.conf(['--foo', '123', '--bar', '$foo'])
  2118. self._assert_int_sub()
  2119. def test_sub_arg_from_config_file(self):
  2120. self._prep_test_str_int_sub()
  2121. paths = self.create_tempfiles([('test',
  2122. '[DEFAULT]\n'
  2123. 'foo = 123\n')])
  2124. self.conf(['--config-file', paths[0], '--bar=$foo'])
  2125. self._assert_int_sub()
  2126. def test_sub_config_file_from_default(self):
  2127. self._prep_test_str_int_sub(foo_default='123')
  2128. paths = self.create_tempfiles([('test',
  2129. '[DEFAULT]\n'
  2130. 'bar = $foo\n')])
  2131. self.conf(['--config-file', paths[0]])
  2132. self._assert_int_sub()
  2133. def test_sub_config_file_from_arg(self):
  2134. self._prep_test_str_int_sub()
  2135. paths = self.create_tempfiles([('test',
  2136. '[DEFAULT]\n'
  2137. 'bar = $foo\n')])
  2138. self.conf(['--config-file', paths[0], '--foo=123'])
  2139. self._assert_int_sub()
  2140. def test_sub_config_file_from_config_file(self):
  2141. self._prep_test_str_int_sub()
  2142. paths = self.create_tempfiles([('test',
  2143. '[DEFAULT]\n'
  2144. 'bar = $foo\n'
  2145. 'foo = 123\n')])
  2146. self.conf(['--config-file', paths[0]])
  2147. self._assert_int_sub()
  2148. def test_sub_group_from_default(self):
  2149. self.conf.register_cli_opt(cfg.StrOpt('foo', default='123'))
  2150. self.conf.register_group(cfg.OptGroup('ba'))
  2151. self.conf.register_cli_opt(cfg.IntOpt('r', default='$foo'), group='ba')
  2152. self.conf([])
  2153. self.assertTrue(hasattr(self.conf, 'ba'))
  2154. self.assertTrue(hasattr(self.conf.ba, 'r'))
  2155. self.assertEqual('123', self.conf.foo)
  2156. self.assertEqual(123, self.conf.ba.r)
  2157. def test_sub_group_from_default_deprecated(self):
  2158. self.conf.register_group(cfg.OptGroup('ba'))
  2159. self.conf.register_cli_opt(cfg.StrOpt(
  2160. 'foo', default='123', deprecated_group='DEFAULT'), group='ba')
  2161. self.conf.register_cli_opt(cfg.IntOpt('r', default='$foo'), group='ba')
  2162. self.conf([])
  2163. self.assertTrue(hasattr(self.conf, 'ba'))
  2164. self.assertTrue(hasattr(self.conf.ba, 'foo'))
  2165. self.assertEqual('123', self.conf.ba.foo)
  2166. self.assertTrue(hasattr(self.conf.ba, 'r'))
  2167. self.assertEqual(123, self.conf.ba.r)
  2168. def test_sub_group_from_args_deprecated(self):
  2169. self.conf.register_group(cfg.OptGroup('ba'))
  2170. self.conf.register_cli_opt(cfg.StrOpt(
  2171. 'foo', default='123', deprecated_group='DEFAULT'), group='ba')
  2172. self.conf.register_cli_opt(cfg.IntOpt('r', default='$foo'), group='ba')
  2173. self.conf(['--ba-foo=4242'])
  2174. self.assertTrue(hasattr(self.conf, 'ba'))
  2175. self.assertTrue(hasattr(self.conf.ba, 'foo'))
  2176. self.assertTrue(hasattr(self.conf.ba, 'r'))
  2177. self.assertEqual('4242', self.conf.ba.foo)
  2178. self.assertEqual(4242, self.conf.ba.r)
  2179. def test_sub_group_from_configfile_deprecated(self):
  2180. self.conf.register_group(cfg.OptGroup('ba'))
  2181. self.conf.register_cli_opt(cfg.StrOpt(
  2182. 'foo', default='123', deprecated_group='DEFAULT'), group='ba')
  2183. self.conf.register_cli_opt(cfg.IntOpt('r', default='$foo'), group='ba')
  2184. paths = self.create_tempfiles([('test',
  2185. '[DEFAULT]\n'
  2186. 'foo=4242\n')])
  2187. self.conf(['--config-file', paths[0]])
  2188. self.assertTrue(hasattr(self.conf, 'ba'))
  2189. self.assertTrue(hasattr(self.conf.ba, 'foo'))
  2190. self.assertTrue(hasattr(self.conf.ba, 'r'))
  2191. self.assertEqual('4242', self.conf.ba.foo)
  2192. self.assertEqual(4242, self.conf.ba.r)
  2193. def test_dict_sub_default_from_default(self):
  2194. self.conf.register_cli_opt(cfg.StrOpt('foo', default='floo'))
  2195. self.conf.register_cli_opt(cfg.StrOpt('bar', default='blaa'))
  2196. self.conf.register_cli_opt(cfg.DictOpt('dt', default={'$foo': '$bar'}))
  2197. self.conf([])
  2198. self.assertEqual('blaa', self.conf.dt['floo'])
  2199. def test_dict_sub_default_from_default_multi(self):
  2200. self.conf.register_cli_opt(cfg.StrOpt('foo', default='floo'))
  2201. self.conf.register_cli_opt(cfg.StrOpt('bar', default='blaa'))
  2202. self.conf.register_cli_opt(cfg.StrOpt('goo', default='gloo'))
  2203. self.conf.register_cli_opt(cfg.StrOpt('har', default='hlaa'))
  2204. self.conf.register_cli_opt(cfg.DictOpt('dt', default={'$foo': '$bar',
  2205. '$goo': 'goo',
  2206. 'har': '$har',
  2207. 'key1': 'str',
  2208. 'key2': 12345}))
  2209. self.conf([])
  2210. self.assertEqual('blaa', self.conf.dt['floo'])
  2211. self.assertEqual('goo', self.conf.dt['gloo'])
  2212. self.assertEqual('hlaa', self.conf.dt['har'])
  2213. self.assertEqual('str', self.conf.dt['key1'])
  2214. self.assertEqual(12345, self.conf.dt['key2'])
  2215. def test_dict_sub_default_from_default_recurse(self):
  2216. self.conf.register_cli_opt(cfg.StrOpt('foo', default='$foo2'))
  2217. self.conf.register_cli_opt(cfg.StrOpt('foo2', default='floo'))
  2218. self.conf.register_cli_opt(cfg.StrOpt('bar', default='$bar2'))
  2219. self.conf.register_cli_opt(cfg.StrOpt('bar2', default='blaa'))
  2220. self.conf.register_cli_opt(cfg.DictOpt('dt', default={'$foo': '$bar'}))
  2221. self.conf([])
  2222. self.assertEqual('blaa', self.conf.dt['floo'])
  2223. def test_dict_sub_default_from_arg(self):
  2224. self.conf.register_cli_opt(cfg.StrOpt('foo', default=None))
  2225. self.conf.register_cli_opt(cfg.StrOpt('bar', default=None))
  2226. self.conf.register_cli_opt(cfg.DictOpt('dt', default={'$foo': '$bar'}))
  2227. self.conf(['--foo', 'floo', '--bar', 'blaa'])
  2228. self.assertTrue(hasattr(self.conf, 'dt'))
  2229. self.assertEqual('blaa', self.conf.dt['floo'])
  2230. def test_dict_sub_default_from_config_file(self):
  2231. self.conf.register_cli_opt(cfg.StrOpt('foo', default='floo'))
  2232. self.conf.register_cli_opt(cfg.StrOpt('bar', default='blaa'))
  2233. self.conf.register_cli_opt(cfg.DictOpt('dt', default={}))
  2234. paths = self.create_tempfiles([('test',
  2235. '[DEFAULT]\n'
  2236. 'dt = $foo:$bar\n')])
  2237. self.conf(['--config-file', paths[0]])
  2238. self.assertTrue(hasattr(self.conf, 'dt'))
  2239. self.assertEqual('blaa', self.conf.dt['floo'])
  2240. class ConfigDirTestCase(BaseTestCase):
  2241. def test_config_dir(self):
  2242. snafu_group = cfg.OptGroup('snafu')
  2243. self.conf.register_group(snafu_group)
  2244. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  2245. self.conf.register_cli_opt(cfg.StrOpt('bell'), group=snafu_group)
  2246. dir = tempfile.mkdtemp()
  2247. self.tempdirs.append(dir)
  2248. paths = self.create_tempfiles([(os.path.join(dir, '00-test'),
  2249. '[DEFAULT]\n'
  2250. 'foo = bar-00\n'
  2251. '[snafu]\n'
  2252. 'bell = whistle-00\n'),
  2253. (os.path.join(dir, '02-test'),
  2254. '[snafu]\n'
  2255. 'bell = whistle-02\n'
  2256. '[DEFAULT]\n'
  2257. 'foo = bar-02\n'),
  2258. (os.path.join(dir, '01-test'),
  2259. '[DEFAULT]\n'
  2260. 'foo = bar-01\n')])
  2261. self.conf(['--foo', 'bar',
  2262. '--config-dir', os.path.dirname(paths[0])])
  2263. self.assertTrue(hasattr(self.conf, 'foo'))
  2264. self.assertEqual('bar-02', self.conf.foo)
  2265. self.assertTrue(hasattr(self.conf, 'snafu'))
  2266. self.assertTrue(hasattr(self.conf.snafu, 'bell'))
  2267. self.assertEqual('whistle-02', self.conf.snafu.bell)
  2268. def test_config_dir_multistr(self):
  2269. # Demonstrate that values for multistr options found in
  2270. # different sources are combined.
  2271. self.conf.register_cli_opt(cfg.MultiStrOpt('foo'))
  2272. dir = tempfile.mkdtemp()
  2273. self.tempdirs.append(dir)
  2274. paths = self.create_tempfiles([(os.path.join(dir, '00-test'),
  2275. '[DEFAULT]\n'
  2276. 'foo = bar-00\n'),
  2277. (os.path.join(dir, '02-test'),
  2278. '[DEFAULT]\n'
  2279. 'foo = bar-02\n'),
  2280. (os.path.join(dir, '01-test'),
  2281. '[DEFAULT]\n'
  2282. 'foo = bar-01\n')])
  2283. self.conf(['--foo', 'bar',
  2284. '--config-dir', os.path.dirname(paths[0])])
  2285. self.assertTrue(hasattr(self.conf, 'foo'))
  2286. self.assertEqual(['bar', 'bar-00', 'bar-01', 'bar-02'], self.conf.foo)
  2287. def test_config_dir_file_precedence(self):
  2288. snafu_group = cfg.OptGroup('snafu')
  2289. self.conf.register_group(snafu_group)
  2290. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  2291. self.conf.register_cli_opt(cfg.StrOpt('bell'), group=snafu_group)
  2292. dir = tempfile.mkdtemp()
  2293. self.tempdirs.append(dir)
  2294. paths = self.create_tempfiles([(os.path.join(dir, '00-test'),
  2295. '[DEFAULT]\n'
  2296. 'foo = bar-00\n'),
  2297. ('01-test',
  2298. '[snafu]\n'
  2299. 'bell = whistle-01\n'
  2300. '[DEFAULT]\n'
  2301. 'foo = bar-01\n'),
  2302. ('03-test',
  2303. '[snafu]\n'
  2304. 'bell = whistle-03\n'
  2305. '[DEFAULT]\n'
  2306. 'foo = bar-03\n'),
  2307. (os.path.join(dir, '02-test'),
  2308. '[DEFAULT]\n'
  2309. 'foo = bar-02\n')])
  2310. self.conf(['--foo', 'bar',
  2311. '--config-file', paths[1],
  2312. '--config-dir', os.path.dirname(paths[0]),
  2313. '--config-file', paths[2], ])
  2314. self.assertTrue(hasattr(self.conf, 'foo'))
  2315. self.assertEqual('bar-03', self.conf.foo)
  2316. self.assertTrue(hasattr(self.conf, 'snafu'))
  2317. self.assertTrue(hasattr(self.conf.snafu, 'bell'))
  2318. self.assertEqual('whistle-03', self.conf.snafu.bell)
  2319. def test_config_dir_default_file_precedence(self):
  2320. snafu_group = cfg.OptGroup('snafu')
  2321. self.conf.register_group(snafu_group)
  2322. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  2323. self.conf.register_cli_opt(cfg.StrOpt('bell'), group=snafu_group)
  2324. dir = tempfile.mkdtemp()
  2325. self.tempdirs.append(dir)
  2326. paths = self.create_tempfiles([(os.path.join(dir, '00-test'),
  2327. '[DEFAULT]\n'
  2328. 'foo = bar-00\n'
  2329. '[snafu]\n'
  2330. 'bell = whistle-11\n'),
  2331. ('01-test',
  2332. '[snafu]\n'
  2333. 'bell = whistle-01\n'
  2334. '[DEFAULT]\n'
  2335. 'foo = bar-01\n'),
  2336. ('03-test',
  2337. '[snafu]\n'
  2338. 'bell = whistle-03\n'
  2339. '[DEFAULT]\n'
  2340. 'foo = bar-03\n'),
  2341. (os.path.join(dir, '02-test'),
  2342. '[DEFAULT]\n'
  2343. 'foo = bar-02\n')])
  2344. self.conf(['--foo', 'bar', '--config-dir', os.path.dirname(paths[0])],
  2345. default_config_files=[paths[1], paths[2]])
  2346. self.assertTrue(hasattr(self.conf, 'foo'))
  2347. self.assertEqual('bar-02', self.conf.foo)
  2348. self.assertTrue(hasattr(self.conf, 'snafu'))
  2349. self.assertTrue(hasattr(self.conf.snafu, 'bell'))
  2350. self.assertEqual('whistle-11', self.conf.snafu.bell)
  2351. def test_config_dir_doesnt_exist(self):
  2352. tmpdir = tempfile.mkdtemp()
  2353. os.rmdir(tmpdir)
  2354. self.assertRaises(cfg.ConfigDirNotFoundError,
  2355. self.conf,
  2356. ['--config-dir', tmpdir]
  2357. )
  2358. class ReparseTestCase(BaseTestCase):
  2359. def test_reparse(self):
  2360. self.conf.register_group(cfg.OptGroup('blaa'))
  2361. self.conf.register_cli_opt(
  2362. cfg.StrOpt('foo', default='r'), group='blaa')
  2363. paths = self.create_tempfiles([('test',
  2364. '[blaa]\n'
  2365. 'foo = b\n')])
  2366. self.conf(['--config-file', paths[0]])
  2367. self.assertTrue(hasattr(self.conf, 'blaa'))
  2368. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  2369. self.assertEqual('b', self.conf.blaa.foo)
  2370. self.conf(['--blaa-foo', 'a'])
  2371. self.assertTrue(hasattr(self.conf, 'blaa'))
  2372. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  2373. self.assertEqual('a', self.conf.blaa.foo)
  2374. self.conf([])
  2375. self.assertTrue(hasattr(self.conf, 'blaa'))
  2376. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  2377. self.assertEqual('r', self.conf.blaa.foo)
  2378. class OverridesTestCase(BaseTestCase):
  2379. def test_default_none(self):
  2380. self.conf.register_opt(cfg.StrOpt('foo', default='foo'))
  2381. self.conf([])
  2382. self.assertEqual('foo', self.conf.foo)
  2383. self.conf.set_default('foo', None)
  2384. self.assertIsNone(self.conf.foo)
  2385. self.conf.clear_default('foo')
  2386. self.assertEqual('foo', self.conf.foo)
  2387. def test_no_default_override(self):
  2388. self.conf.register_opt(cfg.StrOpt('foo'))
  2389. self.conf([])
  2390. self.assertIsNone(self.conf.foo)
  2391. self.conf.set_default('foo', 'bar')
  2392. self.assertEqual('bar', self.conf.foo)
  2393. self.conf.clear_default('foo')
  2394. self.assertIsNone(self.conf.foo)
  2395. def test_default_override(self):
  2396. self.conf.register_opt(cfg.StrOpt('foo', default='foo'))
  2397. self.conf([])
  2398. self.assertEqual('foo', self.conf.foo)
  2399. self.conf.set_default('foo', 'bar')
  2400. self.assertEqual('bar', self.conf.foo)
  2401. self.conf.clear_default('foo')
  2402. self.assertEqual('foo', self.conf.foo)
  2403. def test_set_default_not_in_choices(self):
  2404. self.conf.register_group(cfg.OptGroup('f'))
  2405. self.conf.register_cli_opt(cfg.StrOpt('oo', choices=('a', 'b')),
  2406. group='f')
  2407. self.assertRaises(ValueError,
  2408. self.conf.set_default, 'oo', 'c', 'f')
  2409. def test_enforce_type_default_override(self):
  2410. self.conf.register_opt(cfg.StrOpt('foo', default='foo'))
  2411. self.conf([])
  2412. self.assertEqual('foo', self.conf.foo)
  2413. self.conf.set_default('foo', 'bar')
  2414. self.assertEqual('bar', self.conf.foo)
  2415. self.conf.clear_default('foo')
  2416. self.assertEqual('foo', self.conf.foo)
  2417. def test_enforce_type_wrong_type_default(self):
  2418. self.conf.register_opt(cfg.IntOpt('foo', default=1))
  2419. self.conf([])
  2420. self.assertEqual(1, self.conf.foo)
  2421. self.assertRaises(ValueError, self.conf.set_default,
  2422. 'foo', 'not_really_a_int')
  2423. def test_override(self):
  2424. self.conf.register_opt(cfg.StrOpt('foo'))
  2425. self.conf.set_override('foo', 'bar')
  2426. self.conf([])
  2427. self.assertEqual('bar', self.conf.foo)
  2428. self.conf.clear_override('foo')
  2429. self.assertIsNone(self.conf.foo)
  2430. def test_override_none(self):
  2431. self.conf.register_opt(cfg.StrOpt('foo', default='foo'))
  2432. self.conf([])
  2433. self.assertEqual('foo', self.conf.foo)
  2434. self.conf.set_override('foo', None)
  2435. self.assertIsNone(self.conf.foo)
  2436. self.conf.clear_override('foo')
  2437. self.assertEqual('foo', self.conf.foo)
  2438. def test_group_no_default_override(self):
  2439. self.conf.register_group(cfg.OptGroup('blaa'))
  2440. self.conf.register_opt(cfg.StrOpt('foo'), group='blaa')
  2441. self.conf([])
  2442. self.assertIsNone(self.conf.blaa.foo)
  2443. self.conf.set_default('foo', 'bar', group='blaa')
  2444. self.assertEqual('bar', self.conf.blaa.foo)
  2445. self.conf.clear_default('foo', group='blaa')
  2446. self.assertIsNone(self.conf.blaa.foo)
  2447. def test_group_default_override(self):
  2448. self.conf.register_group(cfg.OptGroup('blaa'))
  2449. self.conf.register_opt(cfg.StrOpt('foo', default='foo'), group='blaa')
  2450. self.conf([])
  2451. self.assertEqual('foo', self.conf.blaa.foo)
  2452. self.conf.set_default('foo', 'bar', group='blaa')
  2453. self.assertEqual('bar', self.conf.blaa.foo)
  2454. self.conf.clear_default('foo', group='blaa')
  2455. self.assertEqual('foo', self.conf.blaa.foo)
  2456. def test_group_override(self):
  2457. self.conf.register_group(cfg.OptGroup('blaa'))
  2458. self.conf.register_opt(cfg.StrOpt('foo'), group='blaa')
  2459. self.assertIsNone(self.conf.blaa.foo)
  2460. self.conf.set_override('foo', 'bar', group='blaa')
  2461. self.conf([])
  2462. self.assertEqual('bar', self.conf.blaa.foo)
  2463. self.conf.clear_override('foo', group='blaa')
  2464. self.assertIsNone(self.conf.blaa.foo)
  2465. def test_cli_bool_default(self):
  2466. self.conf.register_cli_opt(cfg.BoolOpt('foo'))
  2467. self.conf.set_default('foo', True)
  2468. self.assertTrue(self.conf.foo)
  2469. self.conf([])
  2470. self.assertTrue(self.conf.foo)
  2471. self.conf.set_default('foo', False)
  2472. self.assertFalse(self.conf.foo)
  2473. self.conf.clear_default('foo')
  2474. self.assertIsNone(self.conf.foo)
  2475. def test_cli_bool_override(self):
  2476. self.conf.register_cli_opt(cfg.BoolOpt('foo'))
  2477. self.conf.set_override('foo', True)
  2478. self.assertTrue(self.conf.foo)
  2479. self.conf([])
  2480. self.assertTrue(self.conf.foo)
  2481. self.conf.set_override('foo', False)
  2482. self.assertFalse(self.conf.foo)
  2483. self.conf.clear_override('foo')
  2484. self.assertIsNone(self.conf.foo)
  2485. def test_enforce_type_str_override(self):
  2486. self.conf.register_opt(cfg.StrOpt('foo'))
  2487. self.conf.set_override('foo', True)
  2488. self.conf([])
  2489. self.assertEqual('True', self.conf.foo)
  2490. self.conf.clear_override('foo')
  2491. self.assertIsNone(self.conf.foo)
  2492. def test_no_enforce_type_str_override(self):
  2493. self.conf.register_opt(cfg.StrOpt('foo'))
  2494. self.conf.set_override('foo', True, enforce_type=False)
  2495. self.conf([])
  2496. # Ensure we don't change the provided type by mistake
  2497. self.assertEqual(True, self.conf.foo)
  2498. self.conf.clear_override('foo')
  2499. self.assertIsNone(self.conf.foo)
  2500. def test_enforce_type_wrong_type_override(self):
  2501. self.conf.register_opt(cfg.IntOpt('foo'))
  2502. self.assertRaises(ValueError, self.conf.set_override,
  2503. 'foo', "not_really_a_int")
  2504. def test_set_override_in_choices(self):
  2505. self.conf.register_group(cfg.OptGroup('f'))
  2506. self.conf.register_cli_opt(cfg.StrOpt('oo', choices=('a', 'b')),
  2507. group='f')
  2508. self.conf.set_override('oo', 'b', 'f')
  2509. self.assertEqual('b', self.conf.f.oo)
  2510. def test_set_override_not_in_choices(self):
  2511. self.conf.register_group(cfg.OptGroup('f'))
  2512. self.conf.register_cli_opt(cfg.StrOpt('oo', choices=('a', 'b')),
  2513. group='f')
  2514. self.assertRaises(ValueError,
  2515. self.conf.set_override, 'oo', 'c', 'f')
  2516. def test_enforce_type_bool_override(self):
  2517. self.conf.register_opt(cfg.BoolOpt('foo'))
  2518. self.conf.set_override('foo', 'True')
  2519. self.conf([])
  2520. self.assertTrue(self.conf.foo)
  2521. self.conf.clear_override('foo')
  2522. self.assertIsNone(self.conf.foo)
  2523. def test_enforce_type_int_override_with_None(self):
  2524. self.conf.register_opt(cfg.IntOpt('foo'))
  2525. self.conf.set_override('foo', None)
  2526. self.conf([])
  2527. self.assertIsNone(self.conf.foo)
  2528. self.conf.clear_override('foo')
  2529. self.assertIsNone(self.conf.foo)
  2530. def test_enforce_type_str_override_with_None(self):
  2531. self.conf.register_opt(cfg.StrOpt('foo'))
  2532. self.conf.set_override('foo', None)
  2533. self.conf([])
  2534. self.assertIsNone(self.conf.foo)
  2535. self.conf.clear_override('foo')
  2536. self.assertIsNone(self.conf.foo)
  2537. def test_enforce_type_List_override(self):
  2538. self.conf.register_opt(cfg.ListOpt('foo'))
  2539. self.conf.set_override('foo', ['aa', 'bb'])
  2540. self.conf([])
  2541. self.assertEqual(['aa', 'bb'], self.conf.foo)
  2542. self.conf.clear_override('foo')
  2543. self.assertIsNone(self.conf.foo)
  2544. class ResetAndClearTestCase(BaseTestCase):
  2545. def test_clear(self):
  2546. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  2547. self.conf.register_cli_opt(cfg.StrOpt('bar'), group='blaa')
  2548. self.assertIsNone(self.conf.foo)
  2549. self.assertIsNone(self.conf.blaa.bar)
  2550. self.conf(['--foo', 'foo', '--blaa-bar', 'bar'])
  2551. self.assertEqual('foo', self.conf.foo)
  2552. self.assertEqual('bar', self.conf.blaa.bar)
  2553. self.conf.clear()
  2554. self.assertIsNone(self.conf.foo)
  2555. self.assertIsNone(self.conf.blaa.bar)
  2556. def test_reset_and_clear_with_defaults_and_overrides(self):
  2557. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  2558. self.conf.register_cli_opt(cfg.StrOpt('bar'), group='blaa')
  2559. self.conf.set_default('foo', 'foo')
  2560. self.conf.set_override('bar', 'bar', group='blaa')
  2561. self.conf(['--foo', 'foofoo'])
  2562. self.assertEqual('foofoo', self.conf.foo)
  2563. self.assertEqual('bar', self.conf.blaa.bar)
  2564. self.conf.clear()
  2565. self.assertEqual('foo', self.conf.foo)
  2566. self.assertEqual('bar', self.conf.blaa.bar)
  2567. self.conf.reset()
  2568. self.assertIsNone(self.conf.foo)
  2569. self.assertIsNone(self.conf.blaa.bar)
  2570. class UnregisterOptTestCase(BaseTestCase):
  2571. def test_unregister_opt(self):
  2572. opts = [cfg.StrOpt('foo'), cfg.StrOpt('bar')]
  2573. self.conf.register_opts(opts)
  2574. self.assertTrue(hasattr(self.conf, 'foo'))
  2575. self.assertTrue(hasattr(self.conf, 'bar'))
  2576. self.conf.unregister_opt(opts[0])
  2577. self.assertFalse(hasattr(self.conf, 'foo'))
  2578. self.assertTrue(hasattr(self.conf, 'bar'))
  2579. self.conf([])
  2580. self.assertRaises(cfg.ArgsAlreadyParsedError,
  2581. self.conf.unregister_opt, opts[1])
  2582. self.conf.clear()
  2583. self.assertTrue(hasattr(self.conf, 'bar'))
  2584. self.conf.unregister_opts(opts)
  2585. def test_unregister_opt_from_group(self):
  2586. opt = cfg.StrOpt('foo')
  2587. self.conf.register_opt(opt, group='blaa')
  2588. self.assertTrue(hasattr(self.conf, 'blaa'))
  2589. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  2590. self.conf.unregister_opt(opt, group='blaa')
  2591. self.assertFalse(hasattr(self.conf.blaa, 'foo'))
  2592. class ImportOptTestCase(BaseTestCase):
  2593. def test_import_opt(self):
  2594. self.assertFalse(hasattr(cfg.CONF, 'blaa'))
  2595. cfg.CONF.import_opt('blaa', 'oslo_config.tests.testmods.blaa_opt')
  2596. self.assertTrue(hasattr(cfg.CONF, 'blaa'))
  2597. def test_import_opt_in_group(self):
  2598. self.assertFalse(hasattr(cfg.CONF, 'bar'))
  2599. cfg.CONF.import_opt('foo', 'oslo_config.tests.testmods.bar_foo_opt',
  2600. group='bar')
  2601. self.assertTrue(hasattr(cfg.CONF, 'bar'))
  2602. self.assertTrue(hasattr(cfg.CONF.bar, 'foo'))
  2603. def test_import_opt_import_errror(self):
  2604. self.assertRaises(ImportError, cfg.CONF.import_opt,
  2605. 'blaa', 'oslo_config.tests.testmods.blaablaa_opt')
  2606. def test_import_opt_no_such_opt(self):
  2607. self.assertRaises(cfg.NoSuchOptError, cfg.CONF.import_opt,
  2608. 'blaablaa', 'oslo_config.tests.testmods.blaa_opt')
  2609. def test_import_opt_no_such_group(self):
  2610. self.assertRaises(cfg.NoSuchGroupError, cfg.CONF.import_opt,
  2611. 'blaa', 'oslo_config.tests.testmods.blaa_opt',
  2612. group='blaa')
  2613. class ImportGroupTestCase(BaseTestCase):
  2614. def test_import_group(self):
  2615. self.assertFalse(hasattr(cfg.CONF, 'qux'))
  2616. cfg.CONF.import_group('qux', 'oslo_config.tests.testmods.baz_qux_opt')
  2617. self.assertTrue(hasattr(cfg.CONF, 'qux'))
  2618. self.assertTrue(hasattr(cfg.CONF.qux, 'baz'))
  2619. def test_import_group_import_error(self):
  2620. self.assertRaises(ImportError, cfg.CONF.import_group,
  2621. 'qux', 'oslo_config.tests.testmods.bazzz_quxxx_opt')
  2622. def test_import_group_no_such_group(self):
  2623. self.assertRaises(cfg.NoSuchGroupError, cfg.CONF.import_group,
  2624. 'quxxx', 'oslo_config.tests.testmods.baz_qux_opt')
  2625. class RequiredOptsTestCase(BaseTestCase):
  2626. def setUp(self):
  2627. BaseTestCase.setUp(self)
  2628. self.conf.register_opt(cfg.StrOpt('boo', required=False))
  2629. def test_required_opt(self):
  2630. self.conf.register_opt(cfg.StrOpt('foo', required=True))
  2631. paths = self.create_tempfiles([('test',
  2632. '[DEFAULT]\n'
  2633. 'foo = bar')])
  2634. self.conf(['--config-file', paths[0]])
  2635. self.assertTrue(hasattr(self.conf, 'foo'))
  2636. self.assertEqual('bar', self.conf.foo)
  2637. def test_required_cli_opt(self):
  2638. self.conf.register_cli_opt(cfg.StrOpt('foo', required=True))
  2639. self.conf(['--foo', 'bar'])
  2640. self.assertTrue(hasattr(self.conf, 'foo'))
  2641. self.assertEqual('bar', self.conf.foo)
  2642. def test_required_cli_opt_with_dash(self):
  2643. self.conf.register_cli_opt(cfg.StrOpt('foo-bar', required=True))
  2644. self.conf(['--foo-bar', 'baz'])
  2645. self.assertTrue(hasattr(self.conf, 'foo_bar'))
  2646. self.assertEqual('baz', self.conf.foo_bar)
  2647. def test_missing_required_opt(self):
  2648. self.conf.register_opt(cfg.StrOpt('foo', required=True))
  2649. self.assertRaises(cfg.RequiredOptError, self.conf, [])
  2650. def test_missing_required_cli_opt(self):
  2651. self.conf.register_cli_opt(cfg.StrOpt('foo', required=True))
  2652. self.assertRaises(cfg.RequiredOptError, self.conf, [])
  2653. def test_required_group_opt(self):
  2654. self.conf.register_group(cfg.OptGroup('blaa'))
  2655. self.conf.register_opt(cfg.StrOpt('foo', required=True), group='blaa')
  2656. paths = self.create_tempfiles([('test',
  2657. '[blaa]\n'
  2658. 'foo = bar')])
  2659. self.conf(['--config-file', paths[0]])
  2660. self.assertTrue(hasattr(self.conf, 'blaa'))
  2661. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  2662. self.assertEqual('bar', self.conf.blaa.foo)
  2663. def test_required_cli_group_opt(self):
  2664. self.conf.register_group(cfg.OptGroup('blaa'))
  2665. self.conf.register_cli_opt(
  2666. cfg.StrOpt('foo', required=True), group='blaa')
  2667. self.conf(['--blaa-foo', 'bar'])
  2668. self.assertTrue(hasattr(self.conf, 'blaa'))
  2669. self.assertTrue(hasattr(self.conf.blaa, 'foo'))
  2670. self.assertEqual('bar', self.conf.blaa.foo)
  2671. def test_missing_required_group_opt(self):
  2672. self.conf.register_group(cfg.OptGroup('blaa'))
  2673. self.conf.register_opt(cfg.StrOpt('foo', required=True), group='blaa')
  2674. self.assertRaises(cfg.RequiredOptError, self.conf, [])
  2675. def test_missing_required_cli_group_opt(self):
  2676. self.conf.register_group(cfg.OptGroup('blaa'))
  2677. self.conf.register_cli_opt(
  2678. cfg.StrOpt('foo', required=True), group='blaa')
  2679. self.assertRaises(cfg.RequiredOptError, self.conf, [])
  2680. def test_required_opt_with_default(self):
  2681. self.conf.register_cli_opt(cfg.StrOpt('foo', required=True))
  2682. self.conf.set_default('foo', 'bar')
  2683. self.conf([])
  2684. self.assertTrue(hasattr(self.conf, 'foo'))
  2685. self.assertEqual('bar', self.conf.foo)
  2686. def test_required_opt_with_override(self):
  2687. self.conf.register_cli_opt(cfg.StrOpt('foo', required=True))
  2688. self.conf.set_override('foo', 'bar')
  2689. self.conf([])
  2690. self.assertTrue(hasattr(self.conf, 'foo'))
  2691. self.assertEqual('bar', self.conf.foo)
  2692. class SadPathTestCase(BaseTestCase):
  2693. def test_unknown_attr(self):
  2694. self.conf([])
  2695. self.assertFalse(hasattr(self.conf, 'foo'))
  2696. self.assertRaises(AttributeError, getattr, self.conf, 'foo')
  2697. self.assertRaises(cfg.NoSuchOptError, self.conf._get, 'foo')
  2698. self.assertRaises(cfg.NoSuchOptError, self.conf.__getattr__, 'foo')
  2699. def test_unknown_attr_is_attr_error(self):
  2700. self.conf([])
  2701. self.assertFalse(hasattr(self.conf, 'foo'))
  2702. self.assertRaises(AttributeError, getattr, self.conf, 'foo')
  2703. def test_unknown_group_attr(self):
  2704. self.conf.register_group(cfg.OptGroup('blaa'))
  2705. self.conf([])
  2706. self.assertTrue(hasattr(self.conf, 'blaa'))
  2707. self.assertFalse(hasattr(self.conf.blaa, 'foo'))
  2708. self.assertRaises(cfg.NoSuchOptError, getattr, self.conf.blaa, 'foo')
  2709. def test_ok_duplicate(self):
  2710. opt = cfg.StrOpt('foo')
  2711. self.conf.register_cli_opt(opt)
  2712. opt2 = cfg.StrOpt('foo')
  2713. self.conf.register_cli_opt(opt2)
  2714. self.conf([])
  2715. self.assertTrue(hasattr(self.conf, 'foo'))
  2716. self.assertIsNone(self.conf.foo)
  2717. def test_error_duplicate(self):
  2718. self.conf.register_cli_opt(cfg.StrOpt('foo', help='bar'))
  2719. self.assertRaises(cfg.DuplicateOptError,
  2720. self.conf.register_cli_opt, cfg.StrOpt('foo'))
  2721. def test_error_duplicate_with_different_dest(self):
  2722. self.conf.register_cli_opt(cfg.StrOpt('foo', dest='f'))
  2723. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  2724. self.assertRaises(cfg.DuplicateOptError, self.conf, [])
  2725. def test_error_duplicate_short(self):
  2726. self.conf.register_cli_opt(cfg.StrOpt('foo', short='f'))
  2727. self.conf.register_cli_opt(cfg.StrOpt('bar', short='f'))
  2728. self.assertRaises(cfg.DuplicateOptError, self.conf, [])
  2729. def test_already_parsed(self):
  2730. self.conf([])
  2731. self.assertRaises(cfg.ArgsAlreadyParsedError,
  2732. self.conf.register_cli_opt, cfg.StrOpt('foo'))
  2733. def test_bad_cli_arg(self):
  2734. self.conf.register_opt(cfg.BoolOpt('foo'))
  2735. self.useFixture(fixtures.MonkeyPatch('sys.stderr', moves.StringIO()))
  2736. self.assertRaises(SystemExit, self.conf, ['--foo'])
  2737. self.assertIn('error', sys.stderr.getvalue())
  2738. self.assertIn('--foo', sys.stderr.getvalue())
  2739. def _do_test_bad_cli_value(self, opt_class):
  2740. self.conf.register_cli_opt(opt_class('foo'))
  2741. self.useFixture(fixtures.MonkeyPatch('sys.stderr', moves.StringIO()))
  2742. self.assertRaises(SystemExit, self.conf, ['--foo', 'bar'])
  2743. self.assertIn('foo', sys.stderr.getvalue())
  2744. self.assertIn('bar', sys.stderr.getvalue())
  2745. def test_bad_int_arg(self):
  2746. self._do_test_bad_cli_value(cfg.IntOpt)
  2747. def test_bad_float_arg(self):
  2748. self._do_test_bad_cli_value(cfg.FloatOpt)
  2749. def test_conf_file_not_found(self):
  2750. (fd, path) = tempfile.mkstemp()
  2751. os.remove(path)
  2752. self.assertRaises(cfg.ConfigFilesNotFoundError,
  2753. self.conf, ['--config-file', path])
  2754. def test_conf_file_permission_denied(self):
  2755. (fd, path) = tempfile.mkstemp()
  2756. os.chmod(path, 0x000)
  2757. self.assertRaises(cfg.ConfigFilesPermissionDeniedError,
  2758. self.conf, ['--config-file', path])
  2759. os.remove(path)
  2760. def test_conf_file_broken(self):
  2761. paths = self.create_tempfiles([('test', 'foo')])
  2762. self.assertRaises(cfg.ConfigFileParseError,
  2763. self.conf, ['--config-file', paths[0]])
  2764. def _do_test_conf_file_bad_value(self, opt_class):
  2765. self.conf.register_opt(opt_class('foo'))
  2766. paths = self.create_tempfiles([('test',
  2767. '[DEFAULT]\n'
  2768. 'foo = bar\n')])
  2769. self.conf(['--config-file', paths[0]])
  2770. self.assertRaises(ValueError, getattr, self.conf, 'foo')
  2771. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  2772. def test_conf_file_bad_bool(self):
  2773. self._do_test_conf_file_bad_value(cfg.BoolOpt)
  2774. def test_conf_file_bad_int(self):
  2775. self._do_test_conf_file_bad_value(cfg.IntOpt)
  2776. def test_conf_file_bad_float(self):
  2777. self._do_test_conf_file_bad_value(cfg.FloatOpt)
  2778. def test_str_sub_none_value(self):
  2779. self.conf.register_cli_opt(cfg.StrOpt('oo'))
  2780. self.conf.register_cli_opt(cfg.StrOpt('bar', default='$oo'))
  2781. self.conf.register_cli_opt(cfg.StrOpt('barbar', default='foo $oo foo'))
  2782. self.conf([])
  2783. self.assertTrue(hasattr(self.conf, 'bar'))
  2784. self.assertEqual('', self.conf.bar)
  2785. self.assertEqual("foo foo", self.conf.barbar)
  2786. def test_str_sub_from_group(self):
  2787. self.conf.register_group(cfg.OptGroup('f'))
  2788. self.conf.register_cli_opt(cfg.StrOpt('oo', default='blaa'), group='f')
  2789. self.conf.register_cli_opt(cfg.StrOpt('bar', default='$f.oo'))
  2790. self.conf([])
  2791. self.assertTrue(hasattr(self.conf, 'bar'))
  2792. self.assertEqual("blaa", self.conf.bar)
  2793. def test_str_sub_from_group_with_brace(self):
  2794. self.conf.register_group(cfg.OptGroup('f'))
  2795. self.conf.register_cli_opt(cfg.StrOpt('oo', default='blaa'), group='f')
  2796. self.conf.register_cli_opt(cfg.StrOpt('bar', default='${f.oo}'))
  2797. self.conf([])
  2798. self.assertTrue(hasattr(self.conf, 'bar'))
  2799. self.assertEqual("blaa", self.conf.bar)
  2800. def test_set_default_unknown_attr(self):
  2801. self.conf([])
  2802. self.assertRaises(
  2803. cfg.NoSuchOptError, self.conf.set_default, 'foo', 'bar')
  2804. def test_set_default_unknown_group(self):
  2805. self.conf([])
  2806. self.assertRaises(cfg.NoSuchGroupError,
  2807. self.conf.set_default, 'foo', 'bar', group='blaa')
  2808. def test_set_override_unknown_attr(self):
  2809. self.conf([])
  2810. self.assertRaises(
  2811. cfg.NoSuchOptError, self.conf.set_override, 'foo', 'bar')
  2812. def test_set_override_unknown_group(self):
  2813. self.conf([])
  2814. self.assertRaises(cfg.NoSuchGroupError,
  2815. self.conf.set_override, 'foo', 'bar', group='blaa')
  2816. class FindFileTestCase(BaseTestCase):
  2817. def test_find_file_without_init(self):
  2818. self.assertRaises(cfg.NotInitializedError,
  2819. self.conf.find_file, 'foo.json')
  2820. def test_find_policy_file(self):
  2821. policy_file = '/etc/policy.json'
  2822. self.useFixture(fixtures.MonkeyPatch(
  2823. 'os.path.exists',
  2824. lambda p: p == policy_file))
  2825. self.conf([])
  2826. self.assertIsNone(self.conf.find_file('foo.json'))
  2827. self.assertEqual(policy_file, self.conf.find_file('policy.json'))
  2828. def test_find_policy_file_with_config_file(self):
  2829. dir = tempfile.mkdtemp()
  2830. self.tempdirs.append(dir)
  2831. paths = self.create_tempfiles([(os.path.join(dir, 'test.conf'),
  2832. '[DEFAULT]'),
  2833. (os.path.join(dir, 'policy.json'),
  2834. '{}')],
  2835. ext='')
  2836. self.conf(['--config-file', paths[0]])
  2837. self.assertEqual(paths[1], self.conf.find_file('policy.json'))
  2838. def test_find_policy_file_with_multiple_config_dirs(self):
  2839. dir1 = tempfile.mkdtemp()
  2840. self.tempdirs.append(dir1)
  2841. dir2 = tempfile.mkdtemp()
  2842. self.tempdirs.append(dir2)
  2843. self.conf(['--config-dir', dir1, '--config-dir', dir2])
  2844. self.assertEqual(2, len(self.conf.config_dirs))
  2845. self.assertEqual(dir1, self.conf.config_dirs[0])
  2846. self.assertEqual(dir2, self.conf.config_dirs[1])
  2847. def test_config_dirs_empty_list_when_nothing_parsed(self):
  2848. self.assertEqual([], self.conf.config_dirs)
  2849. def test_find_policy_file_with_config_dir(self):
  2850. dir = tempfile.mkdtemp()
  2851. self.tempdirs.append(dir)
  2852. dir2 = tempfile.mkdtemp()
  2853. self.tempdirs.append(dir2)
  2854. path = self.create_tempfiles([(os.path.join(dir, 'policy.json'),
  2855. '{}')],
  2856. ext='')[0]
  2857. self.conf(['--config-dir', dir, '--config-dir', dir2])
  2858. self.assertEqual(path, self.conf.find_file('policy.json'))
  2859. class OptDumpingTestCase(BaseTestCase):
  2860. class FakeLogger(object):
  2861. def __init__(self, test_case, expected_lvl):
  2862. self.test_case = test_case
  2863. self.expected_lvl = expected_lvl
  2864. self.logged = []
  2865. def log(self, lvl, fmt, *args):
  2866. self.test_case.assertEqual(lvl, self.expected_lvl)
  2867. self.logged.append(fmt % args)
  2868. def setUp(self):
  2869. super(OptDumpingTestCase, self).setUp()
  2870. self._args = ['--foo', 'this', '--blaa-bar', 'that',
  2871. '--blaa-key', 'admin', '--passwd', 'hush']
  2872. def _do_test_log_opt_values(self, args):
  2873. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  2874. self.conf.register_cli_opt(cfg.StrOpt('passwd', secret=True))
  2875. self.conf.register_group(cfg.OptGroup('blaa'))
  2876. self.conf.register_cli_opt(cfg.StrOpt('bar'), 'blaa')
  2877. self.conf.register_cli_opt(cfg.StrOpt('key', secret=True), 'blaa')
  2878. self.conf(args)
  2879. logger = self.FakeLogger(self, 666)
  2880. self.conf.log_opt_values(logger, 666)
  2881. self.assertEqual([
  2882. "*" * 80,
  2883. "Configuration options gathered from:",
  2884. "command line args: ['--foo', 'this', '--blaa-bar', "
  2885. "'that', '--blaa-key', 'admin', '--passwd', 'hush']",
  2886. "config files: []",
  2887. "=" * 80,
  2888. "config_dir = []",
  2889. "config_file = []",
  2890. "foo = this",
  2891. "passwd = ****",
  2892. "blaa.bar = that",
  2893. "blaa.key = ****",
  2894. "*" * 80,
  2895. ], logger.logged)
  2896. def test_log_opt_values(self):
  2897. self._do_test_log_opt_values(self._args)
  2898. def test_log_opt_values_from_sys_argv(self):
  2899. self.useFixture(fixtures.MonkeyPatch('sys.argv', ['foo'] + self._args))
  2900. self._do_test_log_opt_values(None)
  2901. def test_log_opt_values_empty_config(self):
  2902. empty_conf = cfg.ConfigOpts()
  2903. logger = self.FakeLogger(self, 666)
  2904. empty_conf.log_opt_values(logger, 666)
  2905. self.assertEqual([
  2906. "*" * 80,
  2907. "Configuration options gathered from:",
  2908. "command line args: None",
  2909. "config files: []",
  2910. "=" * 80,
  2911. "*" * 80,
  2912. ], logger.logged)
  2913. class ConfigParserTestCase(BaseTestCase):
  2914. def test_parse_file(self):
  2915. paths = self.create_tempfiles([('test',
  2916. '[DEFAULT]\n'
  2917. 'foo = bar\n'
  2918. '[BLAA]\n'
  2919. 'bar = foo\n')])
  2920. sections = {}
  2921. parser = cfg.ConfigParser(paths[0], sections)
  2922. parser.parse()
  2923. self.assertIn('DEFAULT', sections)
  2924. self.assertIn('BLAA', sections)
  2925. self.assertEqual(sections['DEFAULT']['foo'], ['bar'])
  2926. self.assertEqual(sections['BLAA']['bar'], ['foo'])
  2927. def test_parse_file_with_normalized(self):
  2928. paths = self.create_tempfiles([('test',
  2929. '[DEFAULT]\n'
  2930. 'foo = bar\n'
  2931. '[BLAA]\n'
  2932. 'bar = foo\n')])
  2933. sections = {}
  2934. normalized = {}
  2935. parser = cfg.ConfigParser(paths[0], sections)
  2936. parser._add_normalized(normalized)
  2937. parser.parse()
  2938. self.assertIn('DEFAULT', sections)
  2939. self.assertIn('DEFAULT', normalized)
  2940. self.assertIn('BLAA', sections)
  2941. self.assertIn('blaa', normalized)
  2942. self.assertEqual(sections['DEFAULT']['foo'], ['bar'])
  2943. self.assertEqual(normalized['DEFAULT']['foo'], ['bar'])
  2944. self.assertEqual(sections['BLAA']['bar'], ['foo'])
  2945. self.assertEqual(normalized['blaa']['bar'], ['foo'])
  2946. def test_no_section(self):
  2947. with tempfile.NamedTemporaryFile() as tmpfile:
  2948. tmpfile.write(six.b('foo = bar'))
  2949. tmpfile.flush()
  2950. parser = cfg.ConfigParser(tmpfile.name, {})
  2951. self.assertRaises(cfg.ParseError, parser.parse)
  2952. def test__parse_file_ioerror(self):
  2953. # Test that IOErrors (other than 'No such file or directory')
  2954. # are propagated.
  2955. filename = 'fake'
  2956. namespace = mock.Mock()
  2957. with mock.patch('oslo_config.cfg.ConfigParser.parse') as parse:
  2958. parse.side_effect = IOError(errno.EMFILE, filename,
  2959. 'Too many open files')
  2960. self.assertRaises(IOError, cfg.ConfigParser._parse_file, filename,
  2961. namespace)
  2962. class MultiConfigParserTestCase(BaseTestCase):
  2963. def test_parse_single_file(self):
  2964. paths = self.create_tempfiles([('test',
  2965. '[DEFAULT]\n'
  2966. 'foo = bar\n'
  2967. '[BLAA]\n'
  2968. 'bar = foo\n')])
  2969. parser = cfg.MultiConfigParser()
  2970. read_ok = parser.read(paths)
  2971. self.assertEqual(read_ok, paths)
  2972. self.assertIn('DEFAULT', parser.parsed[0])
  2973. self.assertEqual(parser.parsed[0]['DEFAULT']['foo'], ['bar'])
  2974. self.assertEqual(parser.get([('DEFAULT', 'foo')]), ['bar'])
  2975. self.assertEqual(parser.get([('DEFAULT', 'foo')], multi=True),
  2976. ['bar'])
  2977. self.assertEqual(parser.get([('DEFAULT', 'foo')], multi=True),
  2978. ['bar'])
  2979. self.assertEqual(parser.get([(None, 'foo')], multi=True),
  2980. ['bar'])
  2981. self.assertEqual(parser._get([('DEFAULT', 'foo')],
  2982. multi=True, normalized=True),
  2983. ['bar'])
  2984. self.assertIn('BLAA', parser.parsed[0])
  2985. self.assertEqual(parser.parsed[0]['BLAA']['bar'], ['foo'])
  2986. self.assertEqual(parser.get([('BLAA', 'bar')]), ['foo'])
  2987. self.assertEqual(parser.get([('BLAA', 'bar')], multi=True),
  2988. ['foo'])
  2989. self.assertEqual(parser._get([('blaa', 'bar')],
  2990. multi=True, normalized=True),
  2991. ['foo'])
  2992. def test_parse_multiple_files(self):
  2993. paths = self.create_tempfiles([('test1',
  2994. '[DEFAULT]\n'
  2995. 'foo = bar\n'
  2996. '[BLAA]\n'
  2997. 'bar = foo'),
  2998. ('test2',
  2999. '[DEFAULT]\n'
  3000. 'foo = barbar\n'
  3001. '[BLAA]\n'
  3002. 'bar = foofoo\n'
  3003. '[bLAa]\n'
  3004. 'bar = foofoofoo\n')])
  3005. parser = cfg.MultiConfigParser()
  3006. read_ok = parser.read(paths)
  3007. self.assertEqual(read_ok, paths)
  3008. self.assertIn('DEFAULT', parser.parsed[0])
  3009. self.assertEqual(parser.parsed[0]['DEFAULT']['foo'], ['barbar'])
  3010. self.assertIn('DEFAULT', parser.parsed[1])
  3011. self.assertEqual(parser.parsed[1]['DEFAULT']['foo'], ['bar'])
  3012. self.assertEqual(parser.get([('DEFAULT', 'foo')]), ['barbar'])
  3013. self.assertEqual(parser.get([('DEFAULT', 'foo')], multi=True),
  3014. ['bar', 'barbar'])
  3015. self.assertIn('BLAA', parser.parsed[0])
  3016. self.assertIn('bLAa', parser.parsed[0])
  3017. self.assertEqual(parser.parsed[0]['BLAA']['bar'], ['foofoo'])
  3018. self.assertEqual(parser.parsed[0]['bLAa']['bar'], ['foofoofoo'])
  3019. self.assertIn('BLAA', parser.parsed[1])
  3020. self.assertEqual(parser.parsed[1]['BLAA']['bar'], ['foo'])
  3021. self.assertEqual(parser.get([('BLAA', 'bar')]), ['foofoo'])
  3022. self.assertEqual(parser.get([('bLAa', 'bar')]), ['foofoofoo'])
  3023. self.assertEqual(parser.get([('BLAA', 'bar')], multi=True),
  3024. ['foo', 'foofoo'])
  3025. self.assertEqual(parser._get([('BLAA', 'bar')],
  3026. multi=True, normalized=True),
  3027. ['foo', 'foofoo', 'foofoofoo'])
  3028. class NamespaceTestCase(BaseTestCase):
  3029. def setUp(self):
  3030. super(NamespaceTestCase, self).setUp()
  3031. self.ns = cfg._Namespace(self.conf)
  3032. def read(self, *texts):
  3033. paths = ((str(i), t) for i, t in enumerate(texts))
  3034. for path in self.create_tempfiles(paths):
  3035. cfg.ConfigParser._parse_file(path, self.ns)
  3036. def assertAbsent(self, key, normalized=False):
  3037. self.assertRaises(KeyError, self.ns._get_value, [key],
  3038. normalized=normalized)
  3039. def assertValue(self, key, expect, multi=False, normalized=False):
  3040. actual = self.ns._get_value([key], multi=multi, normalized=normalized)
  3041. self.assertEqual(actual, expect)
  3042. def test_cli(self):
  3043. self.conf.register_cli_opt(cfg.StrOpt('foo'))
  3044. key = (None, 'foo')
  3045. self.assertAbsent(key)
  3046. self.read('[DEFAULT]\n'
  3047. 'foo = file0\n')
  3048. self.assertValue(key, 'file0')
  3049. self.read('[DEFAULT]\n'
  3050. 'foo = file1\n')
  3051. self.assertEqual('file1', self.ns._get_cli_value([key]))
  3052. def test_single_file(self):
  3053. self.read('[DEFAULT]\n'
  3054. 'foo = bar\n'
  3055. '[BLAA]\n'
  3056. 'bar = foo\n')
  3057. self.assertValue(('DEFAULT', 'foo'), 'bar')
  3058. self.assertValue(('DEFAULT', 'foo'), ['bar'], multi=True)
  3059. self.assertValue(('DEFAULT', 'foo'), ['bar'], multi=True)
  3060. self.assertValue((None, 'foo'), ['bar'], multi=True)
  3061. self.assertValue(('DEFAULT', 'foo'), ['bar'], multi=True,
  3062. normalized=True)
  3063. self.assertValue(('BLAA', 'bar'), 'foo')
  3064. self.assertValue(('BLAA', 'bar'), ['foo'], multi=True)
  3065. self.assertValue(('blaa', 'bar'), ['foo'], multi=True,
  3066. normalized=True)
  3067. def test_multiple_files(self):
  3068. self.read('[DEFAULT]\n'
  3069. 'foo = bar\n'
  3070. '[BLAA]\n'
  3071. 'bar = foo',
  3072. '[DEFAULT]\n'
  3073. 'foo = barbar\n'
  3074. '[BLAA]\n'
  3075. 'bar = foofoo\n'
  3076. '[bLAa]\n'
  3077. 'bar = foofoofoo\n')
  3078. self.assertValue(('DEFAULT', 'foo'), 'barbar')
  3079. self.assertValue(('DEFAULT', 'foo'), ['bar', 'barbar'], multi=True)
  3080. self.assertValue(('BLAA', 'bar'), 'foofoo')
  3081. self.assertValue(('bLAa', 'bar'), 'foofoofoo')
  3082. self.assertValue(('BLAA', 'bar'), ['foo', 'foofoo'], multi=True)
  3083. self.assertValue(('Blaa', 'bar'), ['foo', 'foofoo', 'foofoofoo'],
  3084. multi=True, normalized=True)
  3085. def test_attrs_subparser(self):
  3086. CONF = cfg.ConfigOpts()
  3087. CONF.register_cli_opt(cfg.SubCommandOpt(
  3088. 'foo', handler=lambda sub: sub.add_parser('foo')))
  3089. CONF(['foo'])
  3090. def test_attrs_subparser_failure(self):
  3091. CONF = cfg.ConfigOpts()
  3092. CONF.register_cli_opt(cfg.SubCommandOpt(
  3093. 'foo', handler=lambda sub: sub.add_parser('foo')))
  3094. self.assertRaises(SystemExit, CONF, ['foo', 'bar'])
  3095. class TildeExpansionTestCase(BaseTestCase):
  3096. def test_config_file_tilde(self):
  3097. homedir = os.path.expanduser('~')
  3098. tmpfile = tempfile.mktemp(dir=homedir, prefix='cfg-', suffix='.conf')
  3099. tmpbase = os.path.basename(tmpfile)
  3100. try:
  3101. self.conf(['--config-file', os.path.join('~', tmpbase)])
  3102. except cfg.ConfigFilesNotFoundError as cfnfe:
  3103. self.assertIn(homedir, str(cfnfe))
  3104. self.useFixture(fixtures.MonkeyPatch(
  3105. 'os.path.exists',
  3106. lambda p: p == tmpfile))
  3107. self.assertEqual(tmpfile, self.conf.find_file(tmpbase))
  3108. def test_config_dir_tilde(self):
  3109. homedir = os.path.expanduser('~')
  3110. try:
  3111. tmpdir = tempfile.mkdtemp(dir=homedir,
  3112. prefix='cfg-',
  3113. suffix='.d')
  3114. tmpfile = os.path.join(tmpdir, 'foo.conf')
  3115. self.useFixture(fixtures.MonkeyPatch(
  3116. 'glob.glob',
  3117. lambda p: [tmpfile]))
  3118. e = self.assertRaises(cfg.ConfigFilesNotFoundError,
  3119. self.conf,
  3120. ['--config-dir',
  3121. os.path.join('~',
  3122. os.path.basename(tmpdir))]
  3123. )
  3124. self.assertIn(tmpdir, str(e))
  3125. finally:
  3126. try:
  3127. shutil.rmtree(tmpdir)
  3128. except OSError as exc:
  3129. if exc.errno != 2:
  3130. raise
  3131. class SubCommandTestCase(BaseTestCase):
  3132. def test_sub_command(self):
  3133. def add_parsers(subparsers):
  3134. sub = subparsers.add_parser('a')
  3135. sub.add_argument('bar', type=int)
  3136. self.conf.register_cli_opt(
  3137. cfg.SubCommandOpt('cmd', handler=add_parsers))
  3138. self.assertTrue(hasattr(self.conf, 'cmd'))
  3139. self.conf(['a', '10'])
  3140. self.assertTrue(hasattr(self.conf.cmd, 'name'))
  3141. self.assertTrue(hasattr(self.conf.cmd, 'bar'))
  3142. self.assertEqual('a', self.conf.cmd.name)
  3143. self.assertEqual(10, self.conf.cmd.bar)
  3144. def test_sub_command_with_parent(self):
  3145. def add_parsers(subparsers):
  3146. parent = argparse.ArgumentParser(add_help=False)
  3147. parent.add_argument('bar', type=int)
  3148. subparsers.add_parser('a', parents=[parent])
  3149. self.conf.register_cli_opt(
  3150. cfg.SubCommandOpt('cmd', handler=add_parsers))
  3151. self.assertTrue(hasattr(self.conf, 'cmd'))
  3152. self.conf(['a', '10'])
  3153. self.assertTrue(hasattr(self.conf.cmd, 'name'))
  3154. self.assertTrue(hasattr(self.conf.cmd, 'bar'))
  3155. self.assertEqual('a', self.conf.cmd.name)
  3156. self.assertEqual(10, self.conf.cmd.bar)
  3157. def test_sub_command_with_dest(self):
  3158. def add_parsers(subparsers):
  3159. subparsers.add_parser('a')
  3160. self.conf.register_cli_opt(
  3161. cfg.SubCommandOpt('cmd', dest='command', handler=add_parsers))
  3162. self.assertTrue(hasattr(self.conf, 'command'))
  3163. self.conf(['a'])
  3164. self.assertEqual('a', self.conf.command.name)
  3165. def test_sub_command_with_group(self):
  3166. def add_parsers(subparsers):
  3167. sub = subparsers.add_parser('a')
  3168. sub.add_argument('--bar', choices='XYZ')
  3169. self.conf.register_cli_opt(
  3170. cfg.SubCommandOpt('cmd', handler=add_parsers), group='blaa')
  3171. self.assertTrue(hasattr(self.conf, 'blaa'))
  3172. self.assertTrue(hasattr(self.conf.blaa, 'cmd'))
  3173. self.conf(['a', '--bar', 'Z'])
  3174. self.assertTrue(hasattr(self.conf.blaa.cmd, 'name'))
  3175. self.assertTrue(hasattr(self.conf.blaa.cmd, 'bar'))
  3176. self.assertEqual('a', self.conf.blaa.cmd.name)
  3177. self.assertEqual('Z', self.conf.blaa.cmd.bar)
  3178. def test_sub_command_not_cli(self):
  3179. self.conf.register_opt(cfg.SubCommandOpt('cmd'))
  3180. self.conf([])
  3181. def test_sub_command_resparse(self):
  3182. def add_parsers(subparsers):
  3183. subparsers.add_parser('a')
  3184. self.conf.register_cli_opt(
  3185. cfg.SubCommandOpt('cmd', handler=add_parsers))
  3186. foo_opt = cfg.StrOpt('foo')
  3187. self.conf.register_cli_opt(foo_opt)
  3188. self.conf(['--foo=bar', 'a'])
  3189. self.assertTrue(hasattr(self.conf.cmd, 'name'))
  3190. self.assertEqual('a', self.conf.cmd.name)
  3191. self.assertTrue(hasattr(self.conf, 'foo'))
  3192. self.assertEqual('bar', self.conf.foo)
  3193. self.conf.clear()
  3194. self.conf.unregister_opt(foo_opt)
  3195. self.conf(['a'])
  3196. self.assertTrue(hasattr(self.conf.cmd, 'name'))
  3197. self.assertEqual('a', self.conf.cmd.name)
  3198. self.assertFalse(hasattr(self.conf, 'foo'))
  3199. def test_sub_command_no_handler(self):
  3200. self.conf.register_cli_opt(cfg.SubCommandOpt('cmd'))
  3201. self.useFixture(fixtures.MonkeyPatch('sys.stderr', moves.StringIO()))
  3202. self.assertRaises(SystemExit, self.conf, [])
  3203. self.assertIn('error', sys.stderr.getvalue())
  3204. def test_sub_command_with_help(self):
  3205. def add_parsers(subparsers):
  3206. subparsers.add_parser('a')
  3207. self.conf.register_cli_opt(cfg.SubCommandOpt('cmd',
  3208. title='foo foo',
  3209. description='bar bar',
  3210. help='blaa blaa',
  3211. handler=add_parsers))
  3212. self.useFixture(fixtures.MonkeyPatch('sys.stdout', moves.StringIO()))
  3213. self.assertRaises(SystemExit, self.conf, ['--help'])
  3214. self.assertIn('foo foo', sys.stdout.getvalue())
  3215. self.assertIn('bar bar', sys.stdout.getvalue())
  3216. self.assertIn('blaa blaa', sys.stdout.getvalue())
  3217. def test_sub_command_errors(self):
  3218. def add_parsers(subparsers):
  3219. sub = subparsers.add_parser('a')
  3220. sub.add_argument('--bar')
  3221. self.conf.register_cli_opt(cfg.BoolOpt('bar'))
  3222. self.conf.register_cli_opt(
  3223. cfg.SubCommandOpt('cmd', handler=add_parsers))
  3224. self.conf(['a'])
  3225. self.assertRaises(cfg.DuplicateOptError, getattr, self.conf.cmd, 'bar')
  3226. self.assertRaises(cfg.NoSuchOptError, getattr, self.conf.cmd, 'foo')
  3227. def test_sub_command_multiple(self):
  3228. self.conf.register_cli_opt(cfg.SubCommandOpt('cmd1'))
  3229. self.conf.register_cli_opt(cfg.SubCommandOpt('cmd2'))
  3230. self.useFixture(fixtures.MonkeyPatch('sys.stderr', moves.StringIO()))
  3231. self.assertRaises(SystemExit, self.conf, [])
  3232. self.assertIn('multiple', sys.stderr.getvalue())
  3233. class SetDefaultsTestCase(BaseTestCase):
  3234. def test_default_to_none(self):
  3235. opts = [cfg.StrOpt('foo', default='foo')]
  3236. self.conf.register_opts(opts)
  3237. cfg.set_defaults(opts, foo=None)
  3238. self.conf([])
  3239. self.assertIsNone(self.conf.foo)
  3240. def test_default_from_none(self):
  3241. opts = [cfg.StrOpt('foo')]
  3242. self.conf.register_opts(opts)
  3243. cfg.set_defaults(opts, foo='bar')
  3244. self.conf([])
  3245. self.assertEqual('bar', self.conf.foo)
  3246. def test_change_default(self):
  3247. opts = [cfg.StrOpt('foo', default='foo')]
  3248. self.conf.register_opts(opts)
  3249. cfg.set_defaults(opts, foo='bar')
  3250. self.conf([])
  3251. self.assertEqual('bar', self.conf.foo)
  3252. def test_change_default_many(self):
  3253. opts = [cfg.StrOpt('foo', default='foo'),
  3254. cfg.StrOpt('foo2', default='foo2')]
  3255. self.conf.register_opts(opts)
  3256. cfg.set_defaults(opts, foo='bar', foo2='bar2')
  3257. self.conf([])
  3258. self.assertEqual('bar', self.conf.foo)
  3259. self.assertEqual('bar2', self.conf.foo2)
  3260. def test_group_default_to_none(self):
  3261. opts = [cfg.StrOpt('foo', default='foo')]
  3262. self.conf.register_opts(opts, group='blaa')
  3263. cfg.set_defaults(opts, foo=None)
  3264. self.conf([])
  3265. self.assertIsNone(self.conf.blaa.foo)
  3266. def test_group_default_from_none(self):
  3267. opts = [cfg.StrOpt('foo')]
  3268. self.conf.register_opts(opts, group='blaa')
  3269. cfg.set_defaults(opts, foo='bar')
  3270. self.conf([])
  3271. self.assertEqual('bar', self.conf.blaa.foo)
  3272. def test_group_change_default(self):
  3273. opts = [cfg.StrOpt('foo', default='foo')]
  3274. self.conf.register_opts(opts, group='blaa')
  3275. cfg.set_defaults(opts, foo='bar')
  3276. self.conf([])
  3277. self.assertEqual('bar', self.conf.blaa.foo)
  3278. class DeprecatedOptionsTestCase(BaseTestCase):
  3279. def test_deprecated_opts_equal(self):
  3280. d1 = cfg.DeprecatedOpt('oldfoo', group='oldgroup')
  3281. d2 = cfg.DeprecatedOpt('oldfoo', group='oldgroup')
  3282. self.assertEqual(d1, d2)
  3283. def test_deprecated_opts_not_equal(self):
  3284. d1 = cfg.DeprecatedOpt('oldfoo', group='oldgroup')
  3285. d2 = cfg.DeprecatedOpt('oldfoo2', group='oldgroup')
  3286. self.assertNotEqual(d1, d2)
  3287. class MultipleDeprecatedOptionsTestCase(BaseTestCase):
  3288. def test_conf_file_override_use_deprecated_name_and_group(self):
  3289. self.conf.register_group(cfg.OptGroup('blaa'))
  3290. self.conf.register_opt(cfg.StrOpt('foo',
  3291. deprecated_name='oldfoo',
  3292. deprecated_group='oldgroup'),
  3293. group='blaa')
  3294. paths = self.create_tempfiles([('test',
  3295. '[oldgroup]\n'
  3296. 'oldfoo = bar\n')])
  3297. self.conf(['--config-file', paths[0]])
  3298. self.assertEqual('bar', self.conf.blaa.foo)
  3299. def test_conf_file_override_use_deprecated_opts(self):
  3300. self.conf.register_group(cfg.OptGroup('blaa'))
  3301. oldopts = [cfg.DeprecatedOpt('oldfoo', group='oldgroup')]
  3302. self.conf.register_opt(cfg.StrOpt('foo', deprecated_opts=oldopts),
  3303. group='blaa')
  3304. paths = self.create_tempfiles([('test',
  3305. '[oldgroup]\n'
  3306. 'oldfoo = bar\n')])
  3307. self.conf(['--config-file', paths[0]])
  3308. self.assertEqual('bar', self.conf.blaa.foo)
  3309. def test_conf_file_override_use_deprecated_multi_opts(self):
  3310. self.conf.register_group(cfg.OptGroup('blaa'))
  3311. oldopts = [cfg.DeprecatedOpt('oldfoo', group='oldgroup'),
  3312. cfg.DeprecatedOpt('oldfoo2', group='oldgroup2')]
  3313. self.conf.register_opt(cfg.StrOpt('foo', deprecated_opts=oldopts),
  3314. group='blaa')
  3315. paths = self.create_tempfiles([('test',
  3316. '[oldgroup2]\n'
  3317. 'oldfoo2 = bar\n')])
  3318. self.conf(['--config-file', paths[0]])
  3319. self.assertEqual('bar', self.conf.blaa.foo)
  3320. class MultipleDeprecatedCliOptionsTestCase(BaseTestCase):
  3321. def test_conf_file_override_use_deprecated_name_and_group(self):
  3322. self.conf.register_group(cfg.OptGroup('blaa'))
  3323. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3324. deprecated_name='oldfoo',
  3325. deprecated_group='oldgroup'),
  3326. group='blaa')
  3327. paths = self.create_tempfiles([('test',
  3328. '[oldgroup]\n'
  3329. 'oldfoo = bar\n')])
  3330. self.conf(['--config-file', paths[0]])
  3331. self.assertEqual('bar', self.conf.blaa.foo)
  3332. def test_conf_file_override_use_deprecated_opts(self):
  3333. self.conf.register_group(cfg.OptGroup('blaa'))
  3334. oldopts = [cfg.DeprecatedOpt('oldfoo', group='oldgroup')]
  3335. self.conf.register_cli_opt(cfg.StrOpt('foo', deprecated_opts=oldopts),
  3336. group='blaa')
  3337. paths = self.create_tempfiles([('test',
  3338. '[oldgroup]\n'
  3339. 'oldfoo = bar\n')])
  3340. self.conf(['--config-file', paths[0]])
  3341. self.assertEqual('bar', self.conf.blaa.foo)
  3342. def test_conf_file_override_use_deprecated_multi_opts(self):
  3343. self.conf.register_group(cfg.OptGroup('blaa'))
  3344. oldopts = [cfg.DeprecatedOpt('oldfoo', group='oldgroup'),
  3345. cfg.DeprecatedOpt('oldfoo2', group='oldgroup2')]
  3346. self.conf.register_cli_opt(cfg.StrOpt('foo', deprecated_opts=oldopts),
  3347. group='blaa')
  3348. paths = self.create_tempfiles([('test',
  3349. '[oldgroup2]\n'
  3350. 'oldfoo2 = bar\n')])
  3351. self.conf(['--config-file', paths[0]])
  3352. self.assertEqual('bar', self.conf.blaa.foo)
  3353. def test_conf_file_common_deprecated_group(self):
  3354. self.conf.register_group(cfg.OptGroup('foo'))
  3355. self.conf.register_group(cfg.OptGroup('bar'))
  3356. oldopts = [cfg.DeprecatedOpt('foo', group='DEFAULT')]
  3357. self.conf.register_opt(cfg.StrOpt('common_opt',
  3358. deprecated_opts=oldopts),
  3359. group='bar')
  3360. self.conf.register_opt(cfg.StrOpt('common_opt',
  3361. deprecated_opts=oldopts),
  3362. group='foo')
  3363. paths = self.create_tempfiles([('test',
  3364. '[DEFAULT]\n'
  3365. 'foo = bla\n')])
  3366. self.conf(['--config-file', paths[0]])
  3367. self.assertEqual('bla', self.conf.foo.common_opt)
  3368. self.assertEqual('bla', self.conf.bar.common_opt)
  3369. paths = self.create_tempfiles([('test',
  3370. '[DEFAULT]\n'
  3371. 'foo = bla\n'
  3372. '[bar]\n'
  3373. 'common_opt = blabla\n')])
  3374. self.conf(['--config-file', paths[0]])
  3375. self.assertEqual('bla', self.conf.foo.common_opt)
  3376. self.assertEqual('blabla', self.conf.bar.common_opt)
  3377. paths = self.create_tempfiles([('test',
  3378. '[foo]\n'
  3379. 'common_opt = bla\n'
  3380. '[bar]\n'
  3381. 'common_opt = blabla\n')])
  3382. self.conf(['--config-file', paths[0]])
  3383. self.assertEqual('bla', self.conf.foo.common_opt)
  3384. self.assertEqual('blabla', self.conf.bar.common_opt)
  3385. class ChoicesTestCase(BaseTestCase):
  3386. def test_choice_default(self):
  3387. self.conf.register_cli_opt(cfg.StrOpt('protocol',
  3388. default='http',
  3389. choices=['http', 'https', 'ftp']))
  3390. self.conf([])
  3391. self.assertEqual('http', self.conf.protocol)
  3392. def test_choice_good(self):
  3393. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3394. choices=['bar1', 'bar2']))
  3395. self.conf(['--foo', 'bar1'])
  3396. self.assertEqual('bar1', self.conf.foo)
  3397. def test_choice_bad(self):
  3398. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3399. choices=['bar1', 'bar2']))
  3400. self.assertRaises(SystemExit, self.conf, ['--foo', 'bar3'])
  3401. def test_conf_file_choice_value(self):
  3402. self.conf.register_opt(cfg.StrOpt('foo',
  3403. choices=['bar1', 'bar2']))
  3404. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = bar1\n')])
  3405. self.conf(['--config-file', paths[0]])
  3406. self.assertTrue(hasattr(self.conf, 'foo'))
  3407. self.assertEqual('bar1', self.conf.foo)
  3408. def test_conf_file_choice_empty_value(self):
  3409. self.conf.register_opt(cfg.StrOpt('foo',
  3410. choices=['', 'bar1', 'bar2']))
  3411. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = \n')])
  3412. self.conf(['--config-file', paths[0]])
  3413. self.assertTrue(hasattr(self.conf, 'foo'))
  3414. self.assertEqual('', self.conf.foo)
  3415. def test_conf_file_choice_none_value(self):
  3416. self.conf.register_opt(cfg.StrOpt('foo',
  3417. default=None,
  3418. choices=[None, 'bar1', 'bar2']))
  3419. paths = self.create_tempfiles([('test', '[DEFAULT]\n''\n')])
  3420. self.conf(['--config-file', paths[0]])
  3421. self.assertTrue(hasattr(self.conf, 'foo'))
  3422. self.assertIsNone(self.conf.foo)
  3423. def test_conf_file_bad_choice_value(self):
  3424. self.conf.register_opt(cfg.StrOpt('foo',
  3425. choices=['bar1', 'bar2']))
  3426. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = bar3\n')])
  3427. self.conf(['--config-file', paths[0]])
  3428. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'foo')
  3429. self.assertRaises(ValueError, getattr, self.conf, 'foo')
  3430. def test_conf_file_choice_value_override(self):
  3431. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3432. choices=['baar', 'baaar']))
  3433. paths = self.create_tempfiles([('1',
  3434. '[DEFAULT]\n'
  3435. 'foo = baar\n'),
  3436. ('2',
  3437. '[DEFAULT]\n'
  3438. 'foo = baaar\n')])
  3439. self.conf(['--foo', 'baar',
  3440. '--config-file', paths[0],
  3441. '--config-file', paths[1]])
  3442. self.assertTrue(hasattr(self.conf, 'foo'))
  3443. self.assertEqual('baaar', self.conf.foo)
  3444. def test_conf_file_choice_bad_default(self):
  3445. self.assertRaises(cfg.DefaultValueError, cfg.StrOpt, 'foo',
  3446. choices=['baar', 'baaar'], default='foobaz')
  3447. class PortChoicesTestCase(BaseTestCase):
  3448. def test_choice_default(self):
  3449. self.conf.register_cli_opt(cfg.PortOpt('port',
  3450. default=455,
  3451. choices=[80, 455]))
  3452. self.conf([])
  3453. self.assertEqual(455, self.conf.port)
  3454. def test_choice_good_with_list(self):
  3455. self.conf.register_cli_opt(cfg.PortOpt('port',
  3456. choices=[80, 8080]))
  3457. self.conf(['--port', '80'])
  3458. self.assertEqual(80, self.conf.port)
  3459. def test_choice_good_with_tuple(self):
  3460. self.conf.register_cli_opt(cfg.PortOpt('port',
  3461. choices=(80, 8080)))
  3462. self.conf(['--port', '80'])
  3463. self.assertEqual(80, self.conf.port)
  3464. def test_choice_bad(self):
  3465. self.conf.register_cli_opt(cfg.PortOpt('port',
  3466. choices=[80, 8080]))
  3467. self.assertRaises(SystemExit, self.conf, ['--port', '8181'])
  3468. def test_choice_out_range(self):
  3469. self.assertRaisesRegexp(ValueError, 'out of bounds',
  3470. cfg.PortOpt, 'port', choices=[80, 65537, 0])
  3471. def test_conf_file_choice_value(self):
  3472. self.conf.register_opt(cfg.PortOpt('port',
  3473. choices=[80, 8080]))
  3474. paths = self.create_tempfiles([('test', '[DEFAULT]\n''port = 80\n')])
  3475. self.conf(['--config-file', paths[0]])
  3476. self.assertTrue(hasattr(self.conf, 'port'))
  3477. self.assertEqual(80, self.conf.port)
  3478. def test_conf_file_bad_choice_value(self):
  3479. self.conf.register_opt(cfg.PortOpt('port',
  3480. choices=[80, 8080]))
  3481. paths = self.create_tempfiles([('test', '[DEFAULT]\n''port = 8181\n')])
  3482. self.conf(['--config-file', paths[0]])
  3483. self.assertRaises(cfg.ConfigFileValueError, self.conf._get, 'port')
  3484. self.assertRaises(ValueError, getattr, self.conf, 'port')
  3485. def test_conf_file_choice_value_override(self):
  3486. self.conf.register_cli_opt(cfg.PortOpt('port',
  3487. choices=[80, 8080]))
  3488. paths = self.create_tempfiles([('1',
  3489. '[DEFAULT]\n'
  3490. 'port = 80\n'),
  3491. ('2',
  3492. '[DEFAULT]\n'
  3493. 'port = 8080\n')])
  3494. self.conf(['--port', '80',
  3495. '--config-file', paths[0],
  3496. '--config-file', paths[1]])
  3497. self.assertTrue(hasattr(self.conf, 'port'))
  3498. self.assertEqual(8080, self.conf.port)
  3499. def test_conf_file_choice_bad_default(self):
  3500. self.assertRaises(cfg.DefaultValueError, cfg.PortOpt, 'port',
  3501. choices=[80, 8080], default=8181)
  3502. class RegexTestCase(BaseTestCase):
  3503. def test_regex_good(self):
  3504. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3505. regex='foo|bar'))
  3506. self.conf(['--foo', 'bar'])
  3507. self.assertEqual('bar', self.conf.foo)
  3508. self.conf(['--foo', 'foo'])
  3509. self.assertEqual('foo', self.conf.foo)
  3510. self.conf(['--foo', 'foobar'])
  3511. self.assertEqual('foobar', self.conf.foo)
  3512. def test_regex_bad(self):
  3513. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3514. regex='bar'))
  3515. self.assertRaises(SystemExit, self.conf, ['--foo', 'foo'])
  3516. def test_conf_file_regex_value(self):
  3517. self.conf.register_opt(cfg.StrOpt('foo',
  3518. regex='bar'))
  3519. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = bar\n')])
  3520. self.conf(['--config-file', paths[0]])
  3521. self.assertTrue(hasattr(self.conf, 'foo'))
  3522. self.assertEqual('bar', self.conf.foo)
  3523. def test_conf_file_regex_bad_value(self):
  3524. self.conf.register_opt(cfg.StrOpt('foo',
  3525. regex='bar'))
  3526. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = other\n')])
  3527. self.conf(['--config-file', paths[0]])
  3528. self.assertRaisesRegex(cfg.ConfigFileValueError, "doesn't match regex",
  3529. self.conf._get, 'foo')
  3530. self.assertRaisesRegex(ValueError, "doesn't match regex",
  3531. getattr, self.conf, 'foo')
  3532. def test_regex_with_choice(self):
  3533. self.assertRaises(ValueError, cfg.StrOpt,
  3534. 'foo', choices=['bar1'], regex='bar2')
  3535. class QuotesTestCase(BaseTestCase):
  3536. def test_quotes_good(self):
  3537. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3538. quotes=True))
  3539. self.conf(['--foo', '"foobar1"'])
  3540. self.assertEqual('foobar1', self.conf.foo)
  3541. self.conf(['--foo', "'foobar2'"])
  3542. self.assertEqual('foobar2', self.conf.foo)
  3543. self.conf(['--foo', 'foobar3'])
  3544. self.assertEqual('foobar3', self.conf.foo)
  3545. self.conf(['--foo', 'foobar4"'])
  3546. self.assertEqual('foobar4"', self.conf.foo)
  3547. def test_quotes_bad(self):
  3548. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3549. quotes=True))
  3550. self.assertRaises(SystemExit, self.conf, ['--foo', '"foobar\''])
  3551. self.assertRaises(SystemExit, self.conf, ['--foo', '\'foobar"'])
  3552. self.assertRaises(SystemExit, self.conf, ['--foo', '"foobar'])
  3553. self.assertRaises(SystemExit, self.conf, ['--foo', "'foobar"])
  3554. def test_conf_file_quotes_good_value(self):
  3555. self.conf.register_opt(cfg.StrOpt('foo',
  3556. quotes=True))
  3557. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = "bar"\n')])
  3558. self.conf(['--config-file', paths[0]])
  3559. self.assertTrue(hasattr(self.conf, 'foo'))
  3560. self.assertEqual('bar', self.conf.foo)
  3561. def test_conf_file_quotes_bad_value(self):
  3562. self.conf.register_opt(cfg.StrOpt('foo',
  3563. quotes=True))
  3564. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = "bar\n')])
  3565. self.conf(['--config-file', paths[0]])
  3566. self.assertRaisesRegex(cfg.ConfigFileValueError, 'Non-closed quote:',
  3567. self.conf._get, 'foo')
  3568. self.assertRaisesRegex(ValueError, 'Non-closed quote:',
  3569. getattr, self.conf, 'foo')
  3570. class IgnoreCaseTestCase(BaseTestCase):
  3571. def test_ignore_case_with_choices(self):
  3572. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3573. ignore_case=True,
  3574. choices=['bar1',
  3575. 'bar2',
  3576. 'BAR3']))
  3577. self.conf(['--foo', 'bAr1'])
  3578. self.assertEqual('bAr1', self.conf.foo)
  3579. self.conf(['--foo', 'BaR2'])
  3580. self.assertEqual('BaR2', self.conf.foo)
  3581. self.conf(['--foo', 'baR3'])
  3582. self.assertEqual('baR3', self.conf.foo)
  3583. def test_ignore_case_with_regex(self):
  3584. self.conf.register_cli_opt(cfg.StrOpt('foo',
  3585. ignore_case=True,
  3586. regex='fOO|bar'))
  3587. self.conf(['--foo', 'foo'])
  3588. self.assertEqual('foo', self.conf.foo)
  3589. self.conf(['--foo', 'Bar'])
  3590. self.assertEqual('Bar', self.conf.foo)
  3591. self.conf(['--foo', 'FOObar'])
  3592. self.assertEqual('FOObar', self.conf.foo)
  3593. def test_conf_file_ignore_case_with_choices(self):
  3594. self.conf.register_opt(cfg.StrOpt('foo',
  3595. ignore_case=True,
  3596. choices=['bar1', 'bar2', 'BAR3']))
  3597. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = bAr2\n')])
  3598. self.conf(['--config-file', paths[0]])
  3599. self.assertTrue(hasattr(self.conf, 'foo'))
  3600. self.assertEqual('bAr2', self.conf.foo)
  3601. def test_conf_file_ignore_case_with_regex(self):
  3602. self.conf.register_opt(cfg.StrOpt('foo',
  3603. ignore_case=True,
  3604. regex='bAr'))
  3605. paths = self.create_tempfiles([('test', '[DEFAULT]\n''foo = BaR\n')])
  3606. self.conf(['--config-file', paths[0]])
  3607. self.assertTrue(hasattr(self.conf, 'foo'))
  3608. self.assertEqual('BaR', self.conf.foo)
  3609. class StrOptMaxLengthTestCase(BaseTestCase):
  3610. def test_stropt_max_length_good(self):
  3611. self.conf.register_cli_opt(cfg.StrOpt('foo', max_length=5))
  3612. self.conf(['--foo', '12345'])
  3613. self.assertEqual('12345', self.conf.foo)
  3614. def test_stropt_max_length_bad(self):
  3615. self.conf.register_cli_opt(cfg.StrOpt('foo', max_length=5))
  3616. self.assertRaises(SystemExit, self.conf, ['--foo', '123456'])
  3617. class URIOptMaxLengthTestCase(BaseTestCase):
  3618. def test_uriopt_max_length_good(self):
  3619. self.conf.register_cli_opt(cfg.URIOpt('foo', max_length=30))
  3620. self.conf(['--foo', 'http://www.example.com'])
  3621. self.assertEqual('http://www.example.com', self.conf.foo)
  3622. def test_uriopt_max_length_bad(self):
  3623. self.conf.register_cli_opt(cfg.URIOpt('foo', max_length=30))
  3624. self.assertRaises(SystemExit, self.conf,
  3625. ['--foo', 'http://www.example.com/versions'])
  3626. class URIOptSchemesTestCase(BaseTestCase):
  3627. def test_uriopt_schemes_good(self):
  3628. self.conf.register_cli_opt(cfg.URIOpt('foo', schemes=['http', 'ftp']))
  3629. self.conf(['--foo', 'http://www.example.com'])
  3630. self.assertEqual('http://www.example.com', self.conf.foo)
  3631. self.conf(['--foo', 'ftp://example.com/archives'])
  3632. self.assertEqual('ftp://example.com/archives', self.conf.foo)
  3633. def test_uriopt_schemes_bad(self):
  3634. self.conf.register_cli_opt(cfg.URIOpt('foo', schemes=['http', 'ftp']))
  3635. self.assertRaises(SystemExit, self.conf,
  3636. ['--foo', 'https://www.example.com'])
  3637. self.assertRaises(SystemExit, self.conf,
  3638. ['--foo', 'file://www.example.com'])
  3639. class PrintHelpTestCase(base.BaseTestCase):
  3640. def test_print_help_without_init(self):
  3641. conf = cfg.ConfigOpts()
  3642. conf.register_opts([])
  3643. self.assertRaises(cfg.NotInitializedError,
  3644. conf.print_help)
  3645. def test_print_help_with_clear(self):
  3646. conf = cfg.ConfigOpts()
  3647. conf.register_opts([])
  3648. conf([])
  3649. conf.clear()
  3650. self.assertRaises(cfg.NotInitializedError,
  3651. conf.print_help)
  3652. class OptTestCase(base.BaseTestCase):
  3653. def test_opt_eq(self):
  3654. d1 = cfg.ListOpt('oldfoo')
  3655. d2 = cfg.ListOpt('oldfoo')
  3656. self.assertEqual(d1, d2)
  3657. def test_opt_not_eq(self):
  3658. d1 = cfg.ListOpt('oldfoo')
  3659. d2 = cfg.ListOpt('oldbar')
  3660. self.assertNotEqual(d1, d2)
  3661. def test_illegal_name(self):
  3662. self.assertRaises(ValueError, cfg.BoolOpt, '_foo')
  3663. class SectionsTestCase(BaseTestCase):
  3664. def test_list_all_sections(self):
  3665. paths = self.create_tempfiles([('test.ini',
  3666. '[DEFAULT]\n'
  3667. 'foo = bar\n'
  3668. '[BLAA]\n'
  3669. 'bar = foo\n'),
  3670. ('test2.ini',
  3671. '[DEFAULT]\n'
  3672. 'foo = bar\n'
  3673. '[BLAA]\n'
  3674. 'bar = foo\n')])
  3675. self.conf(args=[], default_config_files=paths)
  3676. self.assertEqual(['BLAA', 'DEFAULT'],
  3677. self.conf.list_all_sections())
  3678. def test_list_all_sections_post_mutate(self):
  3679. paths = self.create_tempfiles([('test.ini',
  3680. '[DEFAULT]\n'
  3681. 'foo = bar\n'
  3682. '[BLAA]\n'
  3683. 'bar = foo\n'),
  3684. ('test2.ini',
  3685. '[WOMBAT]\n'
  3686. 'woo = war\n'
  3687. '[BLAA]\n'
  3688. 'bar = foo\n')])
  3689. self.conf(args=[], default_config_files=paths[:1])
  3690. self.assertEqual(['BLAA', 'DEFAULT'],
  3691. self.conf.list_all_sections())
  3692. shutil.copy(paths[1], paths[0])
  3693. self.conf.mutate_config_files()
  3694. self.assertEqual(['BLAA', 'DEFAULT', 'WOMBAT'],
  3695. self.conf.list_all_sections())
  3696. class DeprecationWarningTestBase(BaseTestCase):
  3697. def setUp(self):
  3698. super(DeprecationWarningTestBase, self).setUp()
  3699. self.log_fixture = self.useFixture(fixtures.FakeLogger())
  3700. self._parser_class = cfg.MultiConfigParser
  3701. class DeprecationWarningTestScenarios(DeprecationWarningTestBase):
  3702. scenarios = [('default-deprecated', dict(deprecated=True,
  3703. group='DEFAULT')),
  3704. ('default-not-deprecated', dict(deprecated=False,
  3705. group='DEFAULT')),
  3706. ('other-deprecated', dict(deprecated=True,
  3707. group='other')),
  3708. ('other-not-deprecated', dict(deprecated=False,
  3709. group='other')),
  3710. ]
  3711. def test_deprecated_logging(self):
  3712. self.conf.register_opt(cfg.StrOpt('foo', deprecated_name='bar'))
  3713. self.conf.register_group(cfg.OptGroup('other'))
  3714. self.conf.register_opt(cfg.StrOpt('foo', deprecated_name='bar'),
  3715. group='other')
  3716. if self.deprecated:
  3717. content = 'bar=baz'
  3718. else:
  3719. content = 'foo=baz'
  3720. paths = self.create_tempfiles([('test',
  3721. '[' + self.group + ']\n' +
  3722. content + '\n')])
  3723. self.conf(['--config-file', paths[0]])
  3724. # Reference these twice to verify they only get logged once
  3725. if self.group == 'DEFAULT':
  3726. self.assertEqual('baz', self.conf.foo)
  3727. self.assertEqual('baz', self.conf.foo)
  3728. else:
  3729. self.assertEqual('baz', self.conf.other.foo)
  3730. self.assertEqual('baz', self.conf.other.foo)
  3731. if self.deprecated:
  3732. expected = (self._parser_class._deprecated_opt_message %
  3733. {'dep_option': 'bar',
  3734. 'dep_group': self.group,
  3735. 'option': 'foo',
  3736. 'group': self.group} + '\n')
  3737. else:
  3738. expected = ''
  3739. self.assertEqual(expected, self.log_fixture.output)
  3740. class DeprecationWarningTests(DeprecationWarningTestBase):
  3741. def test_DeprecatedOpt(self):
  3742. default_deprecated = [cfg.DeprecatedOpt('bar')]
  3743. other_deprecated = [cfg.DeprecatedOpt('baz', group='other')]
  3744. self.conf.register_group(cfg.OptGroup('other'))
  3745. self.conf.register_opt(cfg.StrOpt('foo',
  3746. deprecated_opts=default_deprecated))
  3747. self.conf.register_opt(cfg.StrOpt('foo',
  3748. deprecated_opts=other_deprecated),
  3749. group='other')
  3750. paths = self.create_tempfiles([('test',
  3751. '[DEFAULT]\n' +
  3752. 'bar=baz\n' +
  3753. '[other]\n' +
  3754. 'baz=baz\n')])
  3755. self.conf(['--config-file', paths[0]])
  3756. self.assertEqual('baz', self.conf.foo)
  3757. self.assertEqual('baz', self.conf.other.foo)
  3758. self.assertIn('Option "bar" from group "DEFAULT"',
  3759. self.log_fixture.output)
  3760. self.assertIn('Option "baz" from group "other"',
  3761. self.log_fixture.output)
  3762. def test_check_deprecated(self):
  3763. parser = self._parser_class()
  3764. deprecated_list = [('DEFAULT', 'bar')]
  3765. parser._check_deprecated(('DEFAULT', 'bar'), (None, 'foo'),
  3766. deprecated_list)
  3767. self.assert_message_logged('bar', 'DEFAULT', 'foo', 'DEFAULT')
  3768. def assert_message_logged(self, deprecated_name, deprecated_group,
  3769. current_name, current_group):
  3770. expected = (self._parser_class._deprecated_opt_message %
  3771. {'dep_option': deprecated_name,
  3772. 'dep_group': deprecated_group,
  3773. 'option': current_name,
  3774. 'group': current_group}
  3775. )
  3776. self.assertEqual(expected + '\n', self.log_fixture.output)
  3777. def test_deprecated_for_removal(self):
  3778. self.conf.register_opt(cfg.StrOpt('foo',
  3779. deprecated_for_removal=True))
  3780. self.conf.register_opt(cfg.StrOpt('bar',
  3781. deprecated_for_removal=True))
  3782. paths = self.create_tempfiles([('test',
  3783. '[DEFAULT]\n' +
  3784. 'foo=bar\n')])
  3785. self.conf(['--config-file', paths[0]])
  3786. # Multiple references should be logged only once.
  3787. self.assertEqual('bar', self.conf.foo)
  3788. self.assertEqual('bar', self.conf.foo)
  3789. # Options not set in the config should not be logged.
  3790. self.assertIsNone(self.conf.bar)
  3791. expected = ('Option "foo" from group "DEFAULT" is deprecated for '
  3792. 'removal. Its value may be silently ignored in the '
  3793. 'future.\n')
  3794. self.assertEqual(expected, self.log_fixture.output)
  3795. def test_deprecated_for_removal_with_group(self):
  3796. self.conf.register_group(cfg.OptGroup('other'))
  3797. self.conf.register_opt(cfg.StrOpt('foo',
  3798. deprecated_for_removal=True),
  3799. group='other')
  3800. self.conf.register_opt(cfg.StrOpt('bar',
  3801. deprecated_for_removal=True),
  3802. group='other')
  3803. paths = self.create_tempfiles([('test',
  3804. '[other]\n' +
  3805. 'foo=bar\n')])
  3806. self.conf(['--config-file', paths[0]])
  3807. # Multiple references should be logged only once.
  3808. self.assertEqual('bar', self.conf.other.foo)
  3809. self.assertEqual('bar', self.conf.other.foo)
  3810. # Options not set in the config should not be logged.
  3811. self.assertIsNone(self.conf.other.bar)
  3812. expected = ('Option "foo" from group "other" is deprecated for '
  3813. 'removal. Its value may be silently ignored in the '
  3814. 'future.\n')
  3815. self.assertEqual(expected, self.log_fixture.output)
  3816. def test_deprecated_with_dest(self):
  3817. self.conf.register_group(cfg.OptGroup('other'))
  3818. self.conf.register_opt(cfg.StrOpt('foo-bar', deprecated_name='bar',
  3819. dest='foo'),
  3820. group='other')
  3821. content = 'bar=baz'
  3822. paths = self.create_tempfiles([('test',
  3823. '[other]\n' +
  3824. content + '\n')])
  3825. self.conf(['--config-file', paths[0]])
  3826. self.assertEqual('baz', self.conf.other.foo)
  3827. expected = (self._parser_class._deprecated_opt_message %
  3828. {'dep_option': 'bar',
  3829. 'dep_group': 'other',
  3830. 'option': 'foo-bar',
  3831. 'group': 'other'} + '\n')
  3832. self.assertEqual(expected, self.log_fixture.output)