From 6939b232a4b204deb3464615d9868db56eb5384a Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Mon, 30 Oct 2023 11:26:34 +0200 Subject: [PATCH] Format code with Ruff --- pytest_django/__init__.py | 4 +- pytest_django/asserts.py | 6 +- pytest_django/fixtures.py | 28 ++++---- pytest_django/live_server_helper.py | 2 +- pytest_django/plugin.py | 17 ++--- .../app/migrations/0001_initial.py | 1 - pytest_django_test/db_helpers.py | 22 ++---- pytest_django_test/db_router.py | 12 ++-- pytest_django_test/settings_base.py | 2 +- pytest_django_test/urls_overridden.py | 2 +- tests/conftest.py | 20 +++--- tests/test_asserts.py | 23 +++--- tests/test_database.py | 72 ++++++++++--------- tests/test_db_access_in_repr.py | 18 ++--- tests/test_db_setup.py | 63 ++++++++-------- tests/test_django_configurations.py | 48 +++++++------ tests/test_django_settings_module.py | 52 ++++++++------ tests/test_environment.py | 9 +-- tests/test_fixtures.py | 13 ++-- tests/test_manage_py_scan.py | 4 +- tests/test_unittest.py | 10 +-- tox.ini | 1 + 22 files changed, 214 insertions(+), 215 deletions(-) diff --git a/pytest_django/__init__.py b/pytest_django/__init__.py index 09f9c779e..78fd3dc7f 100644 --- a/pytest_django/__init__.py +++ b/pytest_django/__init__.py @@ -5,6 +5,6 @@ __version__ = "unknown" -__all__ = ( +__all__ = [ "__version__", -) +] diff --git a/pytest_django/asserts.py b/pytest_django/asserts.py index 36a60e970..f305fab07 100644 --- a/pytest_django/asserts.py +++ b/pytest_django/asserts.py @@ -113,7 +113,7 @@ def assertRaisesMessage( expected_exception: type[Exception], expected_message: str, *args, - **kwargs + **kwargs, ): ... @@ -121,7 +121,7 @@ def assertWarnsMessage( expected_warning: Warning, expected_message: str, *args, - **kwargs + **kwargs, ): ... @@ -209,7 +209,7 @@ def assertNumQueries( func=..., *args, using: str = ..., - **kwargs + **kwargs, ): ... diff --git a/pytest_django/fixtures.py b/pytest_django/fixtures.py index 73bb51584..4f7ad1dad 100644 --- a/pytest_django/fixtures.py +++ b/pytest_django/fixtures.py @@ -28,7 +28,7 @@ import django -_DjangoDbDatabases = Optional[Union[Literal['__all__'], Iterable[str]]] +_DjangoDbDatabases = Optional[Union[Literal["__all__"], Iterable[str]]] _DjangoDbAvailableApps = Optional[List[str]] # transaction, reset_sequences, databases, serialized_rollback, available_apps _DjangoDb = Tuple[bool, bool, _DjangoDbDatabases, bool, _DjangoDbAvailableApps] @@ -134,7 +134,7 @@ def django_db_setup( db_cfg = setup_databases( verbosity=request.config.option.verbose, interactive=False, - **setup_databases_args + **setup_databases_args, ) yield @@ -145,9 +145,7 @@ def django_db_setup( teardown_databases(db_cfg, verbosity=request.config.option.verbose) except Exception as exc: # noqa: BLE001 request.node.warn( - pytest.PytestWarning( - f"Error when trying to teardown test databases: {exc!r}" - ) + pytest.PytestWarning(f"Error when trying to teardown test databases: {exc!r}") ) @@ -181,13 +179,12 @@ def _django_db_helper( available_apps, ) = False, False, None, False, None - transactional = transactional or reset_sequences or ( - "transactional_db" in request.fixturenames - or "live_server" in request.fixturenames - ) - reset_sequences = reset_sequences or ( - "django_db_reset_sequences" in request.fixturenames + transactional = ( + transactional + or reset_sequences + or ("transactional_db" in request.fixturenames or "live_server" in request.fixturenames) ) + reset_sequences = reset_sequences or ("django_db_reset_sequences" in request.fixturenames) serialized_rollback = serialized_rollback or ( "django_db_serialized_rollback" in request.fixturenames ) @@ -229,6 +226,7 @@ class PytestDjangoTestCase(test_case_class): # type: ignore[misc,valid-type] # functionality to these methods, in which case skipping them completely # would not be desirable. Let's cross that bridge when we get there... if not transactional: + @classmethod def setUpClass(cls) -> None: super(django.test.TestCase, cls).setUpClass() @@ -558,9 +556,11 @@ def live_server(request: pytest.FixtureRequest): """ skip_if_no_django() - addr = request.config.getvalue("liveserver") or os.getenv( - "DJANGO_LIVE_TEST_SERVER_ADDRESS" - ) or "localhost" + addr = ( + request.config.getvalue("liveserver") + or os.getenv("DJANGO_LIVE_TEST_SERVER_ADDRESS") + or "localhost" + ) server = live_server_helper.LiveServer(addr) yield server diff --git a/pytest_django/live_server_helper.py b/pytest_django/live_server_helper.py index 9972e9909..03b92e1fa 100644 --- a/pytest_django/live_server_helper.py +++ b/pytest_django/live_server_helper.py @@ -45,7 +45,7 @@ def __init__(self, addr: str, *, start: bool = True) -> None: self.thread = LiveServerThread(host, **liveserver_kwargs) self._live_server_modified_settings = modify_settings( - ALLOWED_HOSTS={"append": host} + ALLOWED_HOSTS={"append": host}, ) # `_live_server_modified_settings` is enabled and disabled by # `_live_server_helper`. diff --git a/pytest_django/plugin.py b/pytest_django/plugin.py index 9b7b46da0..5197abb52 100644 --- a/pytest_django/plugin.py +++ b/pytest_django/plugin.py @@ -112,7 +112,8 @@ def pytest_addoption(parser: pytest.Parser) -> None: help="Enable Django migrations on test setup", ) parser.addini( - CONFIGURATION_ENV, "django-configurations class to use by pytest-django." + CONFIGURATION_ENV, + "django-configurations class to use by pytest-django.", ) group.addoption( "--liveserver", @@ -120,7 +121,8 @@ def pytest_addoption(parser: pytest.Parser) -> None: help="Address and port for the live_server fixture.", ) parser.addini( - SETTINGS_MODULE_ENV, "Django settings module to use by pytest-django." + SETTINGS_MODULE_ENV, + "Django settings module to use by pytest-django.", ) parser.addini( @@ -131,8 +133,7 @@ def pytest_addoption(parser: pytest.Parser) -> None: ) parser.addini( "django_debug_mode", - "How to set the Django DEBUG setting (default `False`). " - "Use `keep` to not override.", + "How to set the Django DEBUG setting (default `False`). " "Use `keep` to not override.", default="False", ) group.addoption( @@ -308,9 +309,7 @@ def pytest_load_initial_conftests( if ( options.itv - or _get_boolean_value( - os.environ.get(INVALID_TEMPLATE_VARS_ENV), INVALID_TEMPLATE_VARS_ENV - ) + or _get_boolean_value(os.environ.get(INVALID_TEMPLATE_VARS_ENV), INVALID_TEMPLATE_VARS_ENV) or early_config.getini(INVALID_TEMPLATE_VARS_ENV) ): os.environ[INVALID_TEMPLATE_VARS_ENV] = "true" @@ -370,6 +369,7 @@ def pytest_report_header(config: pytest.Config) -> list[str] | None: if "django" in sys.modules: import django + report_header.insert(0, f"version: {django.get_version()}") if report_header: @@ -534,6 +534,7 @@ def _django_setup_unittest( # Before pytest 5.4: https://github.com/pytest-dev/pytest/issues/5991 # After pytest 5.4: https://github.com/pytest-dev/pytest-django/issues/824 from _pytest.unittest import TestCaseFunction + original_runtest = TestCaseFunction.runtest def non_debugging_runtest(self) -> None: @@ -707,7 +708,7 @@ def _template_string_if_invalid_marker( request: pytest.FixtureRequest, ) -> None: """Apply the @pytest.mark.ignore_template_errors marker, - internal to pytest-django.""" + internal to pytest-django.""" marker = request.keywords.get("ignore_template_errors", None) if os.environ.get(INVALID_TEMPLATE_VARS_ENV, "false") == "true": if marker and django_settings_is_configured(): diff --git a/pytest_django_test/app/migrations/0001_initial.py b/pytest_django_test/app/migrations/0001_initial.py index ac2f7ef6c..c2545f161 100644 --- a/pytest_django_test/app/migrations/0001_initial.py +++ b/pytest_django_test/app/migrations/0001_initial.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - initial = True dependencies: tuple[tuple[str, str], ...] = () diff --git a/pytest_django_test/db_helpers.py b/pytest_django_test/db_helpers.py index bb26d3151..712af0d3f 100644 --- a/pytest_django_test/db_helpers.py +++ b/pytest_django_test/db_helpers.py @@ -30,8 +30,8 @@ # An explicit test db name was given, is that as the base name TEST_DB_NAME = f"{TEST_DB_NAME}_inner" - SECOND_DB_NAME = DB_NAME + '_second' if DB_NAME is not None else None - SECOND_TEST_DB_NAME = TEST_DB_NAME + '_second' if DB_NAME is not None else None + SECOND_DB_NAME = DB_NAME + "_second" if DB_NAME is not None else None + SECOND_TEST_DB_NAME = TEST_DB_NAME + "_second" if DB_NAME is not None else None def get_db_engine() -> str: @@ -87,10 +87,7 @@ def run_mysql(*args: str) -> CmdResult: def skip_if_sqlite_in_memory() -> None: - if ( - _settings["ENGINE"] == "django.db.backends.sqlite3" - and _settings["TEST"]["NAME"] is None - ): + if _settings["ENGINE"] == "django.db.backends.sqlite3" and _settings["TEST"]["NAME"] is None: pytest.skip("Do not test db reuse since database does not support it") @@ -107,9 +104,7 @@ def drop_database(db_suffix: str | None = None) -> None: if db_engine == "postgresql": r = run_psql("postgres", "-c", f"DROP DATABASE {name}") - assert "DROP DATABASE" in force_str( - r.std_out - ) or "does not exist" in force_str(r.std_err) + assert "DROP DATABASE" in force_str(r.std_out) or "does not exist" in force_str(r.std_err) return if db_engine == "mysql": @@ -136,8 +131,7 @@ def db_exists(db_suffix: str | None = None) -> bool: return r.status_code == 0 assert db_engine == "sqlite3", f"{db_engine} cannot be tested properly!" - assert TEST_DB_NAME != ":memory:", ( - "sqlite in-memory database cannot be checked for existence!") + assert TEST_DB_NAME != ":memory:", "sqlite in-memory database cannot be checked for existence!" return os.path.exists(name) @@ -155,8 +149,7 @@ def mark_database() -> None: return assert db_engine == "sqlite3", f"{db_engine} cannot be tested properly!" - assert TEST_DB_NAME != ":memory:", ( - "sqlite in-memory database cannot be marked!") + assert TEST_DB_NAME != ":memory:", "sqlite in-memory database cannot be marked!" conn = sqlite3.connect(TEST_DB_NAME) try: @@ -180,8 +173,7 @@ def mark_exists() -> bool: return r.status_code == 0 assert db_engine == "sqlite3", f"{db_engine} cannot be tested properly!" - assert TEST_DB_NAME != ":memory:", ( - "sqlite in-memory database cannot be checked for mark!") + assert TEST_DB_NAME != ":memory:", "sqlite in-memory database cannot be checked for mark!" conn = sqlite3.connect(TEST_DB_NAME) try: diff --git a/pytest_django_test/db_router.py b/pytest_django_test/db_router.py index c2486e957..e18ae8530 100644 --- a/pytest_django_test/db_router.py +++ b/pytest_django_test/db_router.py @@ -1,14 +1,14 @@ class DbRouter: def db_for_read(self, model, **hints): - if model._meta.app_label == 'app' and model._meta.model_name == 'seconditem': - return 'second' + if model._meta.app_label == "app" and model._meta.model_name == "seconditem": + return "second" return None def db_for_write(self, model, **hints): - if model._meta.app_label == 'app' and model._meta.model_name == 'seconditem': - return 'second' + if model._meta.app_label == "app" and model._meta.model_name == "seconditem": + return "second" return None def allow_migrate(self, db, app_label, model_name=None, **hints): - if app_label == 'app' and model_name == 'seconditem': - return db == 'second' + if app_label == "app" and model_name == "seconditem": + return db == "second" diff --git a/pytest_django_test/settings_base.py b/pytest_django_test/settings_base.py index d1694cd28..132bbd234 100644 --- a/pytest_django_test/settings_base.py +++ b/pytest_django_test/settings_base.py @@ -28,6 +28,6 @@ } ] -DATABASE_ROUTERS = ['pytest_django_test.db_router.DbRouter'] +DATABASE_ROUTERS = ["pytest_django_test.db_router.DbRouter"] USE_TZ = True diff --git a/pytest_django_test/urls_overridden.py b/pytest_django_test/urls_overridden.py index b84507fed..72d9c183c 100644 --- a/pytest_django_test/urls_overridden.py +++ b/pytest_django_test/urls_overridden.py @@ -3,5 +3,5 @@ urlpatterns = [ - path("overridden_url/", lambda r: HttpResponse("Overridden urlconf works!")) + path("overridden_url/", lambda r: HttpResponse("Overridden urlconf works!")), ] diff --git a/tests/conftest.py b/tests/conftest.py index 84340433c..cf08a3bc0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -20,7 +20,8 @@ def pytest_configure(config: pytest.Config) -> None: config.addinivalue_line( - "markers", "django_project: options for the django_pytester fixture" + "markers", + "django_project: options for the django_pytester fixture", ) @@ -68,9 +69,8 @@ def django_pytester( db_settings["second"]["NAME"] = SECOND_DB_NAME db_settings["second"].setdefault("TEST", {})["NAME"] = SECOND_TEST_DB_NAME - test_settings = ( - dedent( - """ + test_settings = dedent( + """ import django # Pypy compatibility @@ -109,13 +109,11 @@ def django_pytester( ] %(extra_settings)s - """ - ) - % { - "db_settings": repr(db_settings), - "extra_settings": dedent(options["extra_settings"]), - } - ) + """ + ) % { + "db_settings": repr(db_settings), + "extra_settings": dedent(options["extra_settings"]), + } if options["project_root"]: project_root = pytester.mkdir(options["project_root"]) diff --git a/tests/test_asserts.py b/tests/test_asserts.py index 20e629952..d8ef24558 100644 --- a/tests/test_asserts.py +++ b/tests/test_asserts.py @@ -19,17 +19,20 @@ def _get_actual_assertions_names() -> list[str]: from django.test import TestCase as DjangoTestCase - obj = DjangoTestCase('run') + obj = DjangoTestCase("run") def is_assert(func) -> bool: - return func.startswith('assert') and '_' not in func + return func.startswith("assert") and "_" not in func - base_methods = [name for name, member in - inspect.getmembers(DefaultTestCase) - if is_assert(name)] + base_methods = [ + name for name, member in inspect.getmembers(DefaultTestCase) if is_assert(name) + ] - return [name for name, member in inspect.getmembers(obj) - if is_assert(name) and name not in base_methods] + return [ + name + for name, member in inspect.getmembers(obj) + if is_assert(name) and name not in base_methods + ] def test_django_asserts_available() -> None: @@ -47,11 +50,11 @@ def test_sanity() -> None: from pytest_django.asserts import assertContains, assertNumQueries - response = HttpResponse('My response') + response = HttpResponse("My response") - assertContains(response, 'My response') + assertContains(response, "My response") with pytest.raises(AssertionError): - assertContains(response, 'Not my response') + assertContains(response, "Not my response") assertNumQueries(0, lambda: 1 + 1) with assertNumQueries(0): diff --git a/tests/test_database.py b/tests/test_database.py index a18cebf4a..14b0f0385 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -13,8 +13,7 @@ def db_supports_reset_sequences() -> bool: """Return if the current db engine supports `reset_sequences`.""" ret: bool = ( - connection.features.supports_transactions - and connection.features.supports_sequence_reset + connection.features.supports_transactions and connection.features.supports_sequence_reset ) return ret @@ -54,12 +53,14 @@ def non_zero_sequences_counter(db: None) -> None: class TestDatabaseFixtures: """Tests for the different database fixtures.""" - @pytest.fixture(params=[ - "db", - "transactional_db", - "django_db_reset_sequences", - "django_db_serialized_rollback", - ]) + @pytest.fixture( + params=[ + "db", + "transactional_db", + "django_db_reset_sequences", + "django_db_serialized_rollback", + ] + ) def all_dbs(self, request: pytest.FixtureRequest) -> None: if request.param == "django_db_reset_sequences": request.getfixturevalue("django_db_reset_sequences") @@ -70,7 +71,7 @@ def all_dbs(self, request: pytest.FixtureRequest) -> None: elif request.param == "django_db_serialized_rollback": request.getfixturevalue("django_db_serialized_rollback") else: - raise AssertionError() # pragma: no cover + raise AssertionError() # pragma: no cover def test_access(self, all_dbs: None) -> None: Item.objects.create(name="spam") @@ -92,7 +93,8 @@ def test_transactions_enabled(self, transactional_db: None) -> None: assert not connection.in_atomic_block def test_transactions_enabled_via_reset_seq( - self, django_db_reset_sequences: None, + self, + django_db_reset_sequences: None, ) -> None: if not connection.features.supports_transactions: pytest.skip("transactions required for this test") @@ -100,9 +102,11 @@ def test_transactions_enabled_via_reset_seq( assert not connection.in_atomic_block def test_django_db_reset_sequences_fixture( - self, db: None, django_pytester: DjangoPytester, non_zero_sequences_counter: None, + self, + db: None, + django_pytester: DjangoPytester, + non_zero_sequences_counter: None, ) -> None: - if not db_supports_reset_sequences(): pytest.skip( "transactions and reset_sequences must be supported " @@ -124,9 +128,7 @@ def test_django_db_reset_sequences_requested( ) result = django_pytester.runpytest_subprocess("-v", "--reuse-db") - result.stdout.fnmatch_lines( - ["*test_django_db_reset_sequences_requested PASSED*"] - ) + result.stdout.fnmatch_lines(["*test_django_db_reset_sequences_requested PASSED*"]) def test_serialized_rollback(self, db: None, django_pytester: DjangoPytester) -> None: django_pytester.create_app_file( @@ -246,7 +248,7 @@ def test_reset_sequences( # The test works when transactions are not supported, but it interacts # badly with other tests. - @pytest.mark.skipif('not connection.features.supports_transactions') + @pytest.mark.skipif("not connection.features.supports_transactions") def test_serialized_rollback( self, fixture_with_serialized_rollback: None, @@ -303,40 +305,40 @@ def test_transaction_reset_sequences_enabled(self, request: pytest.FixtureReques marker = request.node.get_closest_marker("django_db") assert marker.kwargs["reset_sequences"] - @pytest.mark.django_db(databases=['default', 'replica', 'second']) + @pytest.mark.django_db(databases=["default", "replica", "second"]) def test_databases(self, request: pytest.FixtureRequest) -> None: marker = request.node.get_closest_marker("django_db") - assert marker.kwargs["databases"] == ['default', 'replica', 'second'] + assert marker.kwargs["databases"] == ["default", "replica", "second"] - @pytest.mark.django_db(databases=['second']) + @pytest.mark.django_db(databases=["second"]) def test_second_database(self, request: pytest.FixtureRequest) -> None: SecondItem.objects.create(name="spam") - @pytest.mark.django_db(databases=['default']) + @pytest.mark.django_db(databases=["default"]) def test_not_allowed_database(self, request: pytest.FixtureRequest) -> None: - with pytest.raises(AssertionError, match='not allowed'): + with pytest.raises(AssertionError, match="not allowed"): SecondItem.objects.count() - with pytest.raises(AssertionError, match='not allowed'): + with pytest.raises(AssertionError, match="not allowed"): SecondItem.objects.create(name="spam") - @pytest.mark.django_db(databases=['replica']) + @pytest.mark.django_db(databases=["replica"]) def test_replica_database(self, request: pytest.FixtureRequest) -> None: - Item.objects.using('replica').count() + Item.objects.using("replica").count() - @pytest.mark.django_db(databases=['replica']) + @pytest.mark.django_db(databases=["replica"]) def test_replica_database_not_allowed(self, request: pytest.FixtureRequest) -> None: - with pytest.raises(AssertionError, match='not allowed'): + with pytest.raises(AssertionError, match="not allowed"): Item.objects.count() - @pytest.mark.django_db(transaction=True, databases=['default', 'replica']) + @pytest.mark.django_db(transaction=True, databases=["default", "replica"]) def test_replica_mirrors_default_database(self, request: pytest.FixtureRequest) -> None: - Item.objects.create(name='spam') - Item.objects.using('replica').create(name='spam') + Item.objects.create(name="spam") + Item.objects.using("replica").create(name="spam") assert Item.objects.count() == 2 - assert Item.objects.using('replica').count() == 2 + assert Item.objects.using("replica").count() == 2 - @pytest.mark.django_db(databases='__all__') + @pytest.mark.django_db(databases="__all__") def test_all_databases(self, request: pytest.FixtureRequest) -> None: Item.objects.count() Item.objects.create(name="spam") @@ -350,7 +352,7 @@ def test_serialized_rollback_disabled(self, request: pytest.FixtureRequest): # The test works when transactions are not supported, but it interacts # badly with other tests. - @pytest.mark.skipif('not connection.features.supports_transactions') + @pytest.mark.skipif("not connection.features.supports_transactions") @pytest.mark.django_db(serialized_rollback=True) def test_serialized_rollback_enabled(self, request: pytest.FixtureRequest): marker = request.node.get_closest_marker("django_db") @@ -361,10 +363,10 @@ def test_available_apps_disabled(self, request: pytest.FixtureRequest) -> None: marker = request.node.get_closest_marker("django_db") assert not marker.kwargs - @pytest.mark.django_db(available_apps=['pytest_django_test.app']) + @pytest.mark.django_db(available_apps=["pytest_django_test.app"]) def test_available_apps_enabled(self, request: pytest.FixtureRequest) -> None: marker = request.node.get_closest_marker("django_db") - assert marker.kwargs["available_apps"] == ['pytest_django_test.app'] + assert marker.kwargs["available_apps"] == ["pytest_django_test.app"] @pytest.mark.django_db def test_available_apps_default(self, request: pytest.FixtureRequest) -> None: @@ -374,7 +376,7 @@ def test_available_apps_default(self, request: pytest.FixtureRequest) -> None: for app in settings.INSTALLED_APPS: assert apps.is_installed(app) - @pytest.mark.django_db(available_apps=['pytest_django_test.app']) + @pytest.mark.django_db(available_apps=["pytest_django_test.app"]) def test_available_apps_limited(self, request: pytest.FixtureRequest) -> None: from django.apps import apps from django.conf import settings diff --git a/tests/test_db_access_in_repr.py b/tests/test_db_access_in_repr.py index 77b81cce0..065696d99 100644 --- a/tests/test_db_access_in_repr.py +++ b/tests/test_db_access_in_repr.py @@ -18,13 +18,15 @@ def test_via_db_fixture(db): ) result = django_pytester.runpytest_subprocess("--tb=auto") - result.stdout.fnmatch_lines([ - "tpkg/test_the_test.py FF", - "E *DoesNotExist: Item matching query does not exist.", - "tpkg/test_the_test.py:8: ", - 'self = *RuntimeError*Database access not allowed*', - "E *DoesNotExist: Item matching query does not exist.", - "* 2 failed*", - ]) + result.stdout.fnmatch_lines( + [ + "tpkg/test_the_test.py FF", + "E *DoesNotExist: Item matching query does not exist.", + "tpkg/test_the_test.py:8: ", + "self = *RuntimeError*Database access not allowed*", + "E *DoesNotExist: Item matching query does not exist.", + "* 2 failed*", + ] + ) assert "INTERNALERROR" not in str(result.stdout) + str(result.stderr) assert result.ret == 1 diff --git a/tests/test_db_setup.py b/tests/test_db_setup.py index 82be2f690..9d6f0cfe8 100644 --- a/tests/test_db_setup.py +++ b/tests/test_db_setup.py @@ -37,7 +37,8 @@ def test_db_can_be_accessed(): def test_db_order(django_pytester: DjangoPytester) -> None: """Test order in which tests are being executed.""" - django_pytester.create_test_module(''' + django_pytester.create_test_module( + """ import pytest from unittest import TestCase from django.test import SimpleTestCase @@ -93,24 +94,28 @@ def test_run_first_serialized_rollback_decorator(): class MyTestCase(TestCase): def test_run_last_test_case(self): pass - ''') - result = django_pytester.runpytest_subprocess('-q', '--collect-only') + """ + ) + result = django_pytester.runpytest_subprocess("-q", "--collect-only") assert result.ret == 0 - result.stdout.fnmatch_lines([ - "*test_run_first_fixture*", - "*test_run_first_fixture_class*", - "*test_run_first_django_test_case*", - "*test_run_first_decorator*", - "*test_run_first_serialized_rollback_decorator*", - "*test_run_second_decorator*", - "*test_run_second_fixture*", - "*test_run_second_reset_sequences_fixture*", - "*test_run_second_transaction_test_case*", - "*test_run_second_fixture_class*", - "*test_run_second_reset_sequences_decorator*", - "*test_run_last_simple_test_case*", - "*test_run_last_test_case*", - ], consecutive=True) + result.stdout.fnmatch_lines( + [ + "*test_run_first_fixture*", + "*test_run_first_fixture_class*", + "*test_run_first_django_test_case*", + "*test_run_first_decorator*", + "*test_run_first_serialized_rollback_decorator*", + "*test_run_second_decorator*", + "*test_run_second_fixture*", + "*test_run_second_reset_sequences_fixture*", + "*test_run_second_transaction_test_case*", + "*test_run_second_fixture_class*", + "*test_run_second_reset_sequences_decorator*", + "*test_run_last_simple_test_case*", + "*test_run_last_test_case*", + ], + consecutive=True, + ) def test_db_reuse(django_pytester: DjangoPytester) -> None: @@ -154,9 +159,7 @@ def test_db_can_be_accessed(): # Make sure the database has not been re-created assert mark_exists() - result_third = django_pytester.runpytest_subprocess( - "-v", "--reuse-db", "--create-db" - ) + result_third = django_pytester.runpytest_subprocess("-v", "--reuse-db", "--create-db") assert result_third.ret == 0 result_third.stdout.fnmatch_lines(["*test_db_can_be_accessed PASSED*"]) @@ -166,7 +169,6 @@ def test_db_can_be_accessed(): class TestSqlite: - db_settings: ClassVar = { "default": { "ENGINE": "django.db.backends.sqlite3", @@ -176,7 +178,6 @@ class TestSqlite: } def test_sqlite_test_name_used(self, django_pytester: DjangoPytester) -> None: - django_pytester.create_test_module( """ import pytest @@ -259,9 +260,7 @@ def test_d(settings): result.stdout.fnmatch_lines(["*PASSED*test_c*"]) result.stdout.fnmatch_lines(["*PASSED*test_d*"]) - result = django_pytester.runpytest_subprocess( - "-vv", "-n2", "-s", "--reuse-db", "--create-db" - ) + result = django_pytester.runpytest_subprocess("-vv", "-n2", "-s", "--reuse-db", "--create-db") assert result.ret == 0 result.stdout.fnmatch_lines(["*PASSED*test_a*"]) result.stdout.fnmatch_lines(["*PASSED*test_b*"]) @@ -274,7 +273,6 @@ def test_d(settings): class TestSqliteWithXdist: - db_settings: ClassVar = { "default": { "ENGINE": "django.db.backends.sqlite3", @@ -306,7 +304,6 @@ def test_a(): class TestSqliteWithMultipleDbsAndXdist: - db_settings: ClassVar = { "default": { "ENGINE": "django.db.backends.sqlite3", @@ -316,7 +313,7 @@ class TestSqliteWithMultipleDbsAndXdist: "ENGINE": "django.db.backends.sqlite3", "NAME": "db_name", "TEST": {"NAME": "test_custom_db_name"}, - } + }, } def test_sqlite_database_renamed(self, django_pytester: DjangoPytester) -> None: @@ -356,7 +353,6 @@ def test_a(): class TestSqliteWithTox: - db_settings: ClassVar = { "default": { "ENGINE": "django.db.backends.sqlite3", @@ -423,7 +419,6 @@ def test_inner(): class TestSqliteWithToxAndXdist: - db_settings: ClassVar = { "default": { "ENGINE": "django.db.backends.sqlite3", @@ -463,7 +458,6 @@ def test_inner(): class TestSqliteInMemoryWithXdist: - db_settings: ClassVar = { "default": { "ENGINE": "django.db.backends.sqlite3", @@ -518,7 +512,10 @@ def test_inner_migrations(): ) result = django_pytester.runpytest_subprocess( - "--nomigrations", "--tb=short", "-vv", "-s", + "--nomigrations", + "--tb=short", + "-vv", + "-s", ) assert result.ret == 0 assert "Operations to perform:" not in result.stdout.str() diff --git a/tests/test_django_configurations.py b/tests/test_django_configurations.py index 681c8a7d7..e3bc6b26f 100644 --- a/tests/test_django_configurations.py +++ b/tests/test_django_configurations.py @@ -41,11 +41,13 @@ def test_settings(): """ ) result = pytester.runpytest_subprocess() - result.stdout.fnmatch_lines([ - "django: version: *, settings: tpkg.settings_env (from env), " - "configuration: MySettings (from env)", - "* 1 passed*", - ]) + result.stdout.fnmatch_lines( + [ + "django: version: *, settings: tpkg.settings_env (from env), " + "configuration: MySettings (from env)", + "* 1 passed*", + ] + ) assert result.ret == 0 @@ -73,11 +75,13 @@ def test_ds(): """ ) result = pytester.runpytest_subprocess() - result.stdout.fnmatch_lines([ - "django: version: *, settings: tpkg.settings_env (from env), " - "configuration: MySettings (from env)", - "* 1 passed*", - ]) + result.stdout.fnmatch_lines( + [ + "django: version: *, settings: tpkg.settings_env (from env), " + "configuration: MySettings (from env)", + "* 1 passed*", + ] + ) assert result.ret == 0 @@ -104,11 +108,13 @@ def test_ds(): """ ) result = pytester.runpytest_subprocess() - result.stdout.fnmatch_lines([ - "django: version: *, settings: tpkg.settings_ini (from ini), " - "configuration: MySettings (from ini)", - "* 1 passed*", - ]) + result.stdout.fnmatch_lines( + [ + "django: version: *, settings: tpkg.settings_ini (from ini), " + "configuration: MySettings (from ini)", + "* 1 passed*", + ] + ) assert result.ret == 0 @@ -136,9 +142,11 @@ def test_ds(): """ ) result = pytester.runpytest_subprocess("--ds=tpkg.settings_opt", "--dc=MySettings") - result.stdout.fnmatch_lines([ - 'django: version: *, settings: tpkg.settings_opt (from option),' - ' configuration: MySettings (from option)', - "* 1 passed*", - ]) + result.stdout.fnmatch_lines( + [ + "django: version: *, settings: tpkg.settings_opt (from option)," + " configuration: MySettings (from option)", + "* 1 passed*", + ] + ) assert result.ret == 0 diff --git a/tests/test_django_settings_module.py b/tests/test_django_settings_module.py index 9bfc3cdf0..2312fa149 100644 --- a/tests/test_django_settings_module.py +++ b/tests/test_django_settings_module.py @@ -37,10 +37,12 @@ def test_ds(): """ ) result = pytester.runpytest_subprocess() - result.stdout.fnmatch_lines([ - "django: version: *, settings: tpkg.settings_ini (from ini)", - "*= 1 passed*", - ]) + result.stdout.fnmatch_lines( + [ + "django: version: *, settings: tpkg.settings_ini (from ini)", + "*= 1 passed*", + ] + ) assert result.ret == 0 @@ -58,10 +60,12 @@ def test_settings(): """ ) result = pytester.runpytest_subprocess() - result.stdout.fnmatch_lines([ - "django: version: *, settings: tpkg.settings_env (from env)", - "*= 1 passed*", - ]) + result.stdout.fnmatch_lines( + [ + "django: version: *, settings: tpkg.settings_env (from env)", + "*= 1 passed*", + ] + ) def test_ds_option(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None: @@ -84,10 +88,12 @@ def test_ds(): """ ) result = pytester.runpytest_subprocess("--ds=tpkg.settings_opt") - result.stdout.fnmatch_lines([ - "django: version: *, settings: tpkg.settings_opt (from option)", - "*= 1 passed*", - ]) + result.stdout.fnmatch_lines( + [ + "django: version: *, settings: tpkg.settings_opt (from option)", + "*= 1 passed*", + ] + ) def test_ds_env_override_ini(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None: @@ -322,17 +328,19 @@ def test_debug_is_false(): assert r.ret == 0 -@pytest.mark.parametrize('django_debug_mode', [False, True]) +@pytest.mark.parametrize("django_debug_mode", [False, True]) def test_django_debug_mode_true_false( pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch, django_debug_mode: bool, ) -> None: monkeypatch.delenv("DJANGO_SETTINGS_MODULE") - pytester.makeini(f""" + pytester.makeini( + f""" [pytest] django_debug_mode = {django_debug_mode} - """) + """ + ) pytester.makeconftest( """ from django.conf import settings @@ -345,20 +353,23 @@ def pytest_configure(): 'NAME': ':memory:'}}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) - """ % (not django_debug_mode) + """ + % (not django_debug_mode) ) - pytester.makepyfile(f""" + pytester.makepyfile( + f""" from django.conf import settings def test_debug_is_false(): assert settings.DEBUG is {django_debug_mode} - """) + """ + ) r = pytester.runpytest_subprocess() assert r.ret == 0 -@pytest.mark.parametrize('settings_debug', [False, True]) +@pytest.mark.parametrize("settings_debug", [False, True]) def test_django_debug_mode_keep( pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch, @@ -383,7 +394,8 @@ def pytest_configure(): 'NAME': ':memory:'}}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) - """ % settings_debug + """ + % settings_debug ) pytester.makepyfile( diff --git a/tests/test_environment.py b/tests/test_environment.py index e68b99525..2dabb3a7f 100644 --- a/tests/test_environment.py +++ b/tests/test_environment.py @@ -290,9 +290,7 @@ def test_verbose_with_v(self, pytester: pytest.Pytester) -> None: """Verbose output with '-v'.""" result = pytester.runpytest_subprocess("-s", "-v") result.stdout.fnmatch_lines_random(["tpkg/test_the_test.py:*", "*PASSED*"]) - result.stderr.fnmatch_lines( - ["*Destroying test database for alias 'default'*"] - ) + result.stderr.fnmatch_lines(["*Destroying test database for alias 'default'*"]) def test_more_verbose_with_vv(self, pytester: pytest.Pytester) -> None: """More verbose output with '-v -v'.""" @@ -317,10 +315,7 @@ def test_more_verbose_with_vv_and_reusedb(self, pytester: pytest.Pytester) -> No result = pytester.runpytest_subprocess("-s", "-v", "-v", "--create-db") result.stdout.fnmatch_lines(["tpkg/test_the_test.py:*", "*PASSED*"]) result.stderr.fnmatch_lines(["*Creating test database for alias*"]) - assert ( - "*Destroying test database for alias 'default' ('*')...*" - not in result.stderr.str() - ) + assert "*Destroying test database for alias 'default' ('*')...*" not in result.stderr.str() @pytest.mark.django_db diff --git a/tests/test_fixtures.py b/tests/test_fixtures.py index 865eec557..b76d4cc2d 100644 --- a/tests/test_fixtures.py +++ b/tests/test_fixtures.py @@ -57,7 +57,7 @@ def test_admin_client_no_db_marker(admin_client: Client) -> None: # For test below. @pytest.fixture def existing_admin_user(django_user_model): - return django_user_model._default_manager.create_superuser('admin', None, None) + return django_user_model._default_manager.create_superuser("admin", None, None) def test_admin_client_existing_user( @@ -102,8 +102,7 @@ def test_django_assert_num_queries_db( with django_assert_num_queries(2) as captured: Item.objects.create(name="quux") assert excinfo.value.args == ( - "Expected to perform 2 queries but 1 was done " - "(add -v option to show queries)", + "Expected to perform 2 queries but 1 was done " "(add -v option to show queries)", ) assert len(captured.captured_queries) == 1 @@ -718,9 +717,7 @@ def test_unblock_with_block(self, django_db_blocker) -> None: def test_mail(mailoutbox) -> None: - assert ( - mailoutbox is mail.outbox - ) # check that mail.outbox and fixture value is same object + assert mailoutbox is mail.outbox # check that mail.outbox and fixture value is same object assert len(mailoutbox) == 0 mail.send_mail("subject", "body", "from@example.com", ["to@example.com"]) assert len(mailoutbox) == 1 @@ -794,7 +791,5 @@ def mocked_make_msgid(*args, **kwargs): """ ) result = django_pytester.runpytest_subprocess("--tb=short", "-vv", "-s") - result.stdout.fnmatch_lines( - ["*test_mailbox_inner*", "django_mail_dnsname_mark", "PASSED*"] - ) + result.stdout.fnmatch_lines(["*test_mailbox_inner*", "django_mail_dnsname_mark", "PASSED*"]) assert result.ret == 0 diff --git a/tests/test_manage_py_scan.py b/tests/test_manage_py_scan.py index 456757088..d2504eb47 100644 --- a/tests/test_manage_py_scan.py +++ b/tests/test_manage_py_scan.py @@ -123,9 +123,7 @@ def test_django_project_scan_disabled_invalid_settings( assert result.ret != 0 result.stderr.fnmatch_lines(["*ImportError*DOES_NOT_EXIST*"]) - result.stderr.fnmatch_lines( - ["*pytest-django did not search for " "Django projects*"] - ) + result.stderr.fnmatch_lines(["*pytest-django did not search for " "Django projects*"]) @pytest.mark.django_project(project_root="django_project_root", create_manage_py=True) diff --git a/tests/test_unittest.py b/tests/test_unittest.py index 521cb4fde..0fb4f7c9d 100644 --- a/tests/test_unittest.py +++ b/tests/test_unittest.py @@ -40,7 +40,7 @@ def tearDown(self) -> None: class TestFixturesWithSetup(TestCase): - fixtures = ("items", ) + fixtures = ("items",) def setUp(self) -> None: assert Item.objects.count() == 1 @@ -263,9 +263,7 @@ def test_bar(self): ) result = django_pytester.runpytest_subprocess("-v") - result.stdout.fnmatch_lines( - ["*TestFoo::test_foo PASSED*", "*TestBar::test_bar PASSED*"] - ) + result.stdout.fnmatch_lines(["*TestFoo::test_foo PASSED*", "*TestBar::test_bar PASSED*"]) assert result.ret == 0 def test_setUpClass_skip(self, django_pytester: DjangoPytester) -> None: @@ -435,9 +433,7 @@ def test_noop(self): ) result = django_pytester.runpytest_subprocess("-q", "-s") - result.stdout.fnmatch_lines( - ["*FooBarTestCase.setUpClass*", "*test_noop*", "1 passed*"] - ) + result.stdout.fnmatch_lines(["*FooBarTestCase.setUpClass*", "*test_noop*", "1 passed*"]) assert result.ret == 0 diff --git a/tox.ini b/tox.ini index e175d72fc..041fe08fe 100644 --- a/tox.ini +++ b/tox.ini @@ -56,6 +56,7 @@ deps = mypy==1.6.1 commands = ruff check --statistics {posargs:pytest_django pytest_django_test tests} + ruff format --quiet --diff {posargs:pytest_django pytest_django_test tests} mypy {posargs:pytest_django pytest_django_test tests} [testenv:doc8]