summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDerek Gustafson <degustaf@gmail.com>2016-12-06 15:42:53 +0000
committerDerek Gustafson <degustaf@gmail.com>2016-12-06 16:07:00 +0000
commit4faacf211922fbb5a02260dad36a0dbc9d6b6ca6 (patch)
treee99ebc5faa309c10a08f74b34eea54221d3fd985
parent72ea777b1f601aa8d227b8a7d085f5d2d12471d7 (diff)
downloadpylint-git-4faacf211922fbb5a02260dad36a0dbc9d6b6ca6.tar.gz
Reduce dependency on unittest
-rw-r--r--pylint/test/extensions/test_bad_builtin.py11
-rw-r--r--pylint/test/extensions/test_check_docs.py9
-rw-r--r--pylint/test/extensions/test_check_docs_utils.py247
-rw-r--r--pylint/test/extensions/test_check_mccabe.py11
-rw-r--r--pylint/test/extensions/test_check_raise_docs.py8
-rw-r--r--pylint/test/extensions/test_check_return_docs.py8
-rw-r--r--pylint/test/extensions/test_check_yields_docs.py8
-rw-r--r--pylint/test/extensions/test_docstyle.py9
-rw-r--r--pylint/test/extensions/test_elseif_used.py13
-rw-r--r--pylint/test/extensions/test_redefined.py11
-rw-r--r--pylint/test/test_import_graph.py21
-rw-r--r--pylint/test/test_regr.py23
-rw-r--r--pylint/test/test_self.py8
-rw-r--r--pylint/test/unittest_checker_base.py13
-rw-r--r--pylint/test/unittest_checker_classes.py11
-rw-r--r--pylint/test/unittest_checker_exceptions.py15
-rw-r--r--pylint/test/unittest_checker_format.py11
-rw-r--r--pylint/test/unittest_checker_imports.py9
-rw-r--r--pylint/test/unittest_checker_logging.py10
-rw-r--r--pylint/test/unittest_checker_misc.py8
-rw-r--r--pylint/test/unittest_checker_python3.py18
-rw-r--r--pylint/test/unittest_checker_similar.py145
-rw-r--r--pylint/test/unittest_checker_spelling.py25
-rw-r--r--pylint/test/unittest_checker_stdlib.py7
-rw-r--r--pylint/test/unittest_checker_strings.py15
-rw-r--r--pylint/test/unittest_checker_typecheck.py9
-rw-r--r--pylint/test/unittest_checker_variables.py98
-rw-r--r--pylint/test/unittest_checkers_utils.py143
-rw-r--r--pylint/test/unittest_config.py77
-rw-r--r--pylint/test/unittest_lint.py49
-rw-r--r--pylint/test/unittest_pyreverse_diadefs.py142
-rw-r--r--pylint/test/unittest_pyreverse_inspector.py18
-rw-r--r--pylint/test/unittest_pyreverse_writer.py52
-rw-r--r--pylint/test/unittest_reporters_json.py59
-rw-r--r--pylint/test/unittest_reporting.py25
-rw-r--r--pylint/test/unittest_utils.py82
-rw-r--r--pylint/testutils.py33
37 files changed, 714 insertions, 747 deletions
diff --git a/pylint/test/extensions/test_bad_builtin.py b/pylint/test/extensions/test_bad_builtin.py
index 695fb7576..4fbce9e09 100644
--- a/pylint/test/extensions/test_bad_builtin.py
+++ b/pylint/test/extensions/test_bad_builtin.py
@@ -6,9 +6,7 @@
"""Tests for the pylint checker in :mod:`pylint.extensions.bad_builtin
"""
-import os
import os.path as osp
-import unittest
from pylint import checkers
from pylint.extensions.bad_builtin import BadBuiltinChecker
@@ -16,14 +14,13 @@ from pylint.lint import PyLinter, fix_import_path
from pylint.testutils import MinimalTestReporter
-class BadBuiltinTestCase(unittest.TestCase):
+class TestBadBuiltin():
expected = [
]
-
@classmethod
- def setUpClass(cls):
+ def setup_class(cls):
cls._linter = PyLinter()
cls._linter.set_reporter(MinimalTestReporter())
checkers.initialize(cls._linter)
@@ -43,4 +40,6 @@ class BadBuiltinTestCase(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_check_docs.py b/pylint/test/extensions/test_check_docs.py
index ad2bf02b5..6ea3bcaf6 100644
--- a/pylint/test/extensions/test_check_docs.py
+++ b/pylint/test/extensions/test_check_docs.py
@@ -11,16 +11,17 @@ in particular the parameter documentation checker `DocstringChecker`
"""
from __future__ import division, print_function, absolute_import
-import unittest
import sys
+import pytest
+
import astroid
from pylint.testutils import CheckerTestCase, Message, set_config
from pylint.extensions.docparams import DocstringParameterChecker
-class ParamDocCheckerTest(CheckerTestCase):
+class TestParamDocChecker(CheckerTestCase):
"""Tests for pylint_plugin.ParamDocChecker"""
CHECKER_CLASS = DocstringParameterChecker
@@ -957,7 +958,7 @@ class ParamDocCheckerTest(CheckerTestCase):
):
self._visit_methods_of_class(node)
- @unittest.skipIf(sys.version_info[0] != 3, "Enabled on Python 3")
+ @pytest.mark.skipif(sys.version_info[0] != 3, reason="Enabled on Python 3")
def test_kwonlyargs_are_taken_in_account(self):
node = astroid.extract_node('''
def my_func(arg, *, kwonly, missing_kwonly):
@@ -1228,4 +1229,4 @@ class ParamDocCheckerTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_check_docs_utils.py b/pylint/test/extensions/test_check_docs_utils.py
index 362ef35e8..02fcfc31b 100644
--- a/pylint/test/extensions/test_check_docs_utils.py
+++ b/pylint/test/extensions/test_check_docs_utils.py
@@ -9,136 +9,141 @@ in particular the parameter documentation checker `DocstringChecker`
"""
from __future__ import division, print_function, absolute_import
-import unittest
-import sys
-
import astroid
-from pylint.testutils import CheckerTestCase, Message, set_config
import pylint.extensions._check_docs_utils as utils
-class SpaceIndentationTest(unittest.TestCase):
- """Tests for pylint_plugin.ParamDocChecker"""
-
- def test_space_indentation(self):
- assert utils.space_indentation('abc') == 0
- assert utils.space_indentation('') == 0
- assert utils.space_indentation(' abc') == 2
- assert utils.space_indentation('\n abc') == 0
- assert utils.space_indentation(' \n abc') == 3
-
-class PossibleExcTypesText(unittest.TestCase):
- def test_exception_class(self):
- raise_node = astroid.extract_node('''
- def my_func():
- raise NotImplementedError #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set(["NotImplementedError"])
- assert found == expected
-
- def test_exception_instance(self):
- raise_node = astroid.extract_node('''
- def my_func():
- raise NotImplementedError("Not implemented!") #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set(["NotImplementedError"])
- assert found == expected
-
- def test_rethrow(self):
- raise_node = astroid.extract_node('''
- def my_func():
- try:
- fake_func()
- except RuntimeError:
- raise #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set(["RuntimeError"])
- assert found == expected
-
- def test_nested_in_if_rethrow(self):
- raise_node = astroid.extract_node('''
- def my_func():
- try:
- fake_func()
- except RuntimeError:
- if another_func():
- raise #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set(["RuntimeError"])
- assert found == expected
-
- def test_nested_in_try(self):
- raise_node = astroid.extract_node('''
- def my_func():
- try:
- fake_func()
- except RuntimeError:
- try:
- another_func()
- raise #@
- except NameError:
- pass
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set(["RuntimeError"])
- assert found == expected
-
- def test_nested_in_try_except(self):
- raise_node = astroid.extract_node('''
- def my_func():
- try:
- fake_func()
- except RuntimeError:
- try:
- another_func()
- except NameError:
- raise #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set(["NameError"])
- assert found == expected
-
- def test_no_rethrow_types(self):
- raise_node = astroid.extract_node('''
- def my_func():
- try:
- fake_func()
- except:
+def test_space_indentation():
+ """Test for pylint_plugin.ParamDocChecker"""
+ assert utils.space_indentation('abc') == 0
+ assert utils.space_indentation('') == 0
+ assert utils.space_indentation(' abc') == 2
+ assert utils.space_indentation('\n abc') == 0
+ assert utils.space_indentation(' \n abc') == 3
+
+
+def test_exception_class():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ raise NotImplementedError #@
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set(["NotImplementedError"])
+ assert found == expected
+
+
+def test_exception_instance():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ raise NotImplementedError("Not implemented!") #@
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set(["NotImplementedError"])
+ assert found == expected
+
+
+def test_rethrow():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ try:
+ fake_func()
+ except RuntimeError:
+ raise #@
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set(["RuntimeError"])
+ assert found == expected
+
+
+def test_nested_in_if_rethrow():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ try:
+ fake_func()
+ except RuntimeError:
+ if another_func():
raise #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set()
- assert found == expected
-
- def test_multiple_rethrow_types(self):
- raise_node = astroid.extract_node('''
- def my_func():
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set(["RuntimeError"])
+ assert found == expected
+
+
+def test_nested_in_try():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ try:
+ fake_func()
+ except RuntimeError:
try:
- fake_func()
- except (RuntimeError, ValueError):
+ another_func()
raise #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set(["RuntimeError", "ValueError"])
- assert found == expected
-
- def test_ignores_uninferable_type(self):
- raise_node = astroid.extract_node('''
- import not_a_module
- def my_func():
+ except NameError:
+ pass
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set(["RuntimeError"])
+ assert found == expected
+
+
+def test_nested_in_try_except():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ try:
+ fake_func()
+ except RuntimeError:
try:
- fake_func()
- except not_a_module.Error:
+ another_func()
+ except NameError:
raise #@
- ''')
- found = utils.possible_exc_types(raise_node)
- expected = set()
- assert found == expected
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set(["NameError"])
+ assert found == expected
+
+
+def test_no_rethrow_types():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ try:
+ fake_func()
+ except:
+ raise #@
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set()
+ assert found == expected
+
+
+def test_multiple_rethrow_types():
+ raise_node = astroid.extract_node('''
+ def my_func():
+ try:
+ fake_func()
+ except (RuntimeError, ValueError):
+ raise #@
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set(["RuntimeError", "ValueError"])
+ assert found == expected
+
+
+def test_ignores_uninferable_type():
+ raise_node = astroid.extract_node('''
+ import not_a_module
+ def my_func():
+ try:
+ fake_func()
+ except not_a_module.Error:
+ raise #@
+ ''')
+ found = utils.possible_exc_types(raise_node)
+ expected = set()
+ assert found == expected
+
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_check_mccabe.py b/pylint/test/extensions/test_check_mccabe.py
index 8ea646b4f..a9bf926e9 100644
--- a/pylint/test/extensions/test_check_mccabe.py
+++ b/pylint/test/extensions/test_check_mccabe.py
@@ -8,7 +8,6 @@
"""
import os.path as osp
-import unittest
from pylint import checkers
from pylint.extensions.mccabe import register
@@ -16,7 +15,7 @@ from pylint.lint import PyLinter
from pylint.testutils import MinimalTestReporter
-class TestMcCabeMethodChecker(unittest.TestCase):
+class TestMcCabeMethodChecker(object):
"""Test McCabe Method Checker"""
expected_msgs = [
@@ -37,7 +36,7 @@ class TestMcCabeMethodChecker(unittest.TestCase):
]
@classmethod
- def setUpClass(cls):
+ def setup_class(cls):
cls._linter = PyLinter()
cls._linter.set_reporter(MinimalTestReporter())
checkers.initialize(cls._linter)
@@ -45,7 +44,7 @@ class TestMcCabeMethodChecker(unittest.TestCase):
cls._linter.disable('all')
cls._linter.enable('too-complex')
- def setUp(self):
+ def setup_method(self):
self.fname_mccabe_example = osp.join(
osp.dirname(osp.abspath(__file__)), 'data', 'mccabe.py')
@@ -63,4 +62,6 @@ class TestMcCabeMethodChecker(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_check_raise_docs.py b/pylint/test/extensions/test_check_raise_docs.py
index 29d99ba48..f7d2fb7be 100644
--- a/pylint/test/extensions/test_check_raise_docs.py
+++ b/pylint/test/extensions/test_check_raise_docs.py
@@ -10,15 +10,13 @@
"""
from __future__ import division, print_function, absolute_import
-import unittest
-
import astroid
from pylint.testutils import CheckerTestCase, Message, set_config
from pylint.extensions.docparams import DocstringParameterChecker
-class DocstringCheckerRaiseTest(CheckerTestCase):
+class TestDocstringCheckerRaise(CheckerTestCase):
"""Tests for pylint_plugin.RaiseDocChecker"""
CHECKER_CLASS = DocstringParameterChecker
@@ -519,4 +517,6 @@ class DocstringCheckerRaiseTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_check_return_docs.py b/pylint/test/extensions/test_check_return_docs.py
index 636beb9ff..40cfcd893 100644
--- a/pylint/test/extensions/test_check_return_docs.py
+++ b/pylint/test/extensions/test_check_return_docs.py
@@ -12,15 +12,13 @@
"""
from __future__ import division, print_function, absolute_import
-import unittest
-
import astroid
from pylint.testutils import CheckerTestCase, Message, set_config
from pylint.extensions.docparams import DocstringParameterChecker
-class DocstringCheckerReturnTest(CheckerTestCase):
+class TestDocstringCheckerReturn(CheckerTestCase):
"""Tests for pylint_plugin.RaiseDocChecker"""
CHECKER_CLASS = DocstringParameterChecker
@@ -574,4 +572,6 @@ class DocstringCheckerReturnTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_check_yields_docs.py b/pylint/test/extensions/test_check_yields_docs.py
index f2bf85ef3..f92924a4b 100644
--- a/pylint/test/extensions/test_check_yields_docs.py
+++ b/pylint/test/extensions/test_check_yields_docs.py
@@ -9,15 +9,13 @@
"""
from __future__ import division, print_function, absolute_import
-import unittest
-
import astroid
from pylint.testutils import CheckerTestCase, Message, set_config
from pylint.extensions.docparams import DocstringParameterChecker
-class DocstringCheckerYieldTest(CheckerTestCase):
+class TestDocstringCheckerYield(CheckerTestCase):
"""Tests for pylint_plugin.RaiseDocChecker"""
CHECKER_CLASS = DocstringParameterChecker
@@ -398,4 +396,6 @@ class DocstringCheckerYieldTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_docstyle.py b/pylint/test/extensions/test_docstyle.py
index 94f29e34e..42ce4300f 100644
--- a/pylint/test/extensions/test_docstyle.py
+++ b/pylint/test/extensions/test_docstyle.py
@@ -8,7 +8,6 @@
"""
import os.path as osp
-import unittest
from pylint import checkers
from pylint.extensions.docstyle import DocStringStyleChecker
@@ -16,7 +15,7 @@ from pylint.lint import PyLinter
from pylint.testutils import MinimalTestReporter
-class CheckDocStringStyleTest(unittest.TestCase):
+class TestCheckDocStringStyle(object):
expected_msg = [
'First line empty in function docstring',
@@ -38,7 +37,7 @@ class CheckDocStringStyleTest(unittest.TestCase):
]
@classmethod
- def setUpClass(cls):
+ def setup_class(cls):
cls._linter = PyLinter()
cls._linter.set_reporter(MinimalTestReporter())
checkers.initialize(cls._linter)
@@ -58,4 +57,6 @@ class CheckDocStringStyleTest(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_elseif_used.py b/pylint/test/extensions/test_elseif_used.py
index 3cdf27708..3a043f8fc 100644
--- a/pylint/test/extensions/test_elseif_used.py
+++ b/pylint/test/extensions/test_elseif_used.py
@@ -7,9 +7,7 @@
"""Tests for the pylint checker in :mod:`pylint.extensions.check_elif
"""
-import os
import os.path as osp
-import unittest
from pylint import checkers
from pylint.extensions.check_elif import ElseifUsedChecker
@@ -17,10 +15,10 @@ from pylint.lint import PyLinter
from pylint.testutils import MinimalTestReporter
-class CheckElseIfUsedTC(unittest.TestCase):
+class TestCheckElseIfUsed():
@classmethod
- def setUpClass(cls):
+ def setup_class(cls):
cls._linter = PyLinter()
cls._linter.set_reporter(MinimalTestReporter())
checkers.initialize(cls._linter)
@@ -34,11 +32,12 @@ class CheckElseIfUsedTC(unittest.TestCase):
assert len(msgs) == 2
for msg in msgs:
assert msg.symbol == 'else-if-used'
- assert msg.msg == \
- 'Consider using "elif" instead of "else if"'
+ assert msg.msg == 'Consider using "elif" instead of "else if"'
assert msgs[0].line == 9
assert msgs[1].line == 21
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/extensions/test_redefined.py b/pylint/test/extensions/test_redefined.py
index 3e7349567..db74ff1d0 100644
--- a/pylint/test/extensions/test_redefined.py
+++ b/pylint/test/extensions/test_redefined.py
@@ -6,9 +6,7 @@
"""Tests for the pylint checker in :mod:`pylint.extensions.check_elif
"""
-import os
import os.path as osp
-import unittest
from pylint import checkers
from pylint.extensions.redefined_variable_type import MultipleTypesChecker
@@ -16,7 +14,7 @@ from pylint.lint import PyLinter, fix_import_path
from pylint.testutils import MinimalTestReporter
-class CheckElseIfUsedTC(unittest.TestCase):
+class TestCheckElseIfUsed(object):
expected = [
'Redefinition of self.var1 type from int to float',
@@ -30,9 +28,8 @@ class CheckElseIfUsedTC(unittest.TestCase):
'Redefinition of var4 type from float to str',
]
-
@classmethod
- def setUpClass(cls):
+ def setup_class(cls):
cls._linter = PyLinter()
cls._linter.set_reporter(MinimalTestReporter())
checkers.initialize(cls._linter)
@@ -52,4 +49,6 @@ class CheckElseIfUsedTC(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/test_import_graph.py b/pylint/test/test_import_graph.py
index 85bf9ee29..15a77859c 100644
--- a/pylint/test/test_import_graph.py
+++ b/pylint/test/test_import_graph.py
@@ -4,31 +4,29 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
-import sys
import os
from os.path import exists
-import unittest
-import six
from pylint.checkers import initialize, imports
from pylint.lint import PyLinter
import pylint.testutils as testutils
-class DependenciesGraphTC(unittest.TestCase):
+
+class TestDependenciesGraph(object):
"""test the imports graph function"""
dest = 'dependencies_graph.dot'
- def tearDown(self):
+
+ def teardown_method(self):
os.remove(self.dest)
def test_dependencies_graph(self):
imports._dependencies_graph(self.dest, {'labas': ['hoho', 'yep'],
'hoho': ['yep']})
with open(self.dest) as stream:
- assert stream.read().strip() == \
- '''
+ assert stream.read().strip() == '''
digraph "dependencies_graph" {
rankdir=LR
charset="utf-8"
@@ -42,8 +40,9 @@ URL="." node[shape="box"]
}
'''.strip()
-class ImportCheckerTC(unittest.TestCase):
- def setUp(self):
+
+class TestImportChecker(object):
+ def setup_method(self):
self.linter = l = PyLinter(reporter=testutils.TestReporter())
initialize(l)
@@ -72,4 +71,6 @@ class ImportCheckerTC(unittest.TestCase):
pass
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/test_regr.py b/pylint/test/test_regr.py
index 71256574a..9861eb0df 100644
--- a/pylint/test/test_regr.py
+++ b/pylint/test/test_regr.py
@@ -11,7 +11,8 @@ to be incorporated in the automatic functional test framework
import sys
import os
from os.path import abspath, dirname, join
-import unittest
+
+import pytest
import astroid
import pylint.testutils as testutils
@@ -34,8 +35,8 @@ try:
except AttributeError:
PYPY_VERSION_INFO = None
-class NonRegrTC(unittest.TestCase):
- def setUp(self):
+class TestNonRegr(object):
+ def setup_method(self):
"""call reporter.finalize() to cleanup
pending messages if a test finished badly
"""
@@ -55,8 +56,7 @@ class NonRegrTC(unittest.TestCase):
filename = 'package.__init__'
linter.check(filename)
checked = list(linter.stats['by_module'].keys())
- assert checked == ['package.__init__'], \
- '%s: %s' % (filename, checked)
+ assert checked == ['package.__init__'], '%s: %s' % (filename, checked)
cwd = os.getcwd()
os.chdir(join(REGR_DATA, 'package'))
@@ -120,10 +120,10 @@ class NonRegrTC(unittest.TestCase):
got = linter.reporter.finalize().strip()
assert expected in got
- @unittest.skipIf(PYPY_VERSION_INFO and PYPY_VERSION_INFO < (4, 0),
- "On older PyPy versions, sys.executable was set to a value "
- "that is not supported by the implementation of this function. "
- "( https://bitbucket.org/pypy/pypy/commits/19e305e27e67 )")
+ @pytest.mark.skipif(PYPY_VERSION_INFO and PYPY_VERSION_INFO < (4, 0),
+ reason="On older PyPy versions, sys.executable was set to a value "
+ "that is not supported by the implementation of this function. "
+ "( https://bitbucket.org/pypy/pypy/commits/19e305e27e67 )")
def test_epylint_does_not_block_on_huge_files(self):
path = join(REGR_DATA, 'huge.py')
out, err = epylint.py_run(path, return_std=True)
@@ -138,8 +138,7 @@ class NonRegrTC(unittest.TestCase):
expect = ['OptionsManagerMixIn', 'object', 'MessagesHandlerMixIn',
'ReportsHandlerMixIn', 'BaseTokenChecker', 'BaseChecker',
'OptionsProviderMixIn']
- assert [c.name for c in pylinter.ancestors()] == \
- expect
+ assert [c.name for c in pylinter.ancestors()] == expect
assert list(astroid.Instance(pylinter).getattr('config'))
inferred = list(astroid.Instance(pylinter).igetattr('config'))
assert len(inferred) == 1
@@ -148,4 +147,4 @@ class NonRegrTC(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/test_self.py b/pylint/test/test_self.py
index a26bcec68..f62eea138 100644
--- a/pylint/test/test_self.py
+++ b/pylint/test/test_self.py
@@ -13,12 +13,10 @@ import os
from os.path import join, dirname, abspath
import tempfile
import textwrap
-import unittest
import six
from pylint.lint import Run
-from pylint import __pkginfo__
from pylint.reporters import BaseReporter
from pylint.reporters.text import *
from pylint.reporters.json import JSONReporter
@@ -69,7 +67,7 @@ class MultiReporter(BaseReporter):
rep.linter = value
-class RunTC(unittest.TestCase):
+class TestRunTC(object):
def _runtest(self, args, reporter=None, out=None, code=28):
if out is None:
@@ -200,7 +198,7 @@ class RunTC(unittest.TestCase):
'--py3k', '-j 2'],
code=rc_code)
- @unittest.skipIf(sys.version_info[0] > 2, "Requires the --py3k flag.")
+ @pytest.mark.skipif(sys.version_info[0] > 2, reason="Requires the --py3k flag.")
def test_py3k_commutative_with_errors_only(self):
# Test what gets emitted with -E only
@@ -384,4 +382,4 @@ class RunTC(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_base.py b/pylint/test/unittest_checker_base.py
index 352e2a677..24fa2e49f 100644
--- a/pylint/test/unittest_checker_base.py
+++ b/pylint/test/unittest_checker_base.py
@@ -10,14 +10,13 @@
"""Unittest for the base checker."""
import re
-import unittest
import astroid
from pylint.checkers import base
from pylint.testutils import CheckerTestCase, Message, set_config
-class DocstringTest(CheckerTestCase):
+class TestDocstring(CheckerTestCase):
CHECKER_CLASS = base.DocStringChecker
def test_missing_docstring_module(self):
@@ -70,7 +69,7 @@ class DocstringTest(CheckerTestCase):
self.checker.visit_classdef(klass)
-class NameCheckerTest(CheckerTestCase):
+class TestNameChecker(CheckerTestCase):
CHECKER_CLASS = base.NameChecker
CONFIG = {
'bad_names': set(),
@@ -180,7 +179,7 @@ class NameCheckerTest(CheckerTestCase):
self.checker.visit_assignname(assign.targets[0])
-class MultiNamingStyleTest(CheckerTestCase):
+class TestMultiNamingStyle(CheckerTestCase):
CHECKER_CLASS = base.NameChecker
MULTI_STYLE_RE = re.compile('(?:(?P<UP>[A-Z]+)|(?P<down>[a-z]+))$')
@@ -262,7 +261,7 @@ class MultiNamingStyleTest(CheckerTestCase):
self.checker.visit_functiondef(func)
self.checker.leave_module(func.root)
-class ComparisonTest(CheckerTestCase):
+class TestComparison(CheckerTestCase):
CHECKER_CLASS = base.ComparisonChecker
def test_comparison(self):
@@ -319,4 +318,6 @@ class ComparisonTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_classes.py b/pylint/test/unittest_checker_classes.py
index c96d9ed97..cc3c9b7e4 100644
--- a/pylint/test/unittest_checker_classes.py
+++ b/pylint/test/unittest_checker_classes.py
@@ -4,14 +4,15 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Unit tests for the variables checker."""
-import unittest
import sys
+import pytest
+
import astroid
from pylint.checkers import classes
from pylint.testutils import CheckerTestCase, Message, set_config
-class VariablesCheckerTC(CheckerTestCase):
+class TestVariablesChecker(CheckerTestCase):
CHECKER_CLASS = classes.ClassChecker
@@ -52,8 +53,8 @@ class VariablesCheckerTC(CheckerTestCase):
args='_teta')):
self.walk(node.root())
- @unittest.skipUnless(sys.version_info[0] == 3,
- "The test works on Python 3.")
+ @pytest.mark.skipif(sys.version_info[0] != 3,
+ reason="The test works on Python 3.")
def test_regression_non_parent_init_called_tracemalloc(self):
# This used to raise a non-parent-init-called on Pylint 1.3
# See issue https://bitbucket.org/logilab/pylint/issue/308/
@@ -85,4 +86,4 @@ class VariablesCheckerTC(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_exceptions.py b/pylint/test/unittest_checker_exceptions.py
index 1fca324ad..0896f0ca5 100644
--- a/pylint/test/unittest_checker_exceptions.py
+++ b/pylint/test/unittest_checker_exceptions.py
@@ -9,7 +9,8 @@
"""Tests for pylint.checkers.exceptions."""
import sys
-import unittest
+
+import pytest
import astroid
@@ -17,7 +18,7 @@ from pylint.checkers import exceptions
from pylint.testutils import CheckerTestCase, Message
-class ExceptionsCheckerTest(CheckerTestCase):
+class TestExceptionsChecker(CheckerTestCase):
"""Tests for pylint.checkers.exceptions."""
CHECKER_CLASS = exceptions.ExceptionsChecker
@@ -27,16 +28,16 @@ class ExceptionsCheckerTest(CheckerTestCase):
# and `raise (Error, ...)` will be converted to
# `raise Error(...)`, so it beats the purpose of the test.
- @unittest.skipUnless(sys.version_info[0] == 3,
- "The test should emit an error on Python 3.")
+ @pytest.mark.skipif(sys.version_info[0] != 3,
+ reason="The test should emit an error on Python 3.")
def test_raising_bad_type_python3(self):
node = astroid.extract_node('raise (ZeroDivisionError, None) #@')
message = Message('raising-bad-type', node=node, args='tuple')
with self.assertAddsMessages(message):
self.checker.visit_raise(node)
- @unittest.skipUnless(sys.version_info[0] == 2,
- "The test is valid only on Python 2.")
+ @pytest.mark.skipif(sys.version_info[0] != 2,
+ reason="The test is valid only on Python 2.")
def test_raising_bad_type_python2(self):
nodes = astroid.extract_node('''
raise (ZeroDivisionError, None) #@
@@ -60,4 +61,4 @@ class ExceptionsCheckerTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_format.py b/pylint/test/unittest_checker_format.py
index 483356fc9..51636f647 100644
--- a/pylint/test/unittest_checker_format.py
+++ b/pylint/test/unittest_checker_format.py
@@ -19,7 +19,7 @@ from pylint.testutils import (
)
-class MultiStatementLineTest(CheckerTestCase):
+class TestMultiStatementLine(CheckerTestCase):
CHECKER_CLASS = FormatChecker
def testSingleLineIfStmts(self):
@@ -56,7 +56,7 @@ class MultiStatementLineTest(CheckerTestCase):
-class SuperfluousParenthesesTest(CheckerTestCase):
+class TestSuperfluousParentheses(CheckerTestCase):
CHECKER_CLASS = FormatChecker
def testCheckKeywordParensHandlesValidCases(self):
@@ -113,7 +113,7 @@ print('Hello world!')
self.checker.process_tokens(tokenize_str(code))
-class CheckSpaceTest(CheckerTestCase):
+class TestCheckSpace(CheckerTestCase):
CHECKER_CLASS = FormatChecker
def testParenthesesGood(self):
@@ -249,5 +249,6 @@ class CheckSpaceTest(CheckerTestCase):
if __name__ == '__main__':
- import unittest
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_imports.py b/pylint/test/unittest_checker_imports.py
index c91bfbc53..18a312085 100644
--- a/pylint/test/unittest_checker_imports.py
+++ b/pylint/test/unittest_checker_imports.py
@@ -8,14 +8,13 @@
"""Unit tests for the imports checker."""
import os
-import unittest
import astroid
from pylint.checkers import imports
from pylint.testutils import CheckerTestCase, Message, set_config
-class ImportsCheckerTC(CheckerTestCase):
+class TestImportsChecker(CheckerTestCase):
CHECKER_CLASS = imports.ImportsChecker
@@ -91,7 +90,7 @@ class ImportsCheckerTC(CheckerTestCase):
msg = Message(msg_id='relative-beyond-top-level',
node=import_from)
with self.assertAddsMessages(msg):
- self.checker.visit_importfrom(import_from)
+ self.checker.visit_importfrom(import_from)
with self.assertNoMessages():
self.checker.visit_importfrom(module.body[1])
with self.assertNoMessages():
@@ -99,4 +98,6 @@ class ImportsCheckerTC(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_logging.py b/pylint/test/unittest_checker_logging.py
index d3686ae48..8e83e123d 100644
--- a/pylint/test/unittest_checker_logging.py
+++ b/pylint/test/unittest_checker_logging.py
@@ -5,17 +5,15 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Unittest for the logging checker."""
-import unittest
-
import astroid
from pylint.checkers import logging
from pylint.testutils import CheckerTestCase, Message, set_config
-class LoggingModuleDetectionTest(CheckerTestCase):
+class TestLoggingModuleDetection(CheckerTestCase):
CHECKER_CLASS = logging.LoggingChecker
-
+
def test_detects_standard_logging_module(self):
stmts = astroid.extract_node("""
import logging #@
@@ -49,4 +47,6 @@ class LoggingModuleDetectionTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_misc.py b/pylint/test/unittest_checker_misc.py
index 4be093fe8..ed78041c4 100644
--- a/pylint/test/unittest_checker_misc.py
+++ b/pylint/test/unittest_checker_misc.py
@@ -7,8 +7,6 @@
"""Tests for the misc checker."""
-import unittest
-
from pylint.checkers import misc
from pylint.testutils import (
CheckerTestCase, Message,
@@ -16,7 +14,7 @@ from pylint.testutils import (
)
-class FixmeTest(CheckerTestCase):
+class TestFixme(CheckerTestCase):
CHECKER_CLASS = misc.EncodingChecker
def test_fixme_with_message(self):
@@ -87,4 +85,6 @@ class FixmeTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_python3.py b/pylint/test/unittest_checker_python3.py
index b8ef27106..1834c6394 100644
--- a/pylint/test/unittest_checker_python3.py
+++ b/pylint/test/unittest_checker_python3.py
@@ -8,9 +8,10 @@
from __future__ import absolute_import
import sys
-import unittest
import textwrap
+import pytest
+
import astroid
from pylint import testutils
@@ -18,13 +19,12 @@ from pylint.checkers import python3 as checker
from pylint.interfaces import INFERENCE_FAILURE, INFERENCE
-def python2_only(test):
- """Decorator for any tests that will fail under Python 3."""
- return unittest.skipIf(sys.version_info[0] > 2, 'Python 2 only')(test)
+# Decorator for any tests that will fail under Python 3
+python2_only = pytest.mark.skipif(sys.version_info[0] > 2, reason='Python 2 only')
# TODO(cpopa): Port these to the functional test framework instead.
-class Python3CheckerTest(testutils.CheckerTestCase):
+class TestPython3Checker(testutils.CheckerTestCase):
CHECKER_CLASS = checker.Python3Checker
def check_bad_builtin(self, builtin_name):
@@ -284,9 +284,9 @@ class Python3CheckerTest(testutils.CheckerTestCase):
def test_absolute_import(self):
module_import = astroid.parse(
- 'from __future__ import absolute_import; import os')
+ 'from __future__ import absolute_import; import os')
module_from = astroid.parse(
- 'from __future__ import absolute_import; from os import path')
+ 'from __future__ import absolute_import; from os import path')
with self.assertNoMessages():
for module in (module_import, module_from):
self.walk(module)
@@ -716,7 +716,7 @@ class Python3CheckerTest(testutils.CheckerTestCase):
@python2_only
-class Python3TokenCheckerTest(testutils.CheckerTestCase):
+class TestPython3TokenChecker(testutils.CheckerTestCase):
CHECKER_CLASS = checker.Python3TokenChecker
@@ -745,4 +745,4 @@ class Python3TokenCheckerTest(testutils.CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_similar.py b/pylint/test/unittest_checker_similar.py
index 71a61a107..13d722f29 100644
--- a/pylint/test/unittest_checker_similar.py
+++ b/pylint/test/unittest_checker_similar.py
@@ -6,30 +6,27 @@
import sys
from os.path import join, dirname, abspath
-import unittest
import six
+import pytest
from pylint.checkers import similar
SIMILAR1 = join(dirname(abspath(__file__)), 'input', 'similar1')
SIMILAR2 = join(dirname(abspath(__file__)), 'input', 'similar2')
-class SimilarTC(unittest.TestCase):
- """test the similar command line utility"""
-
- def test_ignore_comments(self):
- sys.stdout = six.StringIO()
- try:
- similar.Run(['--ignore-comments', SIMILAR1, SIMILAR2])
- except SystemExit as ex:
- assert ex.code == 0
- output = sys.stdout.getvalue()
- else:
- self.fail('not system exit')
- finally:
- sys.stdout = sys.__stdout__
- assert output.strip() == ("""
+def test_ignore_comments():
+ sys.stdout = six.StringIO()
+ try:
+ similar.Run(['--ignore-comments', SIMILAR1, SIMILAR2])
+ except SystemExit as ex:
+ assert ex.code == 0
+ output = sys.stdout.getvalue()
+ else:
+ pytest.fail('not system exit')
+ finally:
+ sys.stdout = sys.__stdout__
+ assert output.strip() == ("""
10 similar lines in 2 files
==%s:0
==%s:0
@@ -47,18 +44,18 @@ TOTAL lines=44 duplicates=10 percent=22.73
""" % (SIMILAR1, SIMILAR2)).strip()
- def test_ignore_docsrings(self):
- sys.stdout = six.StringIO()
- try:
- similar.Run(['--ignore-docstrings', SIMILAR1, SIMILAR2])
- except SystemExit as ex:
- assert ex.code == 0
- output = sys.stdout.getvalue()
- else:
- self.fail('not system exit')
- finally:
- sys.stdout = sys.__stdout__
- assert output.strip() == ("""
+def test_ignore_docsrings():
+ sys.stdout = six.StringIO()
+ try:
+ similar.Run(['--ignore-docstrings', SIMILAR1, SIMILAR2])
+ except SystemExit as ex:
+ assert ex.code == 0
+ output = sys.stdout.getvalue()
+ else:
+ pytest.fail('not system exit')
+ finally:
+ sys.stdout = sys.__stdout__
+ assert output.strip() == ("""
8 similar lines in 2 files
==%s:6
==%s:6
@@ -83,34 +80,34 @@ TOTAL lines=44 duplicates=13 percent=29.55
""" % ((SIMILAR1, SIMILAR2) * 2)).strip()
- def test_ignore_imports(self):
- sys.stdout = six.StringIO()
- try:
- similar.Run(['--ignore-imports', SIMILAR1, SIMILAR2])
- except SystemExit as ex:
- assert ex.code == 0
- output = sys.stdout.getvalue()
- else:
- self.fail('not system exit')
- finally:
- sys.stdout = sys.__stdout__
- assert output.strip() == """
+def test_ignore_imports():
+ sys.stdout = six.StringIO()
+ try:
+ similar.Run(['--ignore-imports', SIMILAR1, SIMILAR2])
+ except SystemExit as ex:
+ assert ex.code == 0
+ output = sys.stdout.getvalue()
+ else:
+ pytest.fail('not system exit')
+ finally:
+ sys.stdout = sys.__stdout__
+ assert output.strip() == """
TOTAL lines=44 duplicates=0 percent=0.00
""".strip()
- def test_ignore_nothing(self):
- sys.stdout = six.StringIO()
- try:
- similar.Run([SIMILAR1, SIMILAR2])
- except SystemExit as ex:
- assert ex.code == 0
- output = sys.stdout.getvalue()
- else:
- self.fail('not system exit')
- finally:
- sys.stdout = sys.__stdout__
- assert output.strip() == ("""
+def test_ignore_nothing():
+ sys.stdout = six.StringIO()
+ try:
+ similar.Run([SIMILAR1, SIMILAR2])
+ except SystemExit as ex:
+ assert ex.code == 0
+ output = sys.stdout.getvalue()
+ else:
+ pytest.fail('not system exit')
+ finally:
+ sys.stdout = sys.__stdout__
+ assert output.strip() == ("""
5 similar lines in 2 files
==%s:0
==%s:0
@@ -122,27 +119,27 @@ TOTAL lines=44 duplicates=0 percent=0.00
TOTAL lines=44 duplicates=5 percent=11.36
""" % (SIMILAR1, SIMILAR2)).strip()
- def test_help(self):
- sys.stdout = six.StringIO()
- try:
- similar.Run(['--help'])
- except SystemExit as ex:
- assert ex.code == 0
- else:
- self.fail('not system exit')
- finally:
- sys.stdout = sys.__stdout__
-
- def test_no_args(self):
- sys.stdout = six.StringIO()
- try:
- similar.Run([])
- except SystemExit as ex:
- assert ex.code == 1
- else:
- self.fail('not system exit')
- finally:
- sys.stdout = sys.__stdout__
+def test_help():
+ sys.stdout = six.StringIO()
+ try:
+ similar.Run(['--help'])
+ except SystemExit as ex:
+ assert ex.code == 0
+ else:
+ pytest.fail('not system exit')
+ finally:
+ sys.stdout = sys.__stdout__
+
+def test_no_args():
+ sys.stdout = six.StringIO()
+ try:
+ similar.Run([])
+ except SystemExit as ex:
+ assert ex.code == 1
+ else:
+ pytest.fail('not system exit')
+ finally:
+ sys.stdout = sys.__stdout__
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_spelling.py b/pylint/test/unittest_checker_spelling.py
index e0abb20cd..888da1c44 100644
--- a/pylint/test/unittest_checker_spelling.py
+++ b/pylint/test/unittest_checker_spelling.py
@@ -5,7 +5,7 @@
"""Unittest for the spelling checker."""
-import unittest
+import pytest
import astroid
@@ -29,12 +29,12 @@ if enchant is not None:
pass
-class SpellingCheckerTest(CheckerTestCase):
+class TestSpellingChecker(CheckerTestCase):
CHECKER_CLASS = spelling.SpellingChecker
- @unittest.skipIf(spell_dict is None,
- "missing python-enchant package or missing "
- "spelling dictionaries")
+ @pytest.mark.skipif(spell_dict is None,
+ reason="missing python-enchant package or missing "
+ "spelling dictionaries")
@set_config(spelling_dict=spell_dict)
def test_check_bad_coment(self):
with self.assertAddsMessages(
@@ -44,9 +44,9 @@ class SpellingCheckerTest(CheckerTestCase):
"comet' or 'comment' or 'moment' or 'foment"))):
self.checker.process_tokens(tokenize_str("# bad coment"))
- @unittest.skipIf(spell_dict is None,
- "missing python-enchant package or missing "
- "spelling dictionaries")
+ @pytest.mark.skipif(spell_dict is None,
+ reason="missing python-enchant package or missing "
+ "spelling dictionaries")
@set_config(spelling_dict=spell_dict)
def test_check_bad_docstring(self):
stmt = astroid.extract_node(
@@ -67,9 +67,9 @@ class SpellingCheckerTest(CheckerTestCase):
"comet' or 'comment' or 'moment' or 'foment"))):
self.checker.visit_classdef(stmt)
- @unittest.skipIf(spell_dict is None,
- "missing python-enchant package or missing "
- "spelling dictionaries")
+ @pytest.mark.skipif(spell_dict is None,
+ reason="missing python-enchant package or missing "
+ "spelling dictionaries")
@set_config(spelling_dict=spell_dict)
def test_invalid_docstring_characters(self):
stmt = astroid.extract_node(
@@ -81,4 +81,5 @@ class SpellingCheckerTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_stdlib.py b/pylint/test/unittest_checker_stdlib.py
index ad7e7da95..10a8fabb4 100644
--- a/pylint/test/unittest_checker_stdlib.py
+++ b/pylint/test/unittest_checker_stdlib.py
@@ -5,7 +5,6 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
import contextlib
-import unittest
import astroid
@@ -22,7 +21,7 @@ def _add_transform(manager, node, transform, predicate=None):
manager.unregister_transform(node, transform, predicate)
-class StdlibCheckerTest(CheckerTestCase):
+class TestStdlibChecker(CheckerTestCase):
CHECKER_CLASS = stdlib.StdlibChecker
def test_deprecated_no_qname_on_unexpected_nodes(self):
@@ -51,4 +50,6 @@ class StdlibCheckerTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_strings.py b/pylint/test/unittest_checker_strings.py
index c055ecd5e..fd0434538 100644
--- a/pylint/test/unittest_checker_strings.py
+++ b/pylint/test/unittest_checker_strings.py
@@ -4,7 +4,8 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
import sys
-import unittest
+
+import pytest
import astroid
@@ -12,13 +13,13 @@ from pylint.checkers import strings
from pylint.testutils import CheckerTestCase
-class StringCheckerTest(CheckerTestCase):
+class TestStringChecker(CheckerTestCase):
CHECKER_CLASS = strings.StringFormatChecker
- @unittest.skipUnless(sys.version_info > (3, 0),
- "Tests that the string formatting checker "
- "doesn't fail when encountering a bytes "
- "string with a .format call")
+ @pytest.mark.skipif(sys.version_info <= (3, 0), reason=""
+ "Tests that the string formatting checker "
+ "doesn't fail when encountering a bytes "
+ "string with a .format call")
def test_format_bytes(self):
code = "b'test'.format(1, 2)"
node = astroid.extract_node(code)
@@ -27,4 +28,4 @@ class StringCheckerTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_typecheck.py b/pylint/test/unittest_checker_typecheck.py
index 45f54c6df..fcd1cf932 100644
--- a/pylint/test/unittest_checker_typecheck.py
+++ b/pylint/test/unittest_checker_typecheck.py
@@ -6,16 +6,17 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Unittest for the type checker."""
-import unittest
import sys
+import pytest
+
import astroid
from pylint.checkers import typecheck
from pylint.testutils import CheckerTestCase, Message, set_config
-class TypeCheckerTest(CheckerTestCase):
+class TestTypeChecker(CheckerTestCase):
"Tests for pylint.checkers.typecheck"
CHECKER_CLASS = typecheck.TypeChecker
@@ -142,7 +143,7 @@ class TypeCheckerTest(CheckerTestCase):
with self.assertAddsMessages(message):
self.checker.visit_classdef(classdef)
- @unittest.skipUnless(sys.version_info[0] >= 3, 'Needs Python 3.')
+ @pytest.mark.skipif(sys.version_info[0] < 3, reason='Needs Python 3.')
def test_invalid_metaclass_function_metaclasses(self):
module = astroid.parse('''
def invalid_metaclass_1(name, bases, attrs):
@@ -163,4 +164,4 @@ class TypeCheckerTest(CheckerTestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checker_variables.py b/pylint/test/unittest_checker_variables.py
index 762a75aeb..cf1048b71 100644
--- a/pylint/test/unittest_checker_variables.py
+++ b/pylint/test/unittest_checker_variables.py
@@ -6,14 +6,13 @@
"""Unit tests for the variables checker."""
import sys
import os
-import unittest
import astroid
from pylint.checkers import variables
from pylint.testutils import CheckerTestCase, linter, set_config, Message
-class VariablesCheckerTC(CheckerTestCase):
+class TestVariablesChecker(CheckerTestCase):
CHECKER_CLASS = variables.VariablesChecker
@@ -50,15 +49,56 @@ class VariablesCheckerTC(CheckerTestCase):
self.checker.visit_module(root)
self.checker.leave_module(root)
+ def test_redefined_builtin_ignored(self):
+ node = astroid.parse('''
+ from future.builtins import open
+ ''')
+ with self.assertNoMessages():
+ self.checker.visit_module(node)
+
+ @set_config(redefining_builtins_modules=('os',))
+ def test_redefined_builtin_custom_modules(self):
+ node = astroid.parse('''
+ from os import open
+ ''')
+ with self.assertNoMessages():
+ self.checker.visit_module(node)
+
+ @set_config(redefining_builtins_modules=('os',))
+ def test_redefined_builtin_modname_not_ignored(self):
+ node = astroid.parse('''
+ from future.builtins import open
+ ''')
+ with self.assertAddsMessages(
+ Message('redefined-builtin', node=node.body[0], args='open')):
+ self.checker.visit_module(node)
+
+ @set_config(redefining_builtins_modules=('os',))
+ def test_redefined_builtin_in_function(self):
+ node = astroid.extract_node('''
+ def test():
+ from os import open
+ ''')
+ with self.assertNoMessages():
+ self.checker.visit_module(node.root())
+ self.checker.visit_functiondef(node)
+
+
+class TestVariablesCheckerWithTearDown(CheckerTestCase):
+
+ CHECKER_CLASS = variables.VariablesChecker
+
+ def setup_method(self):
+ super(TestVariablesCheckerWithTearDown, self).setup_method()
+ self._to_consume_backup = self.checker._to_consume
+ self.checker._to_consume = []
+
+ def teardown_method(self, method):
+ self.checker._to_consume = self._to_consume_backup
+
@set_config(callbacks=('callback_', '_callback'))
def test_custom_callback_string(self):
""" Test the --calbacks option works. """
- def cleanup():
- self.checker._to_consume = _to_consume
- _to_consume = self.checker._to_consume
- self.checker._to_consume = []
- self.addCleanup(cleanup)
-
node = astroid.extract_node("""
def callback_one(abc):
''' should not emit unused-argument. '''
@@ -93,42 +133,8 @@ class VariablesCheckerTC(CheckerTestCase):
self.checker.visit_functiondef(node)
self.checker.leave_functiondef(node)
- def test_redefined_builtin_ignored(self):
- node = astroid.parse('''
- from future.builtins import open
- ''')
- with self.assertNoMessages():
- self.checker.visit_module(node)
-
- @set_config(redefining_builtins_modules=('os',))
- def test_redefined_builtin_custom_modules(self):
- node = astroid.parse('''
- from os import open
- ''')
- with self.assertNoMessages():
- self.checker.visit_module(node)
-
- @set_config(redefining_builtins_modules=('os',))
- def test_redefined_builtin_modname_not_ignored(self):
- node = astroid.parse('''
- from future.builtins import open
- ''')
- with self.assertAddsMessages(
- Message('redefined-builtin', node=node.body[0], args='open')):
- self.checker.visit_module(node)
-
- @set_config(redefining_builtins_modules=('os',))
- def test_redefined_builtin_in_function(self):
- node = astroid.extract_node('''
- def test():
- from os import open
- ''')
- with self.assertNoMessages():
- self.checker.visit_module(node.root())
- self.checker.visit_functiondef(node)
-
-class MissingSubmoduleTest(CheckerTestCase):
+class TestMissingSubmodule(CheckerTestCase):
CHECKER_CLASS = variables.VariablesChecker
def test_package_all(self):
@@ -138,10 +144,10 @@ class MissingSubmoduleTest(CheckerTestCase):
try:
linter.check(os.path.join(regr_data, 'package_all'))
got = linter.reporter.finalize().strip()
- assert got == "E: 3: Undefined variable name " \
- "'missing' in __all__"
+ assert got == "E: 3: Undefined variable name 'missing' in __all__"
finally:
sys.path.pop(0)
if __name__ == '__main__':
- unittest.main()
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_checkers_utils.py b/pylint/test/unittest_checkers_utils.py
index 95c16e745..c95112330 100644
--- a/pylint/test/unittest_checkers_utils.py
+++ b/pylint/test/unittest_checkers_utils.py
@@ -6,89 +6,84 @@
"""Tests for the pylint.checkers.utils module."""
-import unittest
-import warnings
-
import astroid
from pylint.checkers import utils
-from pylint import __pkginfo__
import pytest
-class UtilsTC(unittest.TestCase):
-
- def test_is_builtin(self):
- assert utils.is_builtin('min') == True
- assert utils.is_builtin('__builtins__') == True
- assert utils.is_builtin('__path__') == False
- assert utils.is_builtin('__file__') == False
- assert utils.is_builtin('whatever') == False
- assert utils.is_builtin('mybuiltin') == False
+def test_is_builtin():
+ assert utils.is_builtin('min') is True
+ assert utils.is_builtin('__builtins__') is True
+ assert utils.is_builtin('__path__') is False
+ assert utils.is_builtin('__file__') is False
+ assert utils.is_builtin('whatever') is False
+ assert utils.is_builtin('mybuiltin') is False
- def testGetArgumentFromCall(self):
- node = astroid.extract_node('foo(bar=3)')
- assert utils.get_argument_from_call(node, keyword='bar') is not None
- with pytest.raises(utils.NoSuchArgumentError):
- node = astroid.extract_node('foo(3)')
- utils.get_argument_from_call(node, keyword='bar')
- with pytest.raises(utils.NoSuchArgumentError):
- node = astroid.extract_node('foo(one=a, two=b, three=c)')
- utils.get_argument_from_call(node, position=1)
- node = astroid.extract_node('foo(a, b, c)')
- assert utils.get_argument_from_call(node, position=1) is not None
- node = astroid.extract_node('foo(a, not_this_one=1, this_one=2)')
- arg = utils.get_argument_from_call(node, position=2, keyword='this_one')
- assert 2 == arg.value
- node = astroid.extract_node('foo(a)')
- with pytest.raises(utils.NoSuchArgumentError):
- utils.get_argument_from_call(node, position=1)
- with pytest.raises(ValueError):
- utils.get_argument_from_call(node, None, None)
+def testGetArgumentFromCall():
+ node = astroid.extract_node('foo(bar=3)')
+ assert utils.get_argument_from_call(node, keyword='bar') is not None
+ with pytest.raises(utils.NoSuchArgumentError):
+ node = astroid.extract_node('foo(3)')
+ utils.get_argument_from_call(node, keyword='bar')
+ with pytest.raises(utils.NoSuchArgumentError):
+ node = astroid.extract_node('foo(one=a, two=b, three=c)')
+ utils.get_argument_from_call(node, position=1)
+ node = astroid.extract_node('foo(a, b, c)')
+ assert utils.get_argument_from_call(node, position=1) is not None
+ node = astroid.extract_node('foo(a, not_this_one=1, this_one=2)')
+ arg = utils.get_argument_from_call(node, position=2, keyword='this_one')
+ assert 2 == arg.value
+ node = astroid.extract_node('foo(a)')
+ with pytest.raises(utils.NoSuchArgumentError):
+ utils.get_argument_from_call(node, position=1)
+ with pytest.raises(ValueError):
+ utils.get_argument_from_call(node, None, None)
- name = utils.get_argument_from_call(node, position=0)
- assert name.name == 'a'
+ name = utils.get_argument_from_call(node, position=0)
+ assert name.name == 'a'
- def test_error_of_type(self):
- nodes = astroid.extract_node("""
- try: pass
- except AttributeError: #@
- pass
- try: pass
- except Exception: #@
- pass
- except: #@
- pass
- """)
- assert utils.error_of_type(nodes[0], AttributeError)
- assert utils.error_of_type(nodes[0], (AttributeError, ))
- assert not utils.error_of_type(nodes[0], Exception)
- assert utils.error_of_type(nodes[1], Exception)
- assert not utils.error_of_type(nodes[2], ImportError)
+def test_error_of_type():
+ nodes = astroid.extract_node("""
+ try: pass
+ except AttributeError: #@
+ pass
+ try: pass
+ except Exception: #@
+ pass
+ except: #@
+ pass
+ """)
+ assert utils.error_of_type(nodes[0], AttributeError)
+ assert utils.error_of_type(nodes[0], (AttributeError, ))
+ assert not utils.error_of_type(nodes[0], Exception)
+ assert utils.error_of_type(nodes[1], Exception)
+ assert not utils.error_of_type(nodes[2], ImportError)
- def test_node_ignores_exception(self):
- nodes = astroid.extract_node("""
- try:
- 1/0 #@
- except ZeroDivisionError:
- pass
- try:
- 1/0 #@
- except Exception:
- pass
- try:
- 2/0 #@
- except:
- pass
- try:
- 1/0 #@
- except ValueError:
- pass
- """)
- assert utils.node_ignores_exception(nodes[0], ZeroDivisionError)
- assert not utils.node_ignores_exception(nodes[1], ZeroDivisionError)
- assert not utils.node_ignores_exception(nodes[2], ZeroDivisionError)
- assert not utils.node_ignores_exception(nodes[3], ZeroDivisionError)
+def test_node_ignores_exception():
+ nodes = astroid.extract_node("""
+ try:
+ 1/0 #@
+ except ZeroDivisionError:
+ pass
+ try:
+ 1/0 #@
+ except Exception:
+ pass
+ try:
+ 2/0 #@
+ except:
+ pass
+ try:
+ 1/0 #@
+ except ValueError:
+ pass
+ """)
+ assert utils.node_ignores_exception(nodes[0], ZeroDivisionError)
+ assert not utils.node_ignores_exception(nodes[1], ZeroDivisionError)
+ assert not utils.node_ignores_exception(nodes[2], ZeroDivisionError)
+ assert not utils.node_ignores_exception(nodes[3], ZeroDivisionError)
if __name__ == '__main__':
- unittest.main()
+ import sys
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_config.py b/pylint/test/unittest_config.py
index 2b40ed5c8..340c93744 100644
--- a/pylint/test/unittest_config.py
+++ b/pylint/test/unittest_config.py
@@ -7,48 +7,47 @@
import re
import sre_constants
-import unittest
from pylint import config
import pytest
-class ConfigValidatorTest(unittest.TestCase):
- def test__regexp_validator_valid(self):
- result = config._regexp_validator(None, None, "test_.*")
- assert isinstance(result, re._pattern_type)
- assert result.pattern == "test_.*"
-
- def test__regexp_validator_invalid(self):
- with pytest.raises(sre_constants.error):
- config._regexp_validator(None, None, "test_)")
-
- def test__csv_validator_no_spaces(self):
- values = ["One", "Two", "Three"]
- result = config._csv_validator(None, None, ",".join(values))
- assert isinstance(result, list)
- assert len(result) == 3
- for i, value in enumerate(values):
- assert result[i] == value
-
- def test__csv_validator_spaces(self):
- values = ["One", "Two", "Three"]
- result = config._csv_validator(None, None, ", ".join(values))
- assert isinstance(result, list)
- assert len(result) == 3
- for i, value in enumerate(values):
- assert result[i] == value
-
- def test__regexp_csv_validator_valid(self):
- pattern_strings = ["test_.*", "foo\.bar", "^baz$"]
- result = config._regexp_csv_validator(None, None, ",".join(pattern_strings))
- for i, regex in enumerate(result):
- assert isinstance(regex, re._pattern_type)
- assert regex.pattern == pattern_strings[i]
-
- def test__regexp_csv_validator_invalid(self):
- pattern_strings = ["test_.*", "foo\.bar", "^baz)$"]
- with pytest.raises(sre_constants.error):
- config._regexp_csv_validator(None, None, ",".join(pattern_strings))
+def test__regexp_validator_valid():
+ result = config._regexp_validator(None, None, "test_.*")
+ assert isinstance(result, re._pattern_type)
+ assert result.pattern == "test_.*"
+
+def test__regexp_validator_invalid():
+ with pytest.raises(sre_constants.error):
+ config._regexp_validator(None, None, "test_)")
+
+def test__csv_validator_no_spaces():
+ values = ["One", "Two", "Three"]
+ result = config._csv_validator(None, None, ",".join(values))
+ assert isinstance(result, list)
+ assert len(result) == 3
+ for i, value in enumerate(values):
+ assert result[i] == value
+
+def test__csv_validator_spaces():
+ values = ["One", "Two", "Three"]
+ result = config._csv_validator(None, None, ", ".join(values))
+ assert isinstance(result, list)
+ assert len(result) == 3
+ for i, value in enumerate(values):
+ assert result[i] == value
+
+def test__regexp_csv_validator_valid():
+ pattern_strings = ["test_.*", "foo\.bar", "^baz$"]
+ result = config._regexp_csv_validator(None, None, ",".join(pattern_strings))
+ for i, regex in enumerate(result):
+ assert isinstance(regex, re._pattern_type)
+ assert regex.pattern == pattern_strings[i]
+
+def test__regexp_csv_validator_invalid():
+ pattern_strings = ["test_.*", "foo\.bar", "^baz)$"]
+ with pytest.raises(sre_constants.error):
+ config._regexp_csv_validator(None, None, ",".join(pattern_strings))
if __name__ == "__main__":
- unittest.main()
+ import sys
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_lint.py b/pylint/test/unittest_lint.py
index 48219ec2d..35f75d4b6 100644
--- a/pylint/test/unittest_lint.py
+++ b/pylint/test/unittest_lint.py
@@ -15,17 +15,14 @@ import tempfile
from shutil import rmtree
from os import getcwd, chdir
from os.path import join, basename, dirname, isdir, abspath, sep
-import unittest
import six
from six.moves import reload_module
from pylint import config, lint
-from pylint.lint import PyLinter, Run, preprocess_options, \
- ArgumentPreprocessingError
+from pylint.lint import PyLinter, Run, preprocess_options, ArgumentPreprocessingError
from pylint.utils import MSG_STATE_SCOPE_CONFIG, MSG_STATE_SCOPE_MODULE, MSG_STATE_CONFIDENCE, \
- MessagesStore, PyLintASTWalker, MessageDefinition, FileState, \
- build_message_def, tokenize_module
+ MessagesStore, MessageDefinition, FileState, tokenize_module
from pylint.exceptions import InvalidMessageError, UnknownMessageError
import pylint.testutils as testutils
from pylint.reporters import text
@@ -127,13 +124,13 @@ def create_files(paths, chroot='.'):
open(filepath, 'w').close()
-class SysPathFixupTC(unittest.TestCase):
- def setUp(self):
+class TestSysPathFixup(object):
+ def setup_method(self):
self.orig = list(sys.path)
self.fake = [1, 2, 3]
sys.path[:] = self.fake
- def tearDown(self):
+ def teardown_method(self):
sys.path[:] = self.orig
def test_no_args(self):
@@ -199,9 +196,9 @@ class SysPathFixupTC(unittest.TestCase):
assert sys.path == self.fake
-class PyLinterTC(unittest.TestCase):
+class TestPyLinter(object):
- def setUp(self):
+ def setup_method(self):
self.linter = PyLinter()
self.linter.disable('I')
self.linter.config.persistent = 0
@@ -224,7 +221,7 @@ class PyLinterTC(unittest.TestCase):
@check_messages('custom')
def visit_class(self, _):
- pass
+ pass
self.linter.register_checker(CustomChecker(self.linter))
self.linter.open()
@@ -373,11 +370,11 @@ class PyLinterTC(unittest.TestCase):
assert linter.is_message_enabled('dangerous-default-value', 1)
def test_enable_report(self):
- assert self.linter.report_is_enabled('RP0001') == True
+ assert self.linter.report_is_enabled('RP0001') is True
self.linter.disable('RP0001')
- assert self.linter.report_is_enabled('RP0001') == False
+ assert self.linter.report_is_enabled('RP0001') is False
self.linter.enable('RP0001')
- assert self.linter.report_is_enabled('RP0001') == True
+ assert self.linter.report_is_enabled('RP0001') is True
def test_report_output_format_aliased(self):
text.register(self.linter)
@@ -497,9 +494,9 @@ class PyLinterTC(unittest.TestCase):
regexp = re.compile(re_str, re.MULTILINE)
assert re.search(regexp, output)
-class ConfigTC(unittest.TestCase):
+class TestConfig(object):
- def setUp(self):
+ def setup_method(self):
os.environ.pop('PYLINTRC', None)
def test_pylint_home(self):
@@ -527,12 +524,12 @@ class ConfigTC(unittest.TestCase):
def test_pylintrc(self):
with fake_home():
try:
- assert config.find_pylintrc() == None
+ assert config.find_pylintrc() is None
os.environ['PYLINTRC'] = join(tempfile.gettempdir(),
'.pylintrc')
- assert config.find_pylintrc() == None
+ assert config.find_pylintrc() is None
os.environ['PYLINTRC'] = '.'
- assert config.find_pylintrc() == None
+ assert config.find_pylintrc() is None
finally:
reload_module(config)
@@ -543,7 +540,7 @@ class ConfigTC(unittest.TestCase):
'a/b/c/__init__.py', 'a/b/c/d/__init__.py',
'a/b/c/d/e/.pylintrc'])
with fake_home():
- assert config.find_pylintrc() == None
+ assert config.find_pylintrc() is None
results = {'a' : join(chroot, 'a', 'pylintrc'),
'a/b' : join(chroot, 'a', 'b', 'pylintrc'),
'a/b/c' : join(chroot, 'a', 'b', 'pylintrc'),
@@ -558,7 +555,7 @@ class ConfigTC(unittest.TestCase):
with tempdir() as chroot:
with fake_home():
create_files(['a/pylintrc', 'a/b/pylintrc', 'a/b/c/d/__init__.py'])
- assert config.find_pylintrc() == None
+ assert config.find_pylintrc() is None
results = {'a' : join(chroot, 'a', 'pylintrc'),
'a/b' : join(chroot, 'a', 'b', 'pylintrc'),
'a/b/c' : None,
@@ -569,7 +566,7 @@ class ConfigTC(unittest.TestCase):
assert config.find_pylintrc() == expected
-class PreprocessOptionsTC(unittest.TestCase):
+class TestPreprocessOptions(object):
def _callback(self, name, value):
self.args.append((name, value))
@@ -603,8 +600,8 @@ class PreprocessOptionsTC(unittest.TestCase):
{'bar' : (None, False)})
-class MessagesStoreTC(unittest.TestCase):
- def setUp(self):
+class TestMessagesStore(object):
+ def setup_method(self):
self.store = MessagesStore()
class Checker(object):
name = 'achecker'
@@ -690,7 +687,7 @@ class MessagesStoreTC(unittest.TestCase):
self.store.check_message_id('old-symbol').symbol
-class RunTestCase(unittest.TestCase):
+class TestRunCase(object):
def test_custom_should_analyze_file(self):
'''Check that we can write custom should_analyze_file that work
@@ -725,4 +722,4 @@ class RunTestCase(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_pyreverse_diadefs.py b/pylint/test/unittest_pyreverse_diadefs.py
index ec4ea158f..bbeea426d 100644
--- a/pylint/test/unittest_pyreverse_diadefs.py
+++ b/pylint/test/unittest_pyreverse_diadefs.py
@@ -5,19 +5,15 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""
-unittest for the extensions.diadefslib modules
+unit test for the extensions.diadefslib modules
"""
-import unittest
-import sys
-
import six
-import astroid
-from astroid import MANAGER
-
import pytest
+import astroid
+
from pylint.pyreverse.inspector import Linker
from pylint.pyreverse.diadefslib import *
@@ -42,43 +38,43 @@ def _process_relations(relations):
return result
-class DiaDefGeneratorTC(unittest.TestCase):
- def test_option_values(self):
- """test for ancestor, associated and module options"""
- handler = DiadefsHandler(Config())
- df_h = DiaDefGenerator(Linker(PROJECT), handler)
- cl_config = Config()
- cl_config.classes = ['Specialization']
- cl_h = DiaDefGenerator(Linker(PROJECT), DiadefsHandler(cl_config) )
- assert (0, 0) == df_h._get_levels()
- assert False == df_h.module_names
- assert (-1, -1) == cl_h._get_levels()
- assert True == cl_h.module_names
- for hndl in [df_h, cl_h]:
- hndl.config.all_ancestors = True
- hndl.config.all_associated = True
- hndl.config.module_names = True
- hndl._set_default_options()
- assert (-1, -1) == hndl._get_levels()
- assert True == hndl.module_names
- handler = DiadefsHandler( Config())
- df_h = DiaDefGenerator(Linker(PROJECT), handler)
- cl_config = Config()
- cl_config.classes = ['Specialization']
- cl_h = DiaDefGenerator(Linker(PROJECT), DiadefsHandler(cl_config) )
- for hndl in [df_h, cl_h]:
- hndl.config.show_ancestors = 2
- hndl.config.show_associated = 1
- hndl.config.module_names = False
- hndl._set_default_options()
- assert (2, 1) == hndl._get_levels()
- assert False == hndl.module_names
- #def test_default_values(self):
- """test efault values for package or class diagrams"""
- # TODO : should test difference between default values for package
- # or class diagrams
-
-class DefaultDiadefGeneratorTC(unittest.TestCase):
+def test_option_values():
+ """test for ancestor, associated and module options"""
+ handler = DiadefsHandler(Config())
+ df_h = DiaDefGenerator(Linker(PROJECT), handler)
+ cl_config = Config()
+ cl_config.classes = ['Specialization']
+ cl_h = DiaDefGenerator(Linker(PROJECT), DiadefsHandler(cl_config) )
+ assert (0, 0) == df_h._get_levels()
+ assert False == df_h.module_names
+ assert (-1, -1) == cl_h._get_levels()
+ assert True == cl_h.module_names
+ for hndl in [df_h, cl_h]:
+ hndl.config.all_ancestors = True
+ hndl.config.all_associated = True
+ hndl.config.module_names = True
+ hndl._set_default_options()
+ assert (-1, -1) == hndl._get_levels()
+ assert True == hndl.module_names
+ handler = DiadefsHandler( Config())
+ df_h = DiaDefGenerator(Linker(PROJECT), handler)
+ cl_config = Config()
+ cl_config.classes = ['Specialization']
+ cl_h = DiaDefGenerator(Linker(PROJECT), DiadefsHandler(cl_config) )
+ for hndl in [df_h, cl_h]:
+ hndl.config.show_ancestors = 2
+ hndl.config.show_associated = 1
+ hndl.config.module_names = False
+ hndl._set_default_options()
+ assert (2, 1) == hndl._get_levels()
+ assert False == hndl.module_names
+
+#def test_default_values():
+ """test efault values for package or class diagrams"""
+ # TODO : should test difference between default values for package
+ # or class diagrams
+
+class TestDefaultDiadefGenerator(object):
def test_known_values1(self):
dd = DefaultDiadefGenerator(Linker(PROJECT), HANDLER).visit(PROJECT)
assert len(dd) == 2
@@ -89,15 +85,15 @@ class DefaultDiadefGeneratorTC(unittest.TestCase):
modules = sorted([(isinstance(m.node, astroid.Module), m.title)
for m in pd.objects])
assert modules == [(True, 'data'),
- (True, 'data.clientmodule_test'),
- (True, 'data.suppliermodule_test')]
+ (True, 'data.clientmodule_test'),
+ (True, 'data.suppliermodule_test')]
cd = dd[1]
assert cd.title == 'classes No Name'
classes = _process_classes(cd.objects)
assert classes == [(True, 'Ancestor'),
- (True, 'DoNothing'),
- (True, 'Interface'),
- (True, 'Specialization')]
+ (True, 'DoNothing'),
+ (True, 'Interface'),
+ (True, 'Specialization')]
_should_rels = [('association', 'DoNothing', 'Ancestor'),
('association', 'DoNothing', 'Specialization'),
@@ -133,32 +129,32 @@ class DefaultDiadefGeneratorTC(unittest.TestCase):
assert cd.title == 'classes No Name'
classes = _process_classes(cd.objects)
assert classes == [(True, 'Ancestor'),
- (True, 'DoNothing'),
- (True, 'Specialization')]
+ (True, 'DoNothing'),
+ (True, 'Specialization')]
-class ClassDiadefGeneratorTC(unittest.TestCase):
- def test_known_values1(self):
- HANDLER.config.classes = ['Specialization']
- cdg = ClassDiadefGenerator(Linker(PROJECT), HANDLER)
- special = 'data.clientmodule_test.Specialization'
- cd = cdg.class_diagram(PROJECT, special)
- assert cd.title == special
- classes = _process_classes(cd.objects)
- assert classes == [(True, 'data.clientmodule_test.Ancestor'),
- (True, special),
- (True, 'data.suppliermodule_test.DoNothing'),
- ]
- def test_known_values2(self):
- HANDLER.config.module_names = False
- cd = ClassDiadefGenerator(Linker(PROJECT), HANDLER).class_diagram(PROJECT, 'data.clientmodule_test.Specialization')
- assert cd.title == 'data.clientmodule_test.Specialization'
- classes = _process_classes(cd.objects)
- assert classes == [(True, 'Ancestor'),
- (True, 'DoNothing'),
- (True, 'Specialization')
- ]
+def test_known_values1():
+ HANDLER.config.classes = ['Specialization']
+ cdg = ClassDiadefGenerator(Linker(PROJECT), HANDLER)
+ special = 'data.clientmodule_test.Specialization'
+ cd = cdg.class_diagram(PROJECT, special)
+ assert cd.title == special
+ classes = _process_classes(cd.objects)
+ assert classes == [(True, 'data.clientmodule_test.Ancestor'),
+ (True, special),
+ (True, 'data.suppliermodule_test.DoNothing')]
+
+
+def test_known_values2():
+ HANDLER.config.module_names = False
+ cd = ClassDiadefGenerator(Linker(PROJECT), HANDLER).class_diagram(PROJECT, 'data.clientmodule_test.Specialization')
+ assert cd.title == 'data.clientmodule_test.Specialization'
+ classes = _process_classes(cd.objects)
+ assert classes == [(True, 'Ancestor'),
+ (True, 'DoNothing'),
+ (True, 'Specialization')]
if __name__ == '__main__':
- unittest.main()
+ import sys
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_pyreverse_inspector.py b/pylint/test/unittest_pyreverse_inspector.py
index ffacb0502..dea0026ad 100644
--- a/pylint/test/unittest_pyreverse_inspector.py
+++ b/pylint/test/unittest_pyreverse_inspector.py
@@ -7,7 +7,6 @@
for the visitors.diadefs module
"""
import os
-import unittest
import astroid
from astroid import nodes
@@ -19,14 +18,14 @@ from unittest_pyreverse_writer import get_project
MANAGER = manager.AstroidManager()
+
def astroid_wrapper(func, modname):
return func(modname)
-class LinkerTest(unittest.TestCase):
+class TestLinker(object):
- def setUp(self):
- super(LinkerTest, self).setUp()
+ def setup_method(self):
self.project = get_project('data', 'data')
self.linker = inspector.Linker(self.project)
self.linker.visit(self.project)
@@ -61,7 +60,7 @@ class LinkerTest(unittest.TestCase):
keys = sorted(type_dict.keys())
assert keys == ['_id', 'relation']
assert isinstance(type_dict['relation'][0], bases.Instance), \
- type_dict['relation']
+ type_dict['relation']
assert type_dict['relation'][0].name == 'DoNothing'
assert type_dict['_id'][0] is astroid.YES
@@ -103,9 +102,7 @@ class LinkerTest(unittest.TestCase):
('Concrete2', ['MyIFace', 'AnotherIFace']),
('Concrete23', ['MyIFace', 'AnotherIFace'])):
klass = module[klass]
- assert [i.name for i in inspector.interfaces(klass)] == \
- interfaces
-
+ assert [i.name for i in inspector.interfaces(klass)] == interfaces
def test_from_directory(self):
expected = os.path.join('pylint', 'test', 'data', '__init__.py')
@@ -120,6 +117,7 @@ class LinkerTest(unittest.TestCase):
assert sorted(self.project.keys()) == expected
-
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_pyreverse_writer.py b/pylint/test/unittest_pyreverse_writer.py
index 69b5a9b21..a13cefe7a 100644
--- a/pylint/test/unittest_pyreverse_writer.py
+++ b/pylint/test/unittest_pyreverse_writer.py
@@ -5,18 +5,14 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""
-unittest for visitors.diadefs and extensions.diadefslib modules
+unit test for visitors.diadefs and extensions.diadefslib modules
"""
import os
-import sys
import codecs
-from os.path import join, dirname, abspath
from difflib import unified_diff
-import unittest
-from astroid import MANAGER
from pylint.pyreverse.inspector import Linker, project_from_files
from pylint.pyreverse.diadefslib import DefaultDiadefGenerator, DiadefsHandler
@@ -56,10 +52,10 @@ def get_project(module, name="No Name"):
CONFIG = Config()
-class DotWriterTC(unittest.TestCase):
+class TestDotWriter(object):
@classmethod
- def setUpClass(cls):
+ def setup_class(cls):
project = get_project(os.path.join(os.path.dirname(__file__), 'data'))
linker = Linker(project)
handler = DiadefsHandler(CONFIG)
@@ -70,7 +66,7 @@ class DotWriterTC(unittest.TestCase):
writer.write(dd)
@classmethod
- def tearDownClass(cls):
+ def teardown_class(cls):
for fname in ('packages_No_Name.dot', 'classes_No_Name.dot',):
try:
os.remove(fname)
@@ -83,11 +79,11 @@ class DotWriterTC(unittest.TestCase):
expected = _file_lines(expected_file)
generated = '\n'.join(generated)
expected = '\n'.join(expected)
- files = "\n *** expected : %s, generated : %s \n" % (
+ files = "\n *** expected : %s, generated : %s \n" % (
expected_file, generated_file)
assert expected == generated, '%s%s' % (
files, '\n'.join(line for line in unified_diff(
- expected.splitlines(), generated.splitlines() )))
+ expected.splitlines(), generated.splitlines() )))
os.remove(generated_file)
def test_package_diagram(self):
@@ -97,29 +93,29 @@ class DotWriterTC(unittest.TestCase):
self._test_same_file('classes_No_Name.dot')
+def test_special():
+ for name in ["__reduce_ex__", "__setattr__"]:
+ assert get_visibility(name) == 'special'
-class GetVisibilityTC(unittest.TestCase):
- def test_special(self):
- for name in ["__reduce_ex__", "__setattr__"]:
- assert get_visibility(name) == 'special'
+def test_private():
+ for name in ["__g_", "____dsf", "__23_9"]:
+ got = get_visibility(name)
+ assert got == 'private', 'got %s instead of private for value %s' % (got, name)
- def test_private(self):
- for name in ["__g_", "____dsf", "__23_9"]:
- got = get_visibility(name)
- assert got == 'private', \
- 'got %s instead of private for value %s' % (got, name)
- def test_public(self):
- assert get_visibility('simple') == 'public'
+def test_public():
+ assert get_visibility('simple') == 'public'
- def test_protected(self):
- for name in ["_","__", "___", "____", "_____", "___e__",
- "_nextsimple", "_filter_it_"]:
- got = get_visibility(name)
- assert got == 'protected', \
- 'got %s instead of protected for value %s' % (got, name)
+
+def test_protected():
+ for name in ["_", "__", "___", "____", "_____", "___e__",
+ "_nextsimple", "_filter_it_"]:
+ got = get_visibility(name)
+ assert got == 'protected', 'got %s instead of protected for value %s' % (got, name)
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_reporters_json.py b/pylint/test/unittest_reporters_json.py
index 0d1e22212..432a5e1b6 100644
--- a/pylint/test/unittest_reporters_json.py
+++ b/pylint/test/unittest_reporters_json.py
@@ -6,7 +6,6 @@
"""Test for the JSON reporter."""
import json
-import unittest
import six
@@ -15,39 +14,39 @@ from pylint import checkers
from pylint.reporters.json import JSONReporter
-class TestJSONReporter(unittest.TestCase):
+def test_simple_json_output():
+ output = six.StringIO()
- def test_simple_json_output(self):
- output = six.StringIO()
+ reporter = JSONReporter()
+ linter = PyLinter(reporter=reporter)
+ checkers.initialize(linter)
- reporter = JSONReporter()
- linter = PyLinter(reporter=reporter)
- checkers.initialize(linter)
+ linter.config.persistent = 0
+ linter.reporter.set_output(output)
+ linter.open()
+ linter.set_current_module('0123')
+ linter.add_message('line-too-long', line=1, args=(1, 2))
- linter.config.persistent = 0
- linter.reporter.set_output(output)
- linter.open()
- linter.set_current_module('0123')
- linter.add_message('line-too-long', line=1, args=(1, 2))
+ # we call this method because we didn't actually run the checkers
+ reporter.display_messages(None)
- # we call this method because we didn't actually run the checkers
- reporter.display_messages(None)
-
- expected_result = [[
- ("column", 0),
- ("line", 1),
- ("message", "Line too long (1/2)"),
- ("module", "0123"),
- ("obj", ""),
- ("path", "0123"),
- ("symbol", "line-too-long"),
- ("type", "convention"),
- ]]
- report_result = json.loads(output.getvalue())
- report_result = [sorted(report_result[0].items(),
- key=lambda item: item[0])]
- assert report_result == expected_result
+ expected_result = [[
+ ("column", 0),
+ ("line", 1),
+ ("message", "Line too long (1/2)"),
+ ("module", "0123"),
+ ("obj", ""),
+ ("path", "0123"),
+ ("symbol", "line-too-long"),
+ ("type", "convention"),
+ ]]
+ report_result = json.loads(output.getvalue())
+ report_result = [sorted(report_result[0].items(),
+ key=lambda item: item[0])]
+ assert report_result == expected_result
if __name__ == '__main__':
- unittest.main()
+ import sys
+ import pytest
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_reporting.py b/pylint/test/unittest_reporting.py
index 8d717d5a7..73d9cd6e6 100644
--- a/pylint/test/unittest_reporting.py
+++ b/pylint/test/unittest_reporting.py
@@ -6,26 +6,22 @@
import os
from os.path import join, dirname, abspath
-import unittest
import warnings
import six
-from pylint import __pkginfo__
from pylint.lint import PyLinter
from pylint import checkers
-from pylint.reporters import BaseReporter
from pylint.reporters.text import TextReporter, ParseableTextReporter
-from pylint.reporters.ureports.nodes import Section
import pytest
HERE = abspath(dirname(__file__))
INPUTDIR = join(HERE, 'input')
-class PyLinterTC(unittest.TestCase):
+class TestPyLinter():
- def setUp(self):
+ def setup_method(self):
self.linter = PyLinter(reporter=TextReporter())
self.linter.disable('I')
self.linter.config.persistent = 0
@@ -42,15 +38,15 @@ class PyLinterTC(unittest.TestCase):
self.linter.add_message('C0301', line=1, args=(1, 2))
self.linter.add_message('line-too-long', line=2, args=(3, 4))
assert output.getvalue() == \
- '************* Module 0123\n' \
- 'C0301:001\n' \
- 'C0301:002\n'
+ '************* Module 0123\n' \
+ 'C0301:001\n' \
+ 'C0301:002\n'
def test_parseable_output_deprecated(self):
with warnings.catch_warnings(record=True) as cm:
warnings.simplefilter("always")
ParseableTextReporter()
-
+
assert len(cm) == 1
assert isinstance(cm[0].message, DeprecationWarning)
@@ -67,9 +63,9 @@ class PyLinterTC(unittest.TestCase):
linter.set_current_module('0123')
linter.add_message('line-too-long', line=1, args=(1, 2))
assert output.getvalue() == \
- '************* Module 0123\n' \
- '0123:1: [C0301(line-too-long), ] ' \
- 'Line too long (1/2)\n'
+ '************* Module 0123\n' \
+ '0123:1: [C0301(line-too-long), ] ' \
+ 'Line too long (1/2)\n'
def test_display_results_is_renamed(self):
class CustomReporter(TextReporter):
@@ -82,4 +78,5 @@ class PyLinterTC(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ import sys
+ pytest.main(sys.argv)
diff --git a/pylint/test/unittest_utils.py b/pylint/test/unittest_utils.py
index 34224a519..57772f7f4 100644
--- a/pylint/test/unittest_utils.py
+++ b/pylint/test/unittest_utils.py
@@ -7,20 +7,17 @@
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
import re
-import unittest
import warnings
import astroid
-from pylint import __pkginfo__
from pylint import utils
-from pylint import interfaces
from pylint.checkers.utils import check_messages
from pylint.exceptions import InvalidMessageError
import pytest
-class PyLintASTWalkerTest(unittest.TestCase):
+class TestPyLintASTWalker(object):
class MockLinter(object):
def __init__(self, msgs):
self._msgs = msgs
@@ -78,20 +75,20 @@ class PyLintASTWalkerTest(unittest.TestCase):
assert not checker.called
-class RegexBlacklistTest(unittest.TestCase):
- def test__basename_in_blacklist_re_match(self):
- patterns = [re.compile(".*enchilada.*"), re.compile("unittest_.*")]
- assert utils._basename_in_blacklist_re("unittest_utils.py", patterns)
- assert utils._basename_in_blacklist_re("cheese_enchiladas.xml", patterns)
+def test__basename_in_blacklist_re_match():
+ patterns = [re.compile(".*enchilada.*"), re.compile("unittest_.*")]
+ assert utils._basename_in_blacklist_re("unittest_utils.py", patterns)
+ assert utils._basename_in_blacklist_re("cheese_enchiladas.xml", patterns)
- def test__basename_in_blacklist_re_nomatch(self):
- patterns = [re.compile(".*enchilada.*"), re.compile("unittest_.*")]
- assert not utils._basename_in_blacklist_re("test_utils.py", patterns)
- assert not utils._basename_in_blacklist_re("enchilad.py", patterns)
+def test__basename_in_blacklist_re_nomatch():
+ patterns = [re.compile(".*enchilada.*"), re.compile("unittest_.*")]
+ assert not utils._basename_in_blacklist_re("test_utils.py", patterns)
+ assert not utils._basename_in_blacklist_re("enchilad.py", patterns)
-class MessagesStoreRegisterMessagesTest(unittest.TestCase):
- def setUp(self):
+
+class TestMessagesStoreRegisterMessages(object):
+ def setup_method(self):
self.store = utils.MessagesStore()
def test_register_error_inconsistent_checker_id(self):
@@ -104,7 +101,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
assert str(cm.value) == \
- r"Inconsistent checker part in message id 'W4321' (expected 'x12xx')"
+ r"Inconsistent checker part in message id 'W4321' (expected 'x12xx')"
def test_register_error_new_id_duplicate_of_new(self):
class CheckerOne(object):
@@ -112,6 +109,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
msgs = {
'W1234': ('message one', 'msg-symbol-one', 'msg description.'),
}
+
class CheckerTwo(object):
name = 'checker_two'
msgs = {
@@ -120,8 +118,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
self.store.register_messages(CheckerOne())
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(CheckerTwo())
- assert str(cm.value) == \
- "Message id 'W1234' is already defined"
+ assert str(cm.value) == "Message id 'W1234' is already defined"
def test_register_error_new_id_duplicate_of_old(self):
class Checker(object):
@@ -133,8 +130,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
}
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
- assert str(cm.value) == \
- "Message id 'W1234' is already defined"
+ assert str(cm.value) == "Message id 'W1234' is already defined"
def test_register_error_old_id_duplicate_of_new(self):
class Checker(object):
@@ -146,8 +142,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
}
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
- assert str(cm.value) == \
- "Message id 'W1234' is already defined"
+ assert str(cm.value) == "Message id 'W1234' is already defined"
def test_register_error_old_id_duplicate_of_old(self):
class Checker(object):
@@ -160,9 +155,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
}
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
- assert str(cm.value) == \
- "Message id 'W1201' is already defined"
-
+ assert str(cm.value) == "Message id 'W1201' is already defined"
def test_register_error_new_symbol_duplicate_of_new(self):
class Checker(object):
@@ -173,8 +166,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
}
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
- assert str(cm.value) == \
- "Message symbol 'msg-symbol' is already defined"
+ assert str(cm.value) == "Message symbol 'msg-symbol' is already defined"
def test_register_error_new_symbol_duplicate_of_old(self):
class Checker(object):
@@ -186,8 +178,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
}
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
- assert str(cm.value) == \
- "Message symbol 'msg-symbol-one' is already defined"
+ assert str(cm.value) == "Message symbol 'msg-symbol-one' is already defined"
def test_register_error_old_symbol_duplicate_of_new(self):
class Checker(object):
@@ -199,8 +190,7 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
}
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
- assert str(cm.value) == \
- "Message symbol 'msg-symbol-one' is already defined"
+ assert str(cm.value) == "Message symbol 'msg-symbol-one' is already defined"
def test_register_error_old_symbol_duplicate_of_old(self):
class Checker(object):
@@ -214,22 +204,22 @@ class MessagesStoreRegisterMessagesTest(unittest.TestCase):
with pytest.raises(InvalidMessageError) as cm:
self.store.register_messages(Checker())
assert str(cm.value) == \
- "Message alternate name 'old-symbol-one' is already defined"
+ "Message alternate name 'old-symbol-one' is already defined"
-class MessageDefinitionTest(unittest.TestCase):
- def test_create_invalid_msgid(self):
- with pytest.raises(InvalidMessageError) as cm:
- utils.MessageDefinition('checker', 'W12345',
- 'msg', 'descr', 'symbol', 'scope')
- assert str(cm.value) == \
- "Invalid message id 'W12345'"
- def test_create_invalid_message_type(self):
- with pytest.raises(InvalidMessageError) as cm:
- utils.MessageDefinition('checker', 'Q1234',
- 'msg', 'descr', 'symbol', 'scope')
- assert str(cm.value) == \
- "Bad message type Q in 'Q1234'"
+def test_create_invalid_msgid():
+ with pytest.raises(InvalidMessageError) as cm:
+ utils.MessageDefinition('checker', 'W12345',
+ 'msg', 'descr', 'symbol', 'scope')
+ assert str(cm.value) == "Invalid message id 'W12345'"
+
+
+def test_create_invalid_message_type():
+ with pytest.raises(InvalidMessageError) as cm:
+ utils.MessageDefinition('checker', 'Q1234',
+ 'msg', 'descr', 'symbol', 'scope')
+ assert str(cm.value) == "Bad message type Q in 'Q1234'"
if __name__ == '__main__':
- unittest.main()
+ import sys
+ pytest.main(sys.argv)
diff --git a/pylint/testutils.py b/pylint/testutils.py
index 5df2b2593..6c505503a 100644
--- a/pylint/testutils.py
+++ b/pylint/testutils.py
@@ -17,7 +17,6 @@ from os import linesep, getcwd, sep
from os.path import abspath, basename, dirname, isdir, join, splitext
import sys
import re
-import unittest
import tempfile
import tokenize
@@ -202,12 +201,12 @@ def set_config(**kwargs):
return _wrapper
-class CheckerTestCase(unittest.TestCase):
- """A base testcase class for unittesting individual checker classes."""
+class CheckerTestCase(object):
+ """A base testcase class for unit testing individual checker classes."""
CHECKER_CLASS = None
CONFIG = {}
- def setUp(self):
+ def setup_method(self):
self.linter = UnittestLinter()
self.checker = self.CHECKER_CLASS(self.linter) # pylint: disable=not-callable
for key, value in six.iteritems(self.CONFIG):
@@ -233,7 +232,7 @@ class CheckerTestCase(unittest.TestCase):
msg = ('Expected messages did not match actual.\n'
'Expected:\n%s\nGot:\n%s' % ('\n'.join(repr(m) for m in messages),
'\n'.join(repr(m) for m in got)))
- self.assertEqual(list(messages), got, msg)
+ assert list(messages) == got, msg
def walk(self, node):
"""recursive walk on the given node"""
@@ -265,7 +264,7 @@ def exception_str(self, ex): # pylint: disable=unused-argument
# Test classes
-class LintTestUsingModule(unittest.TestCase):
+class LintTestUsingModule(object):
INPUT_DIR = None
DEFAULT_PACKAGE = 'input'
package = DEFAULT_PACKAGE
@@ -274,23 +273,10 @@ class LintTestUsingModule(unittest.TestCase):
depends = None
output = None
_TEST_TYPE = 'module'
- maxDiff = None
- def runTest(self):
- # This is a hack to make ./test/test_func.py work under pytest.
- pass
-
- def shortDescription(self):
- values = {'mode' : self._TEST_TYPE,
- 'input': self.module,
- 'pkg': self.package,
- 'cls': self.__class__.__name__}
-
- if self.package == self.DEFAULT_PACKAGE:
- msg = '%(mode)s test of input file "%(input)s" (%(cls)s)'
- else:
- msg = '%(mode)s test of input file "%(input)s" in "%(pkg)s" (%(cls)s)'
- return msg % values
+ # def runTest(self):
+ # # This is a hack to make ./test/test_func.py work under pytest.
+ # pass
def _test_functionality(self):
tocheck = [self.package+'.'+self.module]
@@ -301,8 +287,7 @@ class LintTestUsingModule(unittest.TestCase):
self._test(tocheck)
def _check_result(self, got):
- self.assertMultiLineEqual(self._get_expected().strip()+'\n',
- got.strip()+'\n')
+ assert self._get_expected().strip()+'\n' == got.strip()+'\n'
def _test(self, tocheck):
if INFO_TEST_RGX.match(self.module):