Skip to content

Commit

Permalink
[#3607] Fix all tests after refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos committed Jan 5, 2024
1 parent bc1d1e0 commit 8d8d4b7
Show file tree
Hide file tree
Showing 13 changed files with 72 additions and 126 deletions.
6 changes: 1 addition & 5 deletions src/openforms/contrib/brk/tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,7 @@ class BRKValidatorIntegrationTestCase(
def setUp(self) -> None:
super().setUp()
register = Registry()
register(
"brk-zakelijk-gerechtigd",
verbose_name="dummy",
for_components=("addressNL",),
)(BRKZakelijkGerechtigdeValidator)
register("brk-zakelijk-gerechtigd")(BRKZakelijkGerechtigdeValidator)

patcher = patch("openforms.validations.api.views.register", new=register)
patcher.start()
Expand Down
12 changes: 6 additions & 6 deletions src/openforms/contrib/brk/tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class BRKValidatorTestCase(OFVCRMixin, BRKTestMixin, TestCase):
VCR_TEST_FILES = TEST_FILES

def test_brk_validator_no_auth(self):
validator = BRKZakelijkGerechtigdeValidator()
validator = BRKZakelijkGerechtigdeValidator("brk_validator")

submission_no_auth = SubmissionFactory.create(
form__generate_minimal_setup=True,
Expand All @@ -35,7 +35,7 @@ def test_brk_validator_no_auth(self):
)

def test_brk_validator_no_bsn(self):
validator = BRKZakelijkGerechtigdeValidator()
validator = BRKZakelijkGerechtigdeValidator("brk_validator")

submission_no_bsn = SubmissionFactory.create(
form__generate_minimal_setup=True,
Expand All @@ -52,7 +52,7 @@ def test_brk_validator_no_bsn(self):
)

def test_brk_validator_wrong_bsn(self):
validator = BRKZakelijkGerechtigdeValidator()
validator = BRKZakelijkGerechtigdeValidator("brk_validator")

submission_wrong_bsn = SubmissionFactory.create(
form__generate_minimal_setup=True,
Expand All @@ -73,7 +73,7 @@ def test_brk_validator_wrong_bsn(self):
)

def test_brk_validator_bsn(self):
validator = BRKZakelijkGerechtigdeValidator()
validator = BRKZakelijkGerechtigdeValidator("brk_validator")

submission_bsn = SubmissionFactory.create(
form__generate_minimal_setup=True,
Expand Down Expand Up @@ -112,7 +112,7 @@ def test_brk_validator_bsn(self):

@requests_mock.Mocker()
def test_brk_validator_requests_error(self, m: requests_mock.Mocker):
validator = BRKZakelijkGerechtigdeValidator()
validator = BRKZakelijkGerechtigdeValidator("brk_validator")

submission_bsn = SubmissionFactory.create(
form__generate_minimal_setup=True,
Expand Down Expand Up @@ -150,7 +150,7 @@ def setUp(self):
self.addCleanup(patcher.stop)

def test_brk_validator_not_configured(self):
validator = BRKZakelijkGerechtigdeValidator()
validator = BRKZakelijkGerechtigdeValidator("brk_validator")

submission_bsn = SubmissionFactory.create(
form__generate_minimal_setup=True,
Expand Down
6 changes: 3 additions & 3 deletions src/openforms/contrib/brk/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,12 @@ class ValueSerializer(serializers.Serializer):
value = AddressValueSerializer()


@register("brk-Zaakgerechtigde")
@register("brk-zakelijk-gerechtigd")
@deconstructible
class BRKZaakgerechtigdeValidator(BasePlugin[AddressValue]):
class BRKZakelijkGerechtigdeValidator(BasePlugin[AddressValue]):

value_serializer = ValueSerializer
verbose_name = _("BRK - Zaakgerechtigde")
verbose_name = _("BRK - Zakelijk gerechtigd")
for_components = ("addressNL",)

error_messages = {
Expand Down
8 changes: 4 additions & 4 deletions src/openforms/contrib/kvk/tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def test_kvkNumber_validator(self, m):
status_code=500,
)

validator = partial(KVKNumberRemoteValidator(), submission=Submission())
validator = partial(KVKNumberRemoteValidator("id"), submission=Submission())
validator("69599084")

with self.assertRaisesMessage(
Expand Down Expand Up @@ -96,7 +96,7 @@ def test_kvkNumber_validator_emptyish_results(self, m):
{"resultaten": []},
{},
)
validate = partial(KVKNumberRemoteValidator(), submission=Submission())
validate = partial(KVKNumberRemoteValidator("id"), submission=Submission())

for response_json in bad_responses:
with self.subTest(response_json=response_json):
Expand All @@ -120,7 +120,7 @@ def test_rsin_validator(self, m):
status_code=404,
)

validator = partial(KVKRSINRemoteValidator(), submission=Submission())
validator = partial(KVKRSINRemoteValidator("id"), submission=Submission())
validator("111222333")

with self.assertRaisesMessage(
Expand Down Expand Up @@ -151,7 +151,7 @@ def test_branchNumber_validator(self, m):
status_code=404,
)

validator = partial(KVKBranchNumberRemoteValidator(), submission=Submission())
validator = partial(KVKBranchNumberRemoteValidator(""), submission=Submission())
validator("112233445566")

with self.assertRaisesMessage(
Expand Down
8 changes: 4 additions & 4 deletions src/openforms/contrib/kvk/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ class KVKNumberRemoteValidator(BasePlugin[str], KVKRemoteBaseValidator):

def __call__(self, value: str, submission):
validate_kvk(value)
super().__call__(value)
KVKRemoteBaseValidator.__call__(self, value)


@register("kvk-rsin")
Expand All @@ -108,12 +108,12 @@ class KVKRSINRemoteValidator(BasePlugin[str], KVKRemoteBaseValidator):

def __call__(self, value: str, submission):
validate_rsin(value)
super().__call__(value)
KVKRemoteBaseValidator.__call__(self, value)


@register("kvk-branchNumber")
@deconstructible
class KVKBranchNumberRemoteValidator(KVKRemoteBaseValidator):
class KVKBranchNumberRemoteValidator(BasePlugin[str], KVKRemoteBaseValidator):
query_param = "vestigingsnummer"
value_label = _("Branch number")

Expand All @@ -122,4 +122,4 @@ class KVKBranchNumberRemoteValidator(KVKRemoteBaseValidator):

def __call__(self, value: str, submission):
validate_branchNumber(value)
super().__call__(value)
KVKRemoteBaseValidator.__call__(self, value)
2 changes: 1 addition & 1 deletion src/openforms/payments/tests/test_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def test_long_identifier(self):

with self.assertRaisesMessage(
ValueError,
f"The unique identifier '{long_identifier}' is longer then {UNIQUE_ID_MAX_LENGTH} characters.",
f"The unique identifier '{long_identifier}' is longer than {UNIQUE_ID_MAX_LENGTH} characters.",
):
register(long_identifier)(Plugin)

Expand Down
15 changes: 8 additions & 7 deletions src/openforms/validations/api/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Iterable

from django.utils.translation import gettext_lazy as _

from drf_spectacular.types import OpenApiTypes
Expand All @@ -21,7 +19,8 @@
ValidatorsFilterSerializer,
)

from ..registry import RegisteredValidator, register
from ..base import BasePlugin
from ..registry import register


@extend_schema_view(
Expand All @@ -39,16 +38,18 @@ class ValidatorsListView(ListMixin, APIView):
permission_classes = (permissions.IsAdminUser,)
serializer_class = ValidationPluginSerializer

def get_objects(self) -> list[RegisteredValidator]:
def get_objects(self) -> list[BasePlugin]:
filter_serializer = ValidatorsFilterSerializer(data=self.request.query_params)
if not filter_serializer.is_valid(raise_exception=False):
return []

plugins: Iterable[RegisteredValidator] = register.iter_enabled_plugins()
for_component = filter_serializer.validated_data.get("component_type") or ""
plugins = register.iter_enabled_plugins()
for_component: str = (
filter_serializer.validated_data.get("component_type") or ""
)

if not for_component:
return plugins
return list(plugins)
return [plugin for plugin in plugins if for_component in plugin.for_components]


Expand Down
9 changes: 7 additions & 2 deletions src/openforms/validations/base.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from abc import ABC, abstractmethod
from typing import ClassVar, Generic, TypeVar
from typing import ClassVar, Generic

from rest_framework import serializers
from typing_extensions import TypeVar

from openforms.plugins.plugin import AbstractBasePlugin
from openforms.submissions.models import Submission

T = TypeVar("T")
T = TypeVar("T", default=str)
"""A type variable representing the type of the value being validated by the plugin."""


Expand All @@ -17,6 +18,10 @@ class StringValueSerializer(serializers.Serializer):


class BasePlugin(ABC, AbstractBasePlugin, Generic[T]):
"""The base class for validation plugins.
This class is generic over the type of the validated value, defaulting to ``str``.
"""

value_serializer: ClassVar[type[serializers.BaseSerializer]] = StringValueSerializer
"""The serializer to be used to validate the value."""
Expand Down
13 changes: 6 additions & 7 deletions src/openforms/validations/registry.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
import dataclasses
import logging
from typing import Callable, Iterable, List, Type, TypeVar, Union
from typing import Iterable

from django.core.exceptions import ValidationError as DJ_ValidationError
from django.utils.translation import gettext_lazy as _

import elasticapm
from rest_framework import serializers
from rest_framework.exceptions import ValidationError as DRF_ValidationError
from typing_extensions import TypeVar

from openforms.plugins.registry import BaseRegistry
from openforms.submissions.models import Submission
from openforms.typing import JSONValue

from .base import BasePlugin

logger = logging.getLogger(__name__)

T = TypeVar("T", default=str)


@dataclasses.dataclass()
class ValidationResult:
is_valid: bool
messages: List[str] = dataclasses.field(default_factory=list)
messages: list[str] = dataclasses.field(default_factory=list)


def flatten(iterables: Iterable) -> List[str]:
def flatten(iterables: Iterable[str]) -> list[str]:
def _flat(it):
if isinstance(it, str):
yield it
Expand All @@ -38,9 +40,6 @@ def _flat(it):
return list(_flat(iterables))


T = TypeVar("T")


class Registry(BaseRegistry[BasePlugin[T]]):
"""
A registry for the validations module plugins.
Expand Down
35 changes: 5 additions & 30 deletions src/openforms/validations/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,9 @@
from openforms.config.models import GlobalConfiguration
from openforms.submissions.tests.factories import SubmissionFactory
from openforms.submissions.tests.mixins import SubmissionsMixin
from openforms.validations.registry import Registry, StringValueSerializer
from openforms.validations.tests.test_registry import (
DjangoValidator,
DRFValidator,
function_validator,
)
from openforms.validations.base import StringValueSerializer
from openforms.validations.registry import Registry
from openforms.validations.tests.test_registry import DjangoValidator, DRFValidator


class ValidationsAPITests(SubmissionsMixin, APITestCase):
Expand All @@ -23,20 +20,8 @@ def setUp(self):
self.client.force_login(self.user)

register = Registry()
register(
"django",
verbose_name="Django Test Validator",
for_components=("textfield",),
)(DjangoValidator)
register(
"drf", verbose_name="DRF Test Validator", for_components=("phoneNumber",)
)(DRFValidator)
register("func", verbose_name="Django function Validator", for_components=())(
function_validator
)
register(
"demo", verbose_name="Demo function", for_components=(), is_demo_plugin=True
)(function_validator)
register("django")(DjangoValidator)
register("drf")(DRFValidator)

patcher = patch("openforms.validations.api.views.register", new=register)
patcher.start()
Expand Down Expand Up @@ -71,11 +56,6 @@ def test_validations_list(self):
"label": "DRF Test Validator",
"for_components": ["phoneNumber"],
},
{
"id": "func",
"label": "Django function Validator",
"for_components": [],
},
],
)

Expand Down Expand Up @@ -132,11 +112,6 @@ def test_validations_list(self):
"label": "DRF Test Validator",
"for_components": ["phoneNumber"],
},
{
"id": "func",
"label": "Django function Validator",
"for_components": [],
},
],
)

Expand Down
Loading

0 comments on commit 8d8d4b7

Please sign in to comment.