I have a project written in Django (Django 3.0, Python 3.8), using django-stubs to handle type annotations. Everything went fine until I wrote some tests:
from django.test import TestCase
class TestSomething(TestCase):
@classmethod
def setUpTestData(cls):
cls.some_value = 'foo'
cls.another_value = 'bar'
def test_me(self):
self.assertNotEqual(self.some_value, self.another_value)
When I run mypy, it raises '[attr-defined]' errors about the TestCase class attributes defined in setUpTestData
:
$ mypy --show-error-codes .
my_app/tests/test_something.py:6: error: "Type[TestSomething]" has no attribute "some_value" [attr-defined]
my_app/tests/test_something.py:7: error: "Type[TestSomething]" has no attribute "another_value" [attr-defined]
my_app/tests/test_something.py:10: error: error: "TestSomething" has no attribute "some_value" [attr-defined]
my_app/tests/test_something.py:10: error: error: "TestSomething" has no attribute "another_value" [attr-defined]
I cannot find any advice about type annotations in tests (even tests in general, not to mention Django or unittest tests specifically). I don't think I am using setUpTestData
to do anything it is not supposed to do, so I wonder why nobody reported such issues before.
My main question is:
How can I annotate this code to make mypy satisfied?
A corollary question:
Does it even make sense to add type annotations in tests? Maybe I should just configure mypy to ignore test modules?
Here's the mypy.ini file - I would rather not change the settings to be more lenient:
[mypy]
plugins = mypy_django_plugin.main
python_version = 3.8
ignore_missing_imports = True
strict_optional = True
disallow_subclassing_any = False
disallow_any_generics = True
disallow_untyped_calls = True
disallow_incomplete_defs = True
check_untyped_defs = True
disallow_untyped_decorators = True
no_implicit_optional = True
warn_redundant_casts = True
warn_unused_ignores = true
warn_return_any = True
[mypy.plugins.django-stubs]
django_settings_module = studio.settings
[mypy-*.migrations.*]
ignore_errors = True
Aucun commentaire:
Enregistrer un commentaire