Skip to content

Commit

Permalink
Format code with Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
bluetech committed Oct 30, 2023
1 parent 8a499b2 commit 6939b23
Show file tree
Hide file tree
Showing 22 changed files with 214 additions and 215 deletions.
4 changes: 2 additions & 2 deletions pytest_django/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
__version__ = "unknown"


__all__ = (
__all__ = [
"__version__",
)
]
6 changes: 3 additions & 3 deletions pytest_django/asserts.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,15 @@ def assertRaisesMessage(
expected_exception: type[Exception],
expected_message: str,
*args,
**kwargs
**kwargs,
):
...

def assertWarnsMessage(
expected_warning: Warning,
expected_message: str,
*args,
**kwargs
**kwargs,
):
...

Expand Down Expand Up @@ -209,7 +209,7 @@ def assertNumQueries(
func=...,
*args,
using: str = ...,
**kwargs
**kwargs,
):
...

Expand Down
28 changes: 14 additions & 14 deletions pytest_django/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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
Expand All @@ -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}")
)


Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pytest_django/live_server_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
17 changes: 9 additions & 8 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,17 @@ 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",
default=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(
Expand All @@ -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(
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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():
Expand Down
1 change: 0 additions & 1 deletion pytest_django_test/app/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Migration(migrations.Migration):

initial = True

dependencies: tuple[tuple[str, str], ...] = ()
Expand Down
22 changes: 7 additions & 15 deletions pytest_django_test/db_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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")


Expand All @@ -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":
Expand All @@ -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)


Expand All @@ -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:
Expand All @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions pytest_django_test/db_router.py
Original file line number Diff line number Diff line change
@@ -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"
2 changes: 1 addition & 1 deletion pytest_django_test/settings_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@
}
]

DATABASE_ROUTERS = ['pytest_django_test.db_router.DbRouter']
DATABASE_ROUTERS = ["pytest_django_test.db_router.DbRouter"]

USE_TZ = True
2 changes: 1 addition & 1 deletion pytest_django_test/urls_overridden.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@


urlpatterns = [
path("overridden_url/", lambda r: HttpResponse("Overridden urlconf works!"))
path("overridden_url/", lambda r: HttpResponse("Overridden urlconf works!")),
]
20 changes: 9 additions & 11 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"])
Expand Down
23 changes: 13 additions & 10 deletions tests/test_asserts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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):
Expand Down

0 comments on commit 6939b23

Please sign in to comment.