test_config.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. """Test config, coverage 93%.
  2. (100% for IdleConfParser, IdleUserConfParser*, ConfigChanges).
  3. * Exception is OSError clause in Save method.
  4. Much of IdleConf is also exercised by ConfigDialog and test_configdialog.
  5. """
  6. from idlelib import config
  7. import sys
  8. import os
  9. import tempfile
  10. from test.support import captured_stderr, findfile
  11. import unittest
  12. from unittest import mock
  13. import idlelib
  14. from idlelib.idle_test.mock_idle import Func
  15. # Tests should not depend on fortuitous user configurations.
  16. # They must not affect actual user .cfg files.
  17. # Replace user parsers with empty parsers that cannot be saved
  18. # due to getting '' as the filename when created.
  19. idleConf = config.idleConf
  20. usercfg = idleConf.userCfg
  21. testcfg = {}
  22. usermain = testcfg['main'] = config.IdleUserConfParser('')
  23. userhigh = testcfg['highlight'] = config.IdleUserConfParser('')
  24. userkeys = testcfg['keys'] = config.IdleUserConfParser('')
  25. userextn = testcfg['extensions'] = config.IdleUserConfParser('')
  26. def setUpModule():
  27. idleConf.userCfg = testcfg
  28. idlelib.testing = True
  29. def tearDownModule():
  30. idleConf.userCfg = usercfg
  31. idlelib.testing = False
  32. class IdleConfParserTest(unittest.TestCase):
  33. """Test that IdleConfParser works"""
  34. config = """
  35. [one]
  36. one = false
  37. two = true
  38. three = 10
  39. [two]
  40. one = a string
  41. two = true
  42. three = false
  43. """
  44. def test_get(self):
  45. parser = config.IdleConfParser('')
  46. parser.read_string(self.config)
  47. eq = self.assertEqual
  48. # Test with type argument.
  49. self.assertIs(parser.Get('one', 'one', type='bool'), False)
  50. self.assertIs(parser.Get('one', 'two', type='bool'), True)
  51. eq(parser.Get('one', 'three', type='int'), 10)
  52. eq(parser.Get('two', 'one'), 'a string')
  53. self.assertIs(parser.Get('two', 'two', type='bool'), True)
  54. self.assertIs(parser.Get('two', 'three', type='bool'), False)
  55. # Test without type should fallback to string.
  56. eq(parser.Get('two', 'two'), 'true')
  57. eq(parser.Get('two', 'three'), 'false')
  58. # If option not exist, should return None, or default.
  59. self.assertIsNone(parser.Get('not', 'exist'))
  60. eq(parser.Get('not', 'exist', default='DEFAULT'), 'DEFAULT')
  61. def test_get_option_list(self):
  62. parser = config.IdleConfParser('')
  63. parser.read_string(self.config)
  64. get_list = parser.GetOptionList
  65. self.assertCountEqual(get_list('one'), ['one', 'two', 'three'])
  66. self.assertCountEqual(get_list('two'), ['one', 'two', 'three'])
  67. self.assertEqual(get_list('not exist'), [])
  68. def test_load_nothing(self):
  69. parser = config.IdleConfParser('')
  70. parser.Load()
  71. self.assertEqual(parser.sections(), [])
  72. def test_load_file(self):
  73. # Borrow test/cfgparser.1 from test_configparser.
  74. config_path = findfile('cfgparser.1')
  75. parser = config.IdleConfParser(config_path)
  76. parser.Load()
  77. self.assertEqual(parser.Get('Foo Bar', 'foo'), 'newbar')
  78. self.assertEqual(parser.GetOptionList('Foo Bar'), ['foo'])
  79. class IdleUserConfParserTest(unittest.TestCase):
  80. """Test that IdleUserConfParser works"""
  81. def new_parser(self, path=''):
  82. return config.IdleUserConfParser(path)
  83. def test_set_option(self):
  84. parser = self.new_parser()
  85. parser.add_section('Foo')
  86. # Setting new option in existing section should return True.
  87. self.assertTrue(parser.SetOption('Foo', 'bar', 'true'))
  88. # Setting existing option with same value should return False.
  89. self.assertFalse(parser.SetOption('Foo', 'bar', 'true'))
  90. # Setting exiting option with new value should return True.
  91. self.assertTrue(parser.SetOption('Foo', 'bar', 'false'))
  92. self.assertEqual(parser.Get('Foo', 'bar'), 'false')
  93. # Setting option in new section should create section and return True.
  94. self.assertTrue(parser.SetOption('Bar', 'bar', 'true'))
  95. self.assertCountEqual(parser.sections(), ['Bar', 'Foo'])
  96. self.assertEqual(parser.Get('Bar', 'bar'), 'true')
  97. def test_remove_option(self):
  98. parser = self.new_parser()
  99. parser.AddSection('Foo')
  100. parser.SetOption('Foo', 'bar', 'true')
  101. self.assertTrue(parser.RemoveOption('Foo', 'bar'))
  102. self.assertFalse(parser.RemoveOption('Foo', 'bar'))
  103. self.assertFalse(parser.RemoveOption('Not', 'Exist'))
  104. def test_add_section(self):
  105. parser = self.new_parser()
  106. self.assertEqual(parser.sections(), [])
  107. # Should not add duplicate section.
  108. # Configparser raises DuplicateError, IdleParser not.
  109. parser.AddSection('Foo')
  110. parser.AddSection('Foo')
  111. parser.AddSection('Bar')
  112. self.assertCountEqual(parser.sections(), ['Bar', 'Foo'])
  113. def test_remove_empty_sections(self):
  114. parser = self.new_parser()
  115. parser.AddSection('Foo')
  116. parser.AddSection('Bar')
  117. parser.SetOption('Idle', 'name', 'val')
  118. self.assertCountEqual(parser.sections(), ['Bar', 'Foo', 'Idle'])
  119. parser.RemoveEmptySections()
  120. self.assertEqual(parser.sections(), ['Idle'])
  121. def test_is_empty(self):
  122. parser = self.new_parser()
  123. parser.AddSection('Foo')
  124. parser.AddSection('Bar')
  125. self.assertTrue(parser.IsEmpty())
  126. self.assertEqual(parser.sections(), [])
  127. parser.SetOption('Foo', 'bar', 'false')
  128. parser.AddSection('Bar')
  129. self.assertFalse(parser.IsEmpty())
  130. self.assertCountEqual(parser.sections(), ['Foo'])
  131. def test_save(self):
  132. with tempfile.TemporaryDirectory() as tdir:
  133. path = os.path.join(tdir, 'test.cfg')
  134. parser = self.new_parser(path)
  135. parser.AddSection('Foo')
  136. parser.SetOption('Foo', 'bar', 'true')
  137. # Should save to path when config is not empty.
  138. self.assertFalse(os.path.exists(path))
  139. parser.Save()
  140. self.assertTrue(os.path.exists(path))
  141. # Should remove the file from disk when config is empty.
  142. parser.remove_section('Foo')
  143. parser.Save()
  144. self.assertFalse(os.path.exists(path))
  145. class IdleConfTest(unittest.TestCase):
  146. """Test for idleConf"""
  147. @classmethod
  148. def setUpClass(cls):
  149. cls.config_string = {}
  150. conf = config.IdleConf(_utest=True)
  151. if __name__ != '__main__':
  152. idle_dir = os.path.dirname(__file__)
  153. else:
  154. idle_dir = os.path.abspath(sys.path[0])
  155. for ctype in conf.config_types:
  156. config_path = os.path.join(idle_dir, '../config-%s.def' % ctype)
  157. with open(config_path) as f:
  158. cls.config_string[ctype] = f.read()
  159. cls.orig_warn = config._warn
  160. config._warn = Func()
  161. @classmethod
  162. def tearDownClass(cls):
  163. config._warn = cls.orig_warn
  164. def new_config(self, _utest=False):
  165. return config.IdleConf(_utest=_utest)
  166. def mock_config(self):
  167. """Return a mocked idleConf
  168. Both default and user config used the same config-*.def
  169. """
  170. conf = config.IdleConf(_utest=True)
  171. for ctype in conf.config_types:
  172. conf.defaultCfg[ctype] = config.IdleConfParser('')
  173. conf.defaultCfg[ctype].read_string(self.config_string[ctype])
  174. conf.userCfg[ctype] = config.IdleUserConfParser('')
  175. conf.userCfg[ctype].read_string(self.config_string[ctype])
  176. return conf
  177. @unittest.skipIf(sys.platform.startswith('win'), 'this is test for unix system')
  178. def test_get_user_cfg_dir_unix(self):
  179. # Test to get user config directory under unix.
  180. conf = self.new_config(_utest=True)
  181. # Check normal way should success
  182. with mock.patch('os.path.expanduser', return_value='/home/foo'):
  183. with mock.patch('os.path.exists', return_value=True):
  184. self.assertEqual(conf.GetUserCfgDir(), '/home/foo/.idlerc')
  185. # Check os.getcwd should success
  186. with mock.patch('os.path.expanduser', return_value='~'):
  187. with mock.patch('os.getcwd', return_value='/home/foo/cpython'):
  188. with mock.patch('os.mkdir'):
  189. self.assertEqual(conf.GetUserCfgDir(),
  190. '/home/foo/cpython/.idlerc')
  191. # Check user dir not exists and created failed should raise SystemExit
  192. with mock.patch('os.path.join', return_value='/path/not/exists'):
  193. with self.assertRaises(SystemExit):
  194. with self.assertRaises(FileNotFoundError):
  195. conf.GetUserCfgDir()
  196. @unittest.skipIf(not sys.platform.startswith('win'), 'this is test for Windows system')
  197. def test_get_user_cfg_dir_windows(self):
  198. # Test to get user config directory under Windows.
  199. conf = self.new_config(_utest=True)
  200. # Check normal way should success
  201. with mock.patch('os.path.expanduser', return_value='C:\\foo'):
  202. with mock.patch('os.path.exists', return_value=True):
  203. self.assertEqual(conf.GetUserCfgDir(), 'C:\\foo\\.idlerc')
  204. # Check os.getcwd should success
  205. with mock.patch('os.path.expanduser', return_value='~'):
  206. with mock.patch('os.getcwd', return_value='C:\\foo\\cpython'):
  207. with mock.patch('os.mkdir'):
  208. self.assertEqual(conf.GetUserCfgDir(),
  209. 'C:\\foo\\cpython\\.idlerc')
  210. # Check user dir not exists and created failed should raise SystemExit
  211. with mock.patch('os.path.join', return_value='/path/not/exists'):
  212. with self.assertRaises(SystemExit):
  213. with self.assertRaises(FileNotFoundError):
  214. conf.GetUserCfgDir()
  215. def test_create_config_handlers(self):
  216. conf = self.new_config(_utest=True)
  217. # Mock out idle_dir
  218. idle_dir = '/home/foo'
  219. with mock.patch.dict({'__name__': '__foo__'}):
  220. with mock.patch('os.path.dirname', return_value=idle_dir):
  221. conf.CreateConfigHandlers()
  222. # Check keys are equal
  223. self.assertCountEqual(conf.defaultCfg.keys(), conf.config_types)
  224. self.assertCountEqual(conf.userCfg.keys(), conf.config_types)
  225. # Check conf parser are correct type
  226. for default_parser in conf.defaultCfg.values():
  227. self.assertIsInstance(default_parser, config.IdleConfParser)
  228. for user_parser in conf.userCfg.values():
  229. self.assertIsInstance(user_parser, config.IdleUserConfParser)
  230. # Check config path are correct
  231. for cfg_type, parser in conf.defaultCfg.items():
  232. self.assertEqual(parser.file,
  233. os.path.join(idle_dir, f'config-{cfg_type}.def'))
  234. for cfg_type, parser in conf.userCfg.items():
  235. self.assertEqual(parser.file,
  236. os.path.join(conf.userdir or '#', f'config-{cfg_type}.cfg'))
  237. def test_load_cfg_files(self):
  238. conf = self.new_config(_utest=True)
  239. # Borrow test/cfgparser.1 from test_configparser.
  240. config_path = findfile('cfgparser.1')
  241. conf.defaultCfg['foo'] = config.IdleConfParser(config_path)
  242. conf.userCfg['foo'] = config.IdleUserConfParser(config_path)
  243. # Load all config from path
  244. conf.LoadCfgFiles()
  245. eq = self.assertEqual
  246. # Check defaultCfg is loaded
  247. eq(conf.defaultCfg['foo'].Get('Foo Bar', 'foo'), 'newbar')
  248. eq(conf.defaultCfg['foo'].GetOptionList('Foo Bar'), ['foo'])
  249. # Check userCfg is loaded
  250. eq(conf.userCfg['foo'].Get('Foo Bar', 'foo'), 'newbar')
  251. eq(conf.userCfg['foo'].GetOptionList('Foo Bar'), ['foo'])
  252. def test_save_user_cfg_files(self):
  253. conf = self.mock_config()
  254. with mock.patch('idlelib.config.IdleUserConfParser.Save') as m:
  255. conf.SaveUserCfgFiles()
  256. self.assertEqual(m.call_count, len(conf.userCfg))
  257. def test_get_option(self):
  258. conf = self.mock_config()
  259. eq = self.assertEqual
  260. eq(conf.GetOption('main', 'EditorWindow', 'width'), '80')
  261. eq(conf.GetOption('main', 'EditorWindow', 'width', type='int'), 80)
  262. with mock.patch('idlelib.config._warn') as _warn:
  263. eq(conf.GetOption('main', 'EditorWindow', 'font', type='int'), None)
  264. eq(conf.GetOption('main', 'EditorWindow', 'NotExists'), None)
  265. eq(conf.GetOption('main', 'EditorWindow', 'NotExists', default='NE'), 'NE')
  266. eq(_warn.call_count, 4)
  267. def test_set_option(self):
  268. conf = self.mock_config()
  269. conf.SetOption('main', 'Foo', 'bar', 'newbar')
  270. self.assertEqual(conf.GetOption('main', 'Foo', 'bar'), 'newbar')
  271. def test_get_section_list(self):
  272. conf = self.mock_config()
  273. self.assertCountEqual(
  274. conf.GetSectionList('default', 'main'),
  275. ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme',
  276. 'Keys', 'History', 'HelpFiles'])
  277. self.assertCountEqual(
  278. conf.GetSectionList('user', 'main'),
  279. ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme',
  280. 'Keys', 'History', 'HelpFiles'])
  281. with self.assertRaises(config.InvalidConfigSet):
  282. conf.GetSectionList('foobar', 'main')
  283. with self.assertRaises(config.InvalidConfigType):
  284. conf.GetSectionList('default', 'notexists')
  285. def test_get_highlight(self):
  286. conf = self.mock_config()
  287. eq = self.assertEqual
  288. eq(conf.GetHighlight('IDLE Classic', 'normal'), {'foreground': '#000000',
  289. 'background': '#ffffff'})
  290. # Test cursor (this background should be normal-background)
  291. eq(conf.GetHighlight('IDLE Classic', 'cursor'), {'foreground': 'black',
  292. 'background': '#ffffff'})
  293. # Test get user themes
  294. conf.SetOption('highlight', 'Foobar', 'normal-foreground', '#747474')
  295. conf.SetOption('highlight', 'Foobar', 'normal-background', '#171717')
  296. with mock.patch('idlelib.config._warn'):
  297. eq(conf.GetHighlight('Foobar', 'normal'), {'foreground': '#747474',
  298. 'background': '#171717'})
  299. def test_get_theme_dict(self):
  300. # TODO: finish.
  301. conf = self.mock_config()
  302. # These two should be the same
  303. self.assertEqual(
  304. conf.GetThemeDict('default', 'IDLE Classic'),
  305. conf.GetThemeDict('user', 'IDLE Classic'))
  306. with self.assertRaises(config.InvalidTheme):
  307. conf.GetThemeDict('bad', 'IDLE Classic')
  308. def test_get_current_theme_and_keys(self):
  309. conf = self.mock_config()
  310. self.assertEqual(conf.CurrentTheme(), conf.current_colors_and_keys('Theme'))
  311. self.assertEqual(conf.CurrentKeys(), conf.current_colors_and_keys('Keys'))
  312. def test_current_colors_and_keys(self):
  313. conf = self.mock_config()
  314. self.assertEqual(conf.current_colors_and_keys('Theme'), 'IDLE Classic')
  315. def test_default_keys(self):
  316. current_platform = sys.platform
  317. conf = self.new_config(_utest=True)
  318. sys.platform = 'win32'
  319. self.assertEqual(conf.default_keys(), 'IDLE Classic Windows')
  320. sys.platform = 'darwin'
  321. self.assertEqual(conf.default_keys(), 'IDLE Classic OSX')
  322. sys.platform = 'some-linux'
  323. self.assertEqual(conf.default_keys(), 'IDLE Modern Unix')
  324. # Restore platform
  325. sys.platform = current_platform
  326. def test_get_extensions(self):
  327. userextn.read_string('''
  328. [ZzDummy]
  329. enable = True
  330. [DISABLE]
  331. enable = False
  332. ''')
  333. eq = self.assertEqual
  334. iGE = idleConf.GetExtensions
  335. eq(iGE(shell_only=True), [])
  336. eq(iGE(), ['ZzDummy'])
  337. eq(iGE(editor_only=True), ['ZzDummy'])
  338. eq(iGE(active_only=False), ['ZzDummy', 'DISABLE'])
  339. eq(iGE(active_only=False, editor_only=True), ['ZzDummy', 'DISABLE'])
  340. userextn.remove_section('ZzDummy')
  341. userextn.remove_section('DISABLE')
  342. def test_remove_key_bind_names(self):
  343. conf = self.mock_config()
  344. self.assertCountEqual(
  345. conf.RemoveKeyBindNames(conf.GetSectionList('default', 'extensions')),
  346. ['AutoComplete', 'CodeContext', 'FormatParagraph', 'ParenMatch', 'ZzDummy'])
  347. def test_get_extn_name_for_event(self):
  348. userextn.read_string('''
  349. [ZzDummy]
  350. enable = True
  351. ''')
  352. eq = self.assertEqual
  353. eq(idleConf.GetExtnNameForEvent('z-in'), 'ZzDummy')
  354. eq(idleConf.GetExtnNameForEvent('z-out'), None)
  355. userextn.remove_section('ZzDummy')
  356. def test_get_extension_keys(self):
  357. userextn.read_string('''
  358. [ZzDummy]
  359. enable = True
  360. ''')
  361. self.assertEqual(idleConf.GetExtensionKeys('ZzDummy'),
  362. {'<<z-in>>': ['<Control-Shift-KeyRelease-Insert>']})
  363. userextn.remove_section('ZzDummy')
  364. # need option key test
  365. ## key = ['<Option-Key-2>'] if sys.platform == 'darwin' else ['<Alt-Key-2>']
  366. ## eq(conf.GetExtensionKeys('ZoomHeight'), {'<<zoom-height>>': key})
  367. def test_get_extension_bindings(self):
  368. userextn.read_string('''
  369. [ZzDummy]
  370. enable = True
  371. ''')
  372. eq = self.assertEqual
  373. iGEB = idleConf.GetExtensionBindings
  374. eq(iGEB('NotExists'), {})
  375. expect = {'<<z-in>>': ['<Control-Shift-KeyRelease-Insert>'],
  376. '<<z-out>>': ['<Control-Shift-KeyRelease-Delete>']}
  377. eq(iGEB('ZzDummy'), expect)
  378. userextn.remove_section('ZzDummy')
  379. def test_get_keybinding(self):
  380. conf = self.mock_config()
  381. eq = self.assertEqual
  382. eq(conf.GetKeyBinding('IDLE Modern Unix', '<<copy>>'),
  383. ['<Control-Shift-Key-C>', '<Control-Key-Insert>'])
  384. eq(conf.GetKeyBinding('IDLE Classic Unix', '<<copy>>'),
  385. ['<Alt-Key-w>', '<Meta-Key-w>'])
  386. eq(conf.GetKeyBinding('IDLE Classic Windows', '<<copy>>'),
  387. ['<Control-Key-c>', '<Control-Key-C>'])
  388. eq(conf.GetKeyBinding('IDLE Classic Mac', '<<copy>>'), ['<Command-Key-c>'])
  389. eq(conf.GetKeyBinding('IDLE Classic OSX', '<<copy>>'), ['<Command-Key-c>'])
  390. # Test keybinding not exists
  391. eq(conf.GetKeyBinding('NOT EXISTS', '<<copy>>'), [])
  392. eq(conf.GetKeyBinding('IDLE Modern Unix', 'NOT EXISTS'), [])
  393. def test_get_current_keyset(self):
  394. current_platform = sys.platform
  395. conf = self.mock_config()
  396. # Ensure that platform isn't darwin
  397. sys.platform = 'some-linux'
  398. self.assertEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys()))
  399. # This should not be the same, since replace <Alt- to <Option-.
  400. # Above depended on config-extensions.def having Alt keys,
  401. # which is no longer true.
  402. # sys.platform = 'darwin'
  403. # self.assertNotEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys()))
  404. # Restore platform
  405. sys.platform = current_platform
  406. def test_get_keyset(self):
  407. conf = self.mock_config()
  408. # Conflict with key set, should be disable to ''
  409. conf.defaultCfg['extensions'].add_section('Foobar')
  410. conf.defaultCfg['extensions'].add_section('Foobar_cfgBindings')
  411. conf.defaultCfg['extensions'].set('Foobar', 'enable', 'True')
  412. conf.defaultCfg['extensions'].set('Foobar_cfgBindings', 'newfoo', '<Key-F3>')
  413. self.assertEqual(conf.GetKeySet('IDLE Modern Unix')['<<newfoo>>'], '')
  414. def test_is_core_binding(self):
  415. # XXX: Should move out the core keys to config file or other place
  416. conf = self.mock_config()
  417. self.assertTrue(conf.IsCoreBinding('copy'))
  418. self.assertTrue(conf.IsCoreBinding('cut'))
  419. self.assertTrue(conf.IsCoreBinding('del-word-right'))
  420. self.assertFalse(conf.IsCoreBinding('not-exists'))
  421. def test_extra_help_source_list(self):
  422. # Test GetExtraHelpSourceList and GetAllExtraHelpSourcesList in same
  423. # place to prevent prepare input data twice.
  424. conf = self.mock_config()
  425. # Test default with no extra help source
  426. self.assertEqual(conf.GetExtraHelpSourceList('default'), [])
  427. self.assertEqual(conf.GetExtraHelpSourceList('user'), [])
  428. with self.assertRaises(config.InvalidConfigSet):
  429. self.assertEqual(conf.GetExtraHelpSourceList('bad'), [])
  430. self.assertCountEqual(
  431. conf.GetAllExtraHelpSourcesList(),
  432. conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user'))
  433. # Add help source to user config
  434. conf.userCfg['main'].SetOption('HelpFiles', '4', 'Python;https://python.org') # This is bad input
  435. conf.userCfg['main'].SetOption('HelpFiles', '3', 'Python:https://python.org') # This is bad input
  436. conf.userCfg['main'].SetOption('HelpFiles', '2', 'Pillow;https://pillow.readthedocs.io/en/latest/')
  437. conf.userCfg['main'].SetOption('HelpFiles', '1', 'IDLE;C:/Programs/Python36/Lib/idlelib/help.html')
  438. self.assertEqual(conf.GetExtraHelpSourceList('user'),
  439. [('IDLE', 'C:/Programs/Python36/Lib/idlelib/help.html', '1'),
  440. ('Pillow', 'https://pillow.readthedocs.io/en/latest/', '2'),
  441. ('Python', 'https://python.org', '4')])
  442. self.assertCountEqual(
  443. conf.GetAllExtraHelpSourcesList(),
  444. conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user'))
  445. def test_get_font(self):
  446. from test.support import requires
  447. from tkinter import Tk
  448. from tkinter.font import Font
  449. conf = self.mock_config()
  450. requires('gui')
  451. root = Tk()
  452. root.withdraw()
  453. f = Font.actual(Font(name='TkFixedFont', exists=True, root=root))
  454. self.assertEqual(
  455. conf.GetFont(root, 'main', 'EditorWindow'),
  456. (f['family'], 10 if f['size'] <= 0 else f['size'], f['weight']))
  457. # Cleanup root
  458. root.destroy()
  459. del root
  460. def test_get_core_keys(self):
  461. conf = self.mock_config()
  462. eq = self.assertEqual
  463. eq(conf.GetCoreKeys()['<<center-insert>>'], ['<Control-l>'])
  464. eq(conf.GetCoreKeys()['<<copy>>'], ['<Control-c>', '<Control-C>'])
  465. eq(conf.GetCoreKeys()['<<history-next>>'], ['<Alt-n>'])
  466. eq(conf.GetCoreKeys('IDLE Classic Windows')['<<center-insert>>'],
  467. ['<Control-Key-l>', '<Control-Key-L>'])
  468. eq(conf.GetCoreKeys('IDLE Classic OSX')['<<copy>>'], ['<Command-Key-c>'])
  469. eq(conf.GetCoreKeys('IDLE Classic Unix')['<<history-next>>'],
  470. ['<Alt-Key-n>', '<Meta-Key-n>'])
  471. eq(conf.GetCoreKeys('IDLE Modern Unix')['<<history-next>>'],
  472. ['<Alt-Key-n>', '<Meta-Key-n>'])
  473. class CurrentColorKeysTest(unittest.TestCase):
  474. """ Test colorkeys function with user config [Theme] and [Keys] patterns.
  475. colorkeys = config.IdleConf.current_colors_and_keys
  476. Test all patterns written by IDLE and some errors
  477. Item 'default' should really be 'builtin' (versus 'custom).
  478. """
  479. colorkeys = idleConf.current_colors_and_keys
  480. default_theme = 'IDLE Classic'
  481. default_keys = idleConf.default_keys()
  482. def test_old_builtin_theme(self):
  483. # On initial installation, user main is blank.
  484. self.assertEqual(self.colorkeys('Theme'), self.default_theme)
  485. # For old default, name2 must be blank.
  486. usermain.read_string('''
  487. [Theme]
  488. default = True
  489. ''')
  490. # IDLE omits 'name' for default old builtin theme.
  491. self.assertEqual(self.colorkeys('Theme'), self.default_theme)
  492. # IDLE adds 'name' for non-default old builtin theme.
  493. usermain['Theme']['name'] = 'IDLE New'
  494. self.assertEqual(self.colorkeys('Theme'), 'IDLE New')
  495. # Erroneous non-default old builtin reverts to default.
  496. usermain['Theme']['name'] = 'non-existent'
  497. self.assertEqual(self.colorkeys('Theme'), self.default_theme)
  498. usermain.remove_section('Theme')
  499. def test_new_builtin_theme(self):
  500. # IDLE writes name2 for new builtins.
  501. usermain.read_string('''
  502. [Theme]
  503. default = True
  504. name2 = IDLE Dark
  505. ''')
  506. self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
  507. # Leftover 'name', not removed, is ignored.
  508. usermain['Theme']['name'] = 'IDLE New'
  509. self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
  510. # Erroneous non-default new builtin reverts to default.
  511. usermain['Theme']['name2'] = 'non-existent'
  512. self.assertEqual(self.colorkeys('Theme'), self.default_theme)
  513. usermain.remove_section('Theme')
  514. def test_user_override_theme(self):
  515. # Erroneous custom name (no definition) reverts to default.
  516. usermain.read_string('''
  517. [Theme]
  518. default = False
  519. name = Custom Dark
  520. ''')
  521. self.assertEqual(self.colorkeys('Theme'), self.default_theme)
  522. # Custom name is valid with matching Section name.
  523. userhigh.read_string('[Custom Dark]\na=b')
  524. self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
  525. # Name2 is ignored.
  526. usermain['Theme']['name2'] = 'non-existent'
  527. self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
  528. usermain.remove_section('Theme')
  529. userhigh.remove_section('Custom Dark')
  530. def test_old_builtin_keys(self):
  531. # On initial installation, user main is blank.
  532. self.assertEqual(self.colorkeys('Keys'), self.default_keys)
  533. # For old default, name2 must be blank, name is always used.
  534. usermain.read_string('''
  535. [Keys]
  536. default = True
  537. name = IDLE Classic Unix
  538. ''')
  539. self.assertEqual(self.colorkeys('Keys'), 'IDLE Classic Unix')
  540. # Erroneous non-default old builtin reverts to default.
  541. usermain['Keys']['name'] = 'non-existent'
  542. self.assertEqual(self.colorkeys('Keys'), self.default_keys)
  543. usermain.remove_section('Keys')
  544. def test_new_builtin_keys(self):
  545. # IDLE writes name2 for new builtins.
  546. usermain.read_string('''
  547. [Keys]
  548. default = True
  549. name2 = IDLE Modern Unix
  550. ''')
  551. self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
  552. # Leftover 'name', not removed, is ignored.
  553. usermain['Keys']['name'] = 'IDLE Classic Unix'
  554. self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
  555. # Erroneous non-default new builtin reverts to default.
  556. usermain['Keys']['name2'] = 'non-existent'
  557. self.assertEqual(self.colorkeys('Keys'), self.default_keys)
  558. usermain.remove_section('Keys')
  559. def test_user_override_keys(self):
  560. # Erroneous custom name (no definition) reverts to default.
  561. usermain.read_string('''
  562. [Keys]
  563. default = False
  564. name = Custom Keys
  565. ''')
  566. self.assertEqual(self.colorkeys('Keys'), self.default_keys)
  567. # Custom name is valid with matching Section name.
  568. userkeys.read_string('[Custom Keys]\na=b')
  569. self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
  570. # Name2 is ignored.
  571. usermain['Keys']['name2'] = 'non-existent'
  572. self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
  573. usermain.remove_section('Keys')
  574. userkeys.remove_section('Custom Keys')
  575. class ChangesTest(unittest.TestCase):
  576. empty = {'main':{}, 'highlight':{}, 'keys':{}, 'extensions':{}}
  577. def load(self): # Test_add_option verifies that this works.
  578. changes = self.changes
  579. changes.add_option('main', 'Msec', 'mitem', 'mval')
  580. changes.add_option('highlight', 'Hsec', 'hitem', 'hval')
  581. changes.add_option('keys', 'Ksec', 'kitem', 'kval')
  582. return changes
  583. loaded = {'main': {'Msec': {'mitem': 'mval'}},
  584. 'highlight': {'Hsec': {'hitem': 'hval'}},
  585. 'keys': {'Ksec': {'kitem':'kval'}},
  586. 'extensions': {}}
  587. def setUp(self):
  588. self.changes = config.ConfigChanges()
  589. def test_init(self):
  590. self.assertEqual(self.changes, self.empty)
  591. def test_add_option(self):
  592. changes = self.load()
  593. self.assertEqual(changes, self.loaded)
  594. changes.add_option('main', 'Msec', 'mitem', 'mval')
  595. self.assertEqual(changes, self.loaded)
  596. def test_save_option(self): # Static function does not touch changes.
  597. save_option = self.changes.save_option
  598. self.assertTrue(save_option('main', 'Indent', 'what', '0'))
  599. self.assertFalse(save_option('main', 'Indent', 'what', '0'))
  600. self.assertEqual(usermain['Indent']['what'], '0')
  601. self.assertTrue(save_option('main', 'Indent', 'use-spaces', '0'))
  602. self.assertEqual(usermain['Indent']['use-spaces'], '0')
  603. self.assertTrue(save_option('main', 'Indent', 'use-spaces', '1'))
  604. self.assertFalse(usermain.has_option('Indent', 'use-spaces'))
  605. usermain.remove_section('Indent')
  606. def test_save_added(self):
  607. changes = self.load()
  608. self.assertTrue(changes.save_all())
  609. self.assertEqual(usermain['Msec']['mitem'], 'mval')
  610. self.assertEqual(userhigh['Hsec']['hitem'], 'hval')
  611. self.assertEqual(userkeys['Ksec']['kitem'], 'kval')
  612. changes.add_option('main', 'Msec', 'mitem', 'mval')
  613. self.assertFalse(changes.save_all())
  614. usermain.remove_section('Msec')
  615. userhigh.remove_section('Hsec')
  616. userkeys.remove_section('Ksec')
  617. def test_save_help(self):
  618. # Any change to HelpFiles overwrites entire section.
  619. changes = self.changes
  620. changes.save_option('main', 'HelpFiles', 'IDLE', 'idledoc')
  621. changes.add_option('main', 'HelpFiles', 'ELDI', 'codeldi')
  622. changes.save_all()
  623. self.assertFalse(usermain.has_option('HelpFiles', 'IDLE'))
  624. self.assertTrue(usermain.has_option('HelpFiles', 'ELDI'))
  625. def test_save_default(self): # Cover 2nd and 3rd false branches.
  626. changes = self.changes
  627. changes.add_option('main', 'Indent', 'use-spaces', '1')
  628. # save_option returns False; cfg_type_changed remains False.
  629. # TODO: test that save_all calls usercfg Saves.
  630. def test_delete_section(self):
  631. changes = self.load()
  632. changes.delete_section('main', 'fake') # Test no exception.
  633. self.assertEqual(changes, self.loaded) # Test nothing deleted.
  634. for cfgtype, section in (('main', 'Msec'), ('keys', 'Ksec')):
  635. testcfg[cfgtype].SetOption(section, 'name', 'value')
  636. changes.delete_section(cfgtype, section)
  637. with self.assertRaises(KeyError):
  638. changes[cfgtype][section] # Test section gone from changes
  639. testcfg[cfgtype][section] # and from mock userCfg.
  640. # TODO test for save call.
  641. def test_clear(self):
  642. changes = self.load()
  643. changes.clear()
  644. self.assertEqual(changes, self.empty)
  645. class WarningTest(unittest.TestCase):
  646. def test_warn(self):
  647. Equal = self.assertEqual
  648. config._warned = set()
  649. with captured_stderr() as stderr:
  650. config._warn('warning', 'key')
  651. Equal(config._warned, {('warning','key')})
  652. Equal(stderr.getvalue(), 'warning'+'\n')
  653. with captured_stderr() as stderr:
  654. config._warn('warning', 'key')
  655. Equal(stderr.getvalue(), '')
  656. with captured_stderr() as stderr:
  657. config._warn('warn2', 'yek')
  658. Equal(config._warned, {('warning','key'), ('warn2','yek')})
  659. Equal(stderr.getvalue(), 'warn2'+'\n')
  660. if __name__ == '__main__':
  661. unittest.main(verbosity=2)