Development of an internal social media platform with personalised dashboards for students
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.

unittest_lint.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2009 Charles Hebert <charles.hebert@logilab.fr>
  4. # Copyright (c) 2011-2014 Google, Inc.
  5. # Copyright (c) 2012 Kevin Jing Qiu <kevin.jing.qiu@gmail.com>
  6. # Copyright (c) 2012 Anthony VEREZ <anthony.verez.external@cassidian.com>
  7. # Copyright (c) 2012 FELD Boris <lothiraldan@gmail.com>
  8. # Copyright (c) 2013-2017 Claudiu Popa <pcmanticore@gmail.com>
  9. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  10. # Copyright (c) 2015 Florian Bruhin <me@the-compiler.org>
  11. # Copyright (c) 2015 Noam Yorav-Raphael <noamraph@gmail.com>
  12. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  13. # Copyright (c) 2016-2017 Derek Gustafson <degustaf@gmail.com>
  14. # Copyright (c) 2016 Glenn Matthews <glenn@e-dad.net>
  15. # Copyright (c) 2016 Glenn Matthews <glmatthe@cisco.com>
  16. # Copyright (c) 2017 Craig Citro <craigcitro@gmail.com>
  17. # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
  18. # Copyright (c) 2017 Ville Skyttä <ville.skytta@iki.fi>
  19. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  20. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  21. from contextlib import contextmanager
  22. import sys
  23. import os
  24. import re
  25. import tempfile
  26. from shutil import rmtree
  27. from os import getcwd, chdir
  28. from os.path import join, basename, dirname, isdir, abspath, sep
  29. import six
  30. from six.moves import reload_module
  31. from pylint import config, lint
  32. from pylint.lint import PyLinter, Run, preprocess_options, ArgumentPreprocessingError
  33. from pylint.utils import MSG_STATE_SCOPE_CONFIG, MSG_STATE_SCOPE_MODULE, MSG_STATE_CONFIDENCE, \
  34. MessagesStore, MessageDefinition, FileState, tokenize_module
  35. from pylint.exceptions import InvalidMessageError, UnknownMessageError
  36. import pylint.testutils as testutils
  37. from pylint.reporters import text
  38. from pylint import checkers
  39. from pylint.checkers.utils import check_messages
  40. from pylint import exceptions
  41. from pylint import interfaces
  42. import pytest
  43. if os.name == 'java':
  44. if os._name == 'nt':
  45. HOME = 'USERPROFILE'
  46. else:
  47. HOME = 'HOME'
  48. else:
  49. if sys.platform == 'win32':
  50. HOME = 'USERPROFILE'
  51. else:
  52. HOME = 'HOME'
  53. try:
  54. PYPY_VERSION_INFO = sys.pypy_version_info
  55. except AttributeError:
  56. PYPY_VERSION_INFO = None
  57. @contextmanager
  58. def fake_home():
  59. folder = tempfile.mkdtemp('fake-home')
  60. old_home = os.environ.get(HOME)
  61. try:
  62. os.environ[HOME] = folder
  63. yield
  64. finally:
  65. os.environ.pop('PYLINTRC', '')
  66. if old_home is None:
  67. del os.environ[HOME]
  68. else:
  69. os.environ[HOME] = old_home
  70. rmtree(folder, ignore_errors=True)
  71. def remove(file):
  72. try:
  73. os.remove(file)
  74. except OSError:
  75. pass
  76. HERE = abspath(dirname(__file__))
  77. INPUTDIR = join(HERE, 'input')
  78. @contextmanager
  79. def tempdir():
  80. """Create a temp directory and change the current location to it.
  81. This is supposed to be used with a *with* statement.
  82. """
  83. tmp = tempfile.mkdtemp()
  84. # Get real path of tempfile, otherwise test fail on mac os x
  85. current_dir = getcwd()
  86. chdir(tmp)
  87. abs_tmp = abspath('.')
  88. try:
  89. yield abs_tmp
  90. finally:
  91. chdir(current_dir)
  92. rmtree(abs_tmp)
  93. def create_files(paths, chroot='.'):
  94. """Creates directories and files found in <path>.
  95. :param paths: list of relative paths to files or directories
  96. :param chroot: the root directory in which paths will be created
  97. >>> from os.path import isdir, isfile
  98. >>> isdir('/tmp/a')
  99. False
  100. >>> create_files(['a/b/foo.py', 'a/b/c/', 'a/b/c/d/e.py'], '/tmp')
  101. >>> isdir('/tmp/a')
  102. True
  103. >>> isdir('/tmp/a/b/c')
  104. True
  105. >>> isfile('/tmp/a/b/c/d/e.py')
  106. True
  107. >>> isfile('/tmp/a/b/foo.py')
  108. True
  109. """
  110. dirs, files = set(), set()
  111. for path in paths:
  112. path = join(chroot, path)
  113. filename = basename(path)
  114. # path is a directory path
  115. if filename == '':
  116. dirs.add(path)
  117. # path is a filename path
  118. else:
  119. dirs.add(dirname(path))
  120. files.add(path)
  121. for dirpath in dirs:
  122. if not isdir(dirpath):
  123. os.makedirs(dirpath)
  124. for filepath in files:
  125. open(filepath, 'w').close()
  126. @pytest.fixture
  127. def fake_path():
  128. orig = list(sys.path)
  129. fake = [1, 2, 3]
  130. sys.path[:] = fake
  131. yield fake
  132. sys.path[:] = orig
  133. def test_no_args(fake_path):
  134. with lint.fix_import_path([]):
  135. assert sys.path == ["."] + fake_path
  136. assert sys.path == fake_path
  137. @pytest.mark.parametrize("case", [
  138. ['a/b/'],
  139. ['a/b'],
  140. ['a/b/__init__.py'],
  141. ['a/'],
  142. ['a'],
  143. ])
  144. def test_one_arg(fake_path, case):
  145. with tempdir() as chroot:
  146. create_files(['a/b/__init__.py'])
  147. expected = [join(chroot, 'a')] + ["."] + fake_path
  148. assert sys.path == fake_path
  149. with lint.fix_import_path(case):
  150. assert sys.path == expected
  151. assert sys.path == fake_path
  152. @pytest.mark.parametrize("case", [
  153. ['a/b', 'a/c'],
  154. ['a/c/', 'a/b/'],
  155. ['a/b/__init__.py', 'a/c/__init__.py'],
  156. ['a', 'a/c/__init__.py'],
  157. ])
  158. def test_two_similar_args(fake_path, case):
  159. with tempdir() as chroot:
  160. create_files(['a/b/__init__.py', 'a/c/__init__.py'])
  161. expected = [join(chroot, 'a')] + ["."] + fake_path
  162. assert sys.path == fake_path
  163. with lint.fix_import_path(case):
  164. assert sys.path == expected
  165. assert sys.path == fake_path
  166. @pytest.mark.parametrize("case", [
  167. ['a/b/c/__init__.py', 'a/d/__init__.py', 'a/e/f.py'],
  168. ['a/b/c', 'a', 'a/e'],
  169. ['a/b/c', 'a', 'a/b/c', 'a/e', 'a'],
  170. ])
  171. def test_more_args(fake_path, case):
  172. with tempdir() as chroot:
  173. create_files(['a/b/c/__init__.py', 'a/d/__init__.py', 'a/e/f.py'])
  174. expected = [
  175. join(chroot, suffix)
  176. for suffix in [sep.join(('a', 'b')), 'a', sep.join(('a', 'e'))]
  177. ] + ["."] + fake_path
  178. assert sys.path == fake_path
  179. with lint.fix_import_path(case):
  180. assert sys.path == expected
  181. assert sys.path == fake_path
  182. @pytest.fixture(scope='module')
  183. def disable(disable):
  184. return ['I']
  185. @pytest.fixture(scope='module')
  186. def reporter(reporter):
  187. return testutils.TestReporter
  188. @pytest.fixture
  189. def init_linter(linter):
  190. linter.open()
  191. linter.set_current_module('toto')
  192. linter.file_state = FileState('toto')
  193. return linter
  194. def test_pylint_visit_method_taken_in_account(linter):
  195. class CustomChecker(checkers.BaseChecker):
  196. __implements__ = interfaces.IAstroidChecker
  197. name = 'custom'
  198. msgs = {'W9999': ('', 'custom', '')}
  199. @check_messages('custom')
  200. def visit_class(self, _):
  201. pass
  202. linter.register_checker(CustomChecker(linter))
  203. linter.open()
  204. out = six.moves.StringIO()
  205. linter.set_reporter(text.TextReporter(out))
  206. linter.check('abc')
  207. def test_enable_message(init_linter):
  208. linter = init_linter
  209. assert linter.is_message_enabled('W0101')
  210. assert linter.is_message_enabled('W0102')
  211. linter.disable('W0101', scope='package')
  212. linter.disable('W0102', scope='module', line=1)
  213. assert not linter.is_message_enabled('W0101')
  214. assert not linter.is_message_enabled('W0102', 1)
  215. linter.set_current_module('tutu')
  216. assert not linter.is_message_enabled('W0101')
  217. assert linter.is_message_enabled('W0102')
  218. linter.enable('W0101', scope='package')
  219. linter.enable('W0102', scope='module', line=1)
  220. assert linter.is_message_enabled('W0101')
  221. assert linter.is_message_enabled('W0102', 1)
  222. def test_enable_message_category(init_linter):
  223. linter = init_linter
  224. assert linter.is_message_enabled('W0101')
  225. assert linter.is_message_enabled('C0202')
  226. linter.disable('W', scope='package')
  227. linter.disable('C', scope='module', line=1)
  228. assert not linter.is_message_enabled('W0101')
  229. assert linter.is_message_enabled('C0202')
  230. assert not linter.is_message_enabled('C0202', line=1)
  231. linter.set_current_module('tutu')
  232. assert not linter.is_message_enabled('W0101')
  233. assert linter.is_message_enabled('C0202')
  234. linter.enable('W', scope='package')
  235. linter.enable('C', scope='module', line=1)
  236. assert linter.is_message_enabled('W0101')
  237. assert linter.is_message_enabled('C0202')
  238. assert linter.is_message_enabled('C0202', line=1)
  239. def test_message_state_scope(init_linter):
  240. class FakeConfig(object):
  241. confidence = ['HIGH']
  242. linter = init_linter
  243. linter.disable('C0202')
  244. assert MSG_STATE_SCOPE_CONFIG == linter.get_message_state_scope('C0202')
  245. linter.disable('W0101', scope='module', line=3)
  246. assert MSG_STATE_SCOPE_CONFIG == linter.get_message_state_scope('C0202')
  247. assert MSG_STATE_SCOPE_MODULE == linter.get_message_state_scope('W0101', 3)
  248. linter.enable('W0102', scope='module', line=3)
  249. assert MSG_STATE_SCOPE_MODULE == linter.get_message_state_scope('W0102', 3)
  250. linter.config = FakeConfig()
  251. assert MSG_STATE_CONFIDENCE == \
  252. linter.get_message_state_scope('this-is-bad',
  253. confidence=interfaces.INFERENCE)
  254. def test_enable_message_block(init_linter):
  255. linter = init_linter
  256. linter.open()
  257. filepath = join(INPUTDIR, 'func_block_disable_msg.py')
  258. linter.set_current_module('func_block_disable_msg')
  259. astroid = linter.get_ast(filepath, 'func_block_disable_msg')
  260. linter.process_tokens(tokenize_module(astroid))
  261. fs = linter.file_state
  262. fs.collect_block_lines(linter.msgs_store, astroid)
  263. # global (module level)
  264. assert linter.is_message_enabled('W0613')
  265. assert linter.is_message_enabled('E1101')
  266. # meth1
  267. assert linter.is_message_enabled('W0613', 13)
  268. # meth2
  269. assert not linter.is_message_enabled('W0613', 18)
  270. # meth3
  271. assert not linter.is_message_enabled('E1101', 24)
  272. assert linter.is_message_enabled('E1101', 26)
  273. # meth4
  274. assert not linter.is_message_enabled('E1101', 32)
  275. assert linter.is_message_enabled('E1101', 36)
  276. # meth5
  277. assert not linter.is_message_enabled('E1101', 42)
  278. assert not linter.is_message_enabled('E1101', 43)
  279. assert linter.is_message_enabled('E1101', 46)
  280. assert not linter.is_message_enabled('E1101', 49)
  281. assert not linter.is_message_enabled('E1101', 51)
  282. # meth6
  283. assert not linter.is_message_enabled('E1101', 57)
  284. assert linter.is_message_enabled('E1101', 61)
  285. assert not linter.is_message_enabled('E1101', 64)
  286. assert not linter.is_message_enabled('E1101', 66)
  287. assert linter.is_message_enabled('E0602', 57)
  288. assert linter.is_message_enabled('E0602', 61)
  289. assert not linter.is_message_enabled('E0602', 62)
  290. assert linter.is_message_enabled('E0602', 64)
  291. assert linter.is_message_enabled('E0602', 66)
  292. # meth7
  293. assert not linter.is_message_enabled('E1101', 70)
  294. assert linter.is_message_enabled('E1101', 72)
  295. assert linter.is_message_enabled('E1101', 75)
  296. assert linter.is_message_enabled('E1101', 77)
  297. fs = linter.file_state
  298. assert 17 == fs._suppression_mapping['W0613', 18]
  299. assert 30 == fs._suppression_mapping['E1101', 33]
  300. assert ('E1101', 46) not in fs._suppression_mapping
  301. assert 1 == fs._suppression_mapping['C0302', 18]
  302. assert 1 == fs._suppression_mapping['C0302', 50]
  303. # This is tricky. While the disable in line 106 is disabling
  304. # both 108 and 110, this is usually not what the user wanted.
  305. # Therefore, we report the closest previous disable comment.
  306. assert 106 == fs._suppression_mapping['E1101', 108]
  307. assert 109 == fs._suppression_mapping['E1101', 110]
  308. def test_enable_by_symbol(init_linter):
  309. """messages can be controlled by symbolic names.
  310. The state is consistent across symbols and numbers.
  311. """
  312. linter = init_linter
  313. assert linter.is_message_enabled('W0101')
  314. assert linter.is_message_enabled('unreachable')
  315. assert linter.is_message_enabled('W0102')
  316. assert linter.is_message_enabled('dangerous-default-value')
  317. linter.disable('unreachable', scope='package')
  318. linter.disable('dangerous-default-value', scope='module', line=1)
  319. assert not linter.is_message_enabled('W0101')
  320. assert not linter.is_message_enabled('unreachable')
  321. assert not linter.is_message_enabled('W0102', 1)
  322. assert not linter.is_message_enabled('dangerous-default-value', 1)
  323. linter.set_current_module('tutu')
  324. assert not linter.is_message_enabled('W0101')
  325. assert not linter.is_message_enabled('unreachable')
  326. assert linter.is_message_enabled('W0102')
  327. assert linter.is_message_enabled('dangerous-default-value')
  328. linter.enable('unreachable', scope='package')
  329. linter.enable('dangerous-default-value', scope='module', line=1)
  330. assert linter.is_message_enabled('W0101')
  331. assert linter.is_message_enabled('unreachable')
  332. assert linter.is_message_enabled('W0102', 1)
  333. assert linter.is_message_enabled('dangerous-default-value', 1)
  334. def test_enable_report(linter):
  335. assert linter.report_is_enabled('RP0001')
  336. linter.disable('RP0001')
  337. assert not linter.report_is_enabled('RP0001')
  338. linter.enable('RP0001')
  339. assert linter.report_is_enabled('RP0001')
  340. def test_report_output_format_aliased(linter):
  341. text.register(linter)
  342. linter.set_option('output-format', 'text')
  343. assert linter.reporter.__class__.__name__ == 'TextReporter'
  344. def test_set_unsupported_reporter(linter):
  345. text.register(linter)
  346. with pytest.raises(exceptions.InvalidReporterError):
  347. linter.set_option('output-format', 'missing.module.Class')
  348. def test_set_option_1(linter):
  349. linter.set_option('disable', 'C0111,W0234')
  350. assert not linter.is_message_enabled('C0111')
  351. assert not linter.is_message_enabled('W0234')
  352. assert linter.is_message_enabled('W0113')
  353. assert not linter.is_message_enabled('missing-docstring')
  354. assert not linter.is_message_enabled('non-iterator-returned')
  355. def test_set_option_2(linter):
  356. linter.set_option('disable', ('C0111', 'W0234'))
  357. assert not linter.is_message_enabled('C0111')
  358. assert not linter.is_message_enabled('W0234')
  359. assert linter.is_message_enabled('W0113')
  360. assert not linter.is_message_enabled('missing-docstring')
  361. assert not linter.is_message_enabled('non-iterator-returned')
  362. def test_enable_checkers(linter):
  363. linter.disable('design')
  364. assert not ('design' in [c.name for c in linter.prepare_checkers()])
  365. linter.enable('design')
  366. assert 'design' in [c.name for c in linter.prepare_checkers()]
  367. def test_errors_only(linter):
  368. linter.error_mode()
  369. checkers = linter.prepare_checkers()
  370. checker_names = set(c.name for c in checkers)
  371. should_not = set(('design', 'format', 'metrics',
  372. 'miscellaneous', 'similarities'))
  373. assert set() == should_not & checker_names
  374. def test_disable_similar(linter):
  375. linter.set_option('disable', 'RP0801')
  376. linter.set_option('disable', 'R0801')
  377. assert not ('similarities' in [c.name for c in linter.prepare_checkers()])
  378. def test_disable_alot(linter):
  379. """check that we disabled a lot of checkers"""
  380. linter.set_option('reports', False)
  381. linter.set_option('disable', 'R,C,W')
  382. checker_names = [c.name for c in linter.prepare_checkers()]
  383. for cname in ('design', 'metrics', 'similarities'):
  384. assert not (cname in checker_names), cname
  385. def test_addmessage(linter):
  386. linter.set_reporter(testutils.TestReporter())
  387. linter.open()
  388. linter.set_current_module('0123')
  389. linter.add_message('C0301', line=1, args=(1, 2))
  390. linter.add_message('line-too-long', line=2, args=(3, 4))
  391. assert ['C: 1: Line too long (1/2)', 'C: 2: Line too long (3/4)'] == \
  392. linter.reporter.messages
  393. def test_addmessage_invalid(linter):
  394. linter.set_reporter(testutils.TestReporter())
  395. linter.open()
  396. linter.set_current_module('0123')
  397. with pytest.raises(InvalidMessageError) as cm:
  398. linter.add_message('line-too-long', args=(1, 2))
  399. assert str(cm.value) == "Message C0301 must provide line, got None"
  400. with pytest.raises(InvalidMessageError) as cm:
  401. linter.add_message('line-too-long', line=2, node='fake_node', args=(1, 2))
  402. assert str(cm.value) == "Message C0301 must only provide line, got line=2, node=fake_node"
  403. with pytest.raises(InvalidMessageError) as cm:
  404. linter.add_message('C0321')
  405. assert str(cm.value) == "Message C0321 must provide Node, got None"
  406. def test_init_hooks_called_before_load_plugins():
  407. with pytest.raises(RuntimeError):
  408. Run(['--load-plugins', 'unexistant', '--init-hook', 'raise RuntimeError'])
  409. with pytest.raises(RuntimeError):
  410. Run(['--init-hook', 'raise RuntimeError', '--load-plugins', 'unexistant'])
  411. def test_analyze_explicit_script(linter):
  412. linter.set_reporter(testutils.TestReporter())
  413. linter.check(os.path.join(os.path.dirname(__file__), 'data', 'ascript'))
  414. assert ['C: 2: Line too long (175/100)'] == linter.reporter.messages
  415. def test_python3_checker_disabled(linter):
  416. checker_names = [c.name for c in linter.prepare_checkers()]
  417. assert 'python3' not in checker_names
  418. linter.set_option('enable', 'python3')
  419. checker_names = [c.name for c in linter.prepare_checkers()]
  420. assert 'python3' in checker_names
  421. def test_full_documentation(linter):
  422. out = six.StringIO()
  423. linter.print_full_documentation(out)
  424. output = out.getvalue()
  425. # A few spot checks only
  426. for re_str in [
  427. # autogenerated text
  428. "^Pylint global options and switches$",
  429. "Verbatim name of the checker is ``python3``",
  430. # messages
  431. "^:old-octal-literal \\(E1608\\):",
  432. # options
  433. "^:dummy-variables-rgx:",
  434. ]:
  435. regexp = re.compile(re_str, re.MULTILINE)
  436. assert re.search(regexp, output)
  437. @pytest.fixture
  438. def pop_pylintrc():
  439. os.environ.pop('PYLINTRC', None)
  440. @pytest.mark.usefixture("pop_pylintrc")
  441. def test_pylint_home():
  442. uhome = os.path.expanduser('~')
  443. if uhome == '~':
  444. expected = '.pylint.d'
  445. else:
  446. expected = os.path.join(uhome, '.pylint.d')
  447. assert config.PYLINT_HOME == expected
  448. try:
  449. pylintd = join(tempfile.gettempdir(), '.pylint.d')
  450. os.environ['PYLINTHOME'] = pylintd
  451. try:
  452. reload_module(config)
  453. assert config.PYLINT_HOME == pylintd
  454. finally:
  455. try:
  456. os.remove(pylintd)
  457. except:
  458. pass
  459. finally:
  460. del os.environ['PYLINTHOME']
  461. @pytest.mark.skipif(PYPY_VERSION_INFO,
  462. reason="TOX runs this test from within the repo and finds "
  463. "the project's pylintrc.")
  464. @pytest.mark.usefixture("pop_pylintrc")
  465. def test_pylintrc():
  466. with fake_home():
  467. current_dir = getcwd()
  468. chdir(os.path.dirname(os.path.abspath(sys.executable)))
  469. try:
  470. assert config.find_pylintrc() is None
  471. os.environ['PYLINTRC'] = join(tempfile.gettempdir(),
  472. '.pylintrc')
  473. assert config.find_pylintrc() is None
  474. os.environ['PYLINTRC'] = '.'
  475. assert config.find_pylintrc() is None
  476. finally:
  477. chdir(current_dir)
  478. reload_module(config)
  479. @pytest.mark.usefixture("pop_pylintrc")
  480. def test_pylintrc_parentdir():
  481. with tempdir() as chroot:
  482. create_files(['a/pylintrc', 'a/b/__init__.py', 'a/b/pylintrc',
  483. 'a/b/c/__init__.py', 'a/b/c/d/__init__.py',
  484. 'a/b/c/d/e/.pylintrc'])
  485. with fake_home():
  486. assert config.find_pylintrc() is None
  487. results = {'a' : join(chroot, 'a', 'pylintrc'),
  488. 'a/b' : join(chroot, 'a', 'b', 'pylintrc'),
  489. 'a/b/c' : join(chroot, 'a', 'b', 'pylintrc'),
  490. 'a/b/c/d' : join(chroot, 'a', 'b', 'pylintrc'),
  491. 'a/b/c/d/e' : join(chroot, 'a', 'b', 'c', 'd', 'e', '.pylintrc'),
  492. }
  493. for basedir, expected in results.items():
  494. os.chdir(join(chroot, basedir))
  495. assert config.find_pylintrc() == expected
  496. @pytest.mark.usefixture("pop_pylintrc")
  497. def test_pylintrc_parentdir_no_package():
  498. with tempdir() as chroot:
  499. with fake_home():
  500. create_files(['a/pylintrc', 'a/b/pylintrc', 'a/b/c/d/__init__.py'])
  501. assert config.find_pylintrc() is None
  502. results = {'a' : join(chroot, 'a', 'pylintrc'),
  503. 'a/b' : join(chroot, 'a', 'b', 'pylintrc'),
  504. 'a/b/c' : None,
  505. 'a/b/c/d' : None,
  506. }
  507. for basedir, expected in results.items():
  508. os.chdir(join(chroot, basedir))
  509. assert config.find_pylintrc() == expected
  510. class TestPreprocessOptions(object):
  511. def _callback(self, name, value):
  512. self.args.append((name, value))
  513. def test_value_equal(self):
  514. self.args = []
  515. preprocess_options(['--foo', '--bar=baz', '--qu=ux'],
  516. {'foo': (self._callback, False),
  517. 'qu': (self._callback, True)})
  518. assert [('foo', None), ('qu', 'ux')] == self.args
  519. def test_value_space(self):
  520. self.args = []
  521. preprocess_options(['--qu', 'ux'],
  522. {'qu': (self._callback, True)})
  523. assert [('qu', 'ux')] == self.args
  524. def test_error_missing_expected_value(self):
  525. with pytest.raises(ArgumentPreprocessingError):
  526. preprocess_options(['--foo', '--bar', '--qu=ux'],
  527. {'bar': (None, True)})
  528. with pytest.raises(ArgumentPreprocessingError):
  529. preprocess_options(['--foo', '--bar'],
  530. {'bar': (None, True)})
  531. def test_error_unexpected_value(self):
  532. with pytest.raises(ArgumentPreprocessingError):
  533. preprocess_options(['--foo', '--bar=spam', '--qu=ux'],
  534. {'bar': (None, False)})
  535. @pytest.fixture
  536. def store():
  537. store = MessagesStore()
  538. class Checker(object):
  539. name = 'achecker'
  540. msgs = {
  541. 'W1234': ('message', 'msg-symbol', 'msg description.',
  542. {'old_names': [('W0001', 'old-symbol')]}),
  543. 'E1234': ('Duplicate keyword argument %r in %s call',
  544. 'duplicate-keyword-arg',
  545. 'Used when a function call passes the same keyword argument multiple times.',
  546. {'maxversion': (2, 6)}),
  547. }
  548. store.register_messages(Checker())
  549. return store
  550. class TestMessagesStore(object):
  551. def _compare_messages(self, desc, msg, checkerref=False):
  552. assert desc == msg.format_help(checkerref=checkerref)
  553. def test_check_message_id(self, store):
  554. assert isinstance(store.check_message_id('W1234'), MessageDefinition)
  555. with pytest.raises(UnknownMessageError):
  556. store.check_message_id('YB12')
  557. def test_message_help(self, store):
  558. msg = store.check_message_id('W1234')
  559. self._compare_messages(
  560. ''':msg-symbol (W1234): *message*
  561. msg description. This message belongs to the achecker checker.''',
  562. msg, checkerref=True)
  563. self._compare_messages(
  564. ''':msg-symbol (W1234): *message*
  565. msg description.''',
  566. msg, checkerref=False)
  567. def test_message_help_minmax(self, store):
  568. # build the message manually to be python version independent
  569. msg = store.check_message_id('E1234')
  570. self._compare_messages(
  571. ''':duplicate-keyword-arg (E1234): *Duplicate keyword argument %r in %s call*
  572. Used when a function call passes the same keyword argument multiple times.
  573. This message belongs to the achecker checker. It can't be emitted when using
  574. Python >= 2.6.''',
  575. msg, checkerref=True)
  576. self._compare_messages(
  577. ''':duplicate-keyword-arg (E1234): *Duplicate keyword argument %r in %s call*
  578. Used when a function call passes the same keyword argument multiple times.
  579. This message can't be emitted when using Python >= 2.6.''',
  580. msg, checkerref=False)
  581. def test_list_messages(self, store):
  582. sys.stdout = six.StringIO()
  583. try:
  584. store.list_messages()
  585. output = sys.stdout.getvalue()
  586. finally:
  587. sys.stdout = sys.__stdout__
  588. # cursory examination of the output: we're mostly testing it completes
  589. assert ':msg-symbol (W1234): *message*' in output
  590. def test_add_renamed_message(self, store):
  591. store.add_renamed_message('W1234', 'old-bad-name', 'msg-symbol')
  592. assert 'msg-symbol' == store.check_message_id('W1234').symbol
  593. assert 'msg-symbol' == store.check_message_id('old-bad-name').symbol
  594. def test_add_renamed_message_invalid(self, store):
  595. # conflicting message ID
  596. with pytest.raises(InvalidMessageError) as cm:
  597. store.add_renamed_message(
  598. 'W1234', 'old-msg-symbol', 'duplicate-keyword-arg')
  599. assert str(cm.value) == "Message id 'W1234' is already defined"
  600. # conflicting message symbol
  601. with pytest.raises(InvalidMessageError) as cm:
  602. store.add_renamed_message(
  603. 'W1337', 'msg-symbol', 'duplicate-keyword-arg')
  604. assert str(cm.value) == "Message symbol 'msg-symbol' is already defined"
  605. def test_renamed_message_register(self, store):
  606. assert 'msg-symbol' == store.check_message_id('W0001').symbol
  607. assert 'msg-symbol' == store.check_message_id('old-symbol').symbol
  608. def test_custom_should_analyze_file():
  609. '''Check that we can write custom should_analyze_file that work
  610. even for arguments.
  611. '''
  612. class CustomPyLinter(PyLinter):
  613. def should_analyze_file(self, modname, path, is_argument=False):
  614. if os.path.basename(path) == 'wrong.py':
  615. return False
  616. return super(CustomPyLinter, self).should_analyze_file(
  617. modname, path, is_argument=is_argument)
  618. package_dir = os.path.join(HERE, 'regrtest_data', 'bad_package')
  619. wrong_file = os.path.join(package_dir, 'wrong.py')
  620. reporter = testutils.TestReporter()
  621. linter = CustomPyLinter()
  622. linter.config.persistent = 0
  623. linter.open()
  624. linter.set_reporter(reporter)
  625. try:
  626. sys.path.append(os.path.dirname(package_dir))
  627. linter.check([package_dir, wrong_file])
  628. finally:
  629. sys.path.pop()
  630. messages = reporter.messages
  631. assert len(messages) == 1
  632. assert 'invalid syntax' in messages[0]
  633. def test_filename_with__init__(init_linter):
  634. # This tracks a regression where a file whose name ends in __init__.py,
  635. # such as flycheck__init__.py, would accidentally lead to linting the
  636. # entire containing directory.
  637. reporter = testutils.TestReporter()
  638. linter = init_linter
  639. linter.open()
  640. linter.set_reporter(reporter)
  641. filepath = join(INPUTDIR, 'not__init__.py')
  642. linter.check([filepath])
  643. messages = reporter.messages
  644. assert len(messages) == 0