Skip to content

Commit

Permalink
type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Feb 6, 2024
1 parent 4945d05 commit 178667e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
22 changes: 13 additions & 9 deletions codeforlife/tests/model_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

import typing as t
from unittest.case import _AssertRaisesContext

from django.db.models import Model
from django.forms.models import model_to_dict
Expand Down Expand Up @@ -59,23 +60,26 @@ def assert_raises_validation_error(self, code: str, *args, **kwargs):
The assert-raises context which will auto-assert the code.
"""

context = self.assertRaises(ValidationError, *args, **kwargs)

class ContextWrapper:
class Wrapper:
"""Wrap context to assert code on exit."""

def __init__(self, context):
self.context = context
def __init__(self, ctx: "_AssertRaisesContext[ValidationError]"):
self.ctx = ctx

def __enter__(self, *args, **kwargs):
return self.context.__enter__(*args, **kwargs)
return self.ctx.__enter__(*args, **kwargs)

def __exit__(self, *args, **kwargs):
value = self.context.__exit__(*args, **kwargs)
assert self.context.exception.detail[0].code == code
value = self.ctx.__exit__(*args, **kwargs)
assert (
code
== self.ctx.exception.detail[ # type: ignore[union-attr]
0 # type: ignore[index]
].code
)
return value

return ContextWrapper(context)
return Wrapper(self.assertRaises(ValidationError, *args, **kwargs))

# pylint: disable-next=too-many-arguments
def _assert_validate(
Expand Down
18 changes: 9 additions & 9 deletions codeforlife/user/tests/auth/password_validators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
Base test case for all password validators.
"""

from unittest.case import _AssertRaisesContext

from django.core.exceptions import ValidationError
from django.test import TestCase

Expand All @@ -22,20 +24,18 @@ def assert_raises_validation_error(self, code: str, *args, **kwargs):
The assert-raises context which will auto-assert the code.
"""

context = self.assertRaises(ValidationError, *args, **kwargs)

class ContextWrapper:
class Wrapper:
"""Wrap context to assert code on exit."""

def __init__(self, context):
self.context = context
def __init__(self, ctx: "_AssertRaisesContext[ValidationError]"):
self.ctx = ctx

def __enter__(self, *args, **kwargs):
return self.context.__enter__(*args, **kwargs)
return self.ctx.__enter__(*args, **kwargs)

def __exit__(self, *args, **kwargs):
value = self.context.__exit__(*args, **kwargs)
assert self.context.exception.code == code
value = self.ctx.__exit__(*args, **kwargs)
assert self.ctx.exception.code == code
return value

return ContextWrapper(context)
return Wrapper(self.assertRaises(ValidationError, *args, **kwargs))

0 comments on commit 178667e

Please sign in to comment.