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 5dc9c12 commit 2faa6ec
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 91 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
2 changes: 1 addition & 1 deletion src/openforms/contrib/kvk/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def __call__(self, value: str, submission):

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

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
3 changes: 2 additions & 1 deletion src/openforms/validations/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
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.base import StringValueSerializer
from openforms.validations.registry import Registry
from openforms.validations.tests.test_registry import (
DjangoValidator,
DRFValidator,
Expand Down
74 changes: 21 additions & 53 deletions src/openforms/validations/tests/test_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,86 +5,61 @@
from rest_framework.exceptions import ValidationError as DRFValidationError

from openforms.submissions.models import Submission
from openforms.validations.registry import Registry, StringValueSerializer
from openforms.validations.base import BasePlugin
from openforms.validations.registry import Registry


class DjangoValidator:
is_enabled = True
components = ("textfield",)
value_serializer = StringValueSerializer
class DjangoValidator(BasePlugin):
for_components = ("textfield",)

def __call__(self, value, submission):
if value != "VALID":
raise DjangoValidationError("not VALID value")


class DRFValidator:
is_enabled = True
components = ("phoneNumber",)
value_serializer = StringValueSerializer
class DRFValidator(BasePlugin):
for_components = ("phoneNumber",)

def __call__(self, value, submission):
if value != "VALID":
raise DRFValidationError("not VALID value")


class DisabledValidator:
is_enabled = False
components = ("textfield",)
value_serializer = StringValueSerializer
class DisabledValidator(BasePlugin):
for_components = ("textfield",)

def __call__(self, value, submission):
if value != "VALID":
raise DRFValidationError("not VALID value")


def function_validator(value, submission):
if value != "VALID":
raise DjangoValidationError("not VALID value")


function_validator.value_serializer = StringValueSerializer
@property
def is_enabled(self) -> bool:
return False


class RegistryTest(TestCase):
def test_register_function(self):
register = Registry()
register("plugin", "Plugin")(DjangoValidator)
register("plugin")(DjangoValidator)
plugin = register["plugin"]
self.assertNotIsInstance(plugin, DjangoValidator)
self.assertIsInstance(plugin.callable, DjangoValidator)
self.assertIsInstance(plugin, DjangoValidator)

def test_duplicate_identifier(self):
register = Registry()
register("plugin", "Plugin")(DjangoValidator)
register("plugin")(DjangoValidator)

with self.assertRaisesMessage(
ValueError,
"The unique identifier 'plugin' is already present in the registry",
"The unique identifier 'plugin' is already present in the registry.",
):
register("plugin", "Plugin")(DjangoValidator)

def test_decorator(self):
registry = Registry()

def decorated(value, submission):
pass

decorated.value_serializer = StringValueSerializer
registry("func", verbose_name="Function")(decorated)

wrapped = list(registry)[0]
self.assertEqual(wrapped.identifier, "func")
self.assertEqual(wrapped.verbose_name, "Function")
self.assertEqual(wrapped.callable, decorated)
register("plugin")(DjangoValidator)

def test_validate(self):
registry = Registry()
registry("django", "Django")(DjangoValidator)
registry("drf", "DRF")(DRFValidator)
registry("func", "Function")(function_validator)
registry("django")(DjangoValidator)
registry("drf")(DRFValidator)

# The submission object is not relevant for these validators, we use a dummy string instead
# The submission object is not relevant for these validators, we use a dummy object instead
res = registry.validate("django", "VALID", Submission())
self.assertEqual(res.is_valid, True)
self.assertEqual(res.messages, [])
Expand All @@ -99,13 +74,6 @@ def test_validate(self):
self.assertEqual(res.is_valid, False)
self.assertEqual(res.messages, ["not VALID value"])

res = registry.validate("func", "VALID", Submission())
self.assertEqual(res.is_valid, True)
self.assertEqual(res.messages, [])
res = registry.validate("func", "INVALID", Submission())
self.assertEqual(res.is_valid, False)
self.assertEqual(res.messages, ["not VALID value"])

res = registry.validate("NOT_REGISTERED", "VALID", Submission())
self.assertEqual(res.is_valid, False)
self.assertEqual(
Expand All @@ -119,10 +87,10 @@ def test_validate(self):

def test_validate_plugin_not_enabled(self):
registry = Registry()
registry("disabled", "Disabled")(DisabledValidator())
registry("disabled")(DisabledValidator)

res = registry.validate("disabled", "VALID", Submission())
self.assertEqual(res.is_valid, False)
self.assertFalse(res.is_valid)
self.assertEqual(
res.messages,
[_("plugin '{plugin_id}' not enabled").format(plugin_id="disabled")],
Expand Down
Loading

0 comments on commit 2faa6ec

Please sign in to comment.