Skip to content
test_checks.py 43.7 KiB
Newer Older
Dong Zhuang's avatar
Dong Zhuang committed
__copyright__ = "Copyright (C) 2017 Dong Zhuang"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import os
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
Dong Zhuang's avatar
Dong Zhuang committed
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils.translation import gettext_lazy as _

from relate.checks import register_startup_checks_extra
from tests.factories import UserFactory
Andreas Klöckner's avatar
Andreas Klöckner committed
from tests.utils import mock
Dong Zhuang's avatar
Dong Zhuang committed


class CheckRelateSettingsBase(SimpleTestCase):
    @property
    def func(self):
        from relate.checks import check_relate_settings
Dong Zhuang's avatar
Dong Zhuang committed
        return check_relate_settings

    @property
    def msg_id_prefix(self):
        raise NotImplementedError()

    def assertCheckMessages(self,  # noqa
                            expected_ids=None, expected_msgs=None, length=None,
                            filter_message_id_prefixes=None, ignore_order=False):
        """
        Check the run check result of the setting item of the testcase instance
        :param expected_ids: Optional, list of expected message id,
        default to None
        :param expected_msgs: Optional, list of expected message string,
        default to None
        :param length: Optional, length of expected check message,
        default to None
        :param filter_message_id_prefixes: a list or tuple of message id prefix,
        to restrict the
         run check result to be within the iterable.
        """
        if not filter_message_id_prefixes:
            filter_message_id_prefixes = self.msg_id_prefix
            if isinstance(filter_message_id_prefixes, str):
                filter_message_id_prefixes = [filter_message_id_prefixes]
            assert isinstance(filter_message_id_prefixes, (list, tuple))

        if expected_ids is None and expected_msgs is None and length is None:
            raise RuntimeError("At least one parameter should be specified "
                               "to make the assertion")

        result = self.func(None)

        def is_id_in_filter(id, filter):
            prefix = id.split(".")[0]
            return prefix in filter

        try:
            result_ids, result_msgs = (
                list(zip(*[(r.id, r.msg) for r in result
                      if is_id_in_filter(r.id, filter_message_id_prefixes)])))

            if expected_ids is not None:
                assert isinstance(expected_ids, (list, tuple))
                if ignore_order:
                    result_ids = tuple(sorted(result_ids))
                    expected_ids = sorted(expected_ids)
                self.assertEqual(result_ids, tuple(expected_ids))

            if expected_msgs is not None:
                assert isinstance(expected_msgs, (list, tuple))
                if ignore_order:
                    result_msgs = tuple(sorted(result_msgs))
                    expected_msgs = sorted(expected_msgs)
                self.assertEqual(result_msgs, tuple(expected_msgs))

            if length is not None:
                self.assertEqual(len(expected_ids), len(result_ids))
        except ValueError as e:
            if "values to unpack" in str(e):
                if expected_ids or expected_msgs or length:
                    self.fail("Check message unexpectedly found to be empty")
            else:
                raise

Dong Zhuang's avatar
Dong Zhuang committed

class CheckRelateURL(CheckRelateSettingsBase):
    msg_id_prefix = "relate_base_url"

Dong Zhuang's avatar
Dong Zhuang committed
    VALID_CONF = "example.com"
    INVALID_CONF_NONE = None
    INVALID_CONF_EMPTY_LIST = []
    INVALID_CONF_SPACES = "  "

    @override_settings(RELATE_BASE_URL=VALID_CONF)
    def test_valid_relate_base_url1(self):
        self.assertCheckMessages([])
Dong Zhuang's avatar
Dong Zhuang committed

    @override_settings(RELATE_BASE_URL=INVALID_CONF_NONE)
    def test_invalid_relate_base_url_none(self):
        self.assertCheckMessages(["relate_base_url.E001"])
Dong Zhuang's avatar
Dong Zhuang committed

    @override_settings(RELATE_BASE_URL=INVALID_CONF_EMPTY_LIST)
    def test_invalid_relate_base_url_empty_list(self):
        self.assertCheckMessages(["relate_base_url.E002"])
Dong Zhuang's avatar
Dong Zhuang committed

    @override_settings(RELATE_BASE_URL=INVALID_CONF_SPACES)
    def test_invalid_relate_base_url_spaces(self):
        self.assertCheckMessages(["relate_base_url.E003"])
class CheckRelateUserProfileMaskMethod(CheckRelateSettingsBase):
    # This TestCase is not pure for check, but also make sure it returned
    # expected result
    databases = "__all__"

    msg_id_prefix = "relate_user_profile_mask_method"

    def setUp(self):
        super().setUp()
        self.user = UserFactory.create(first_name="my_first", last_name="my_last")

        from accounts.utils import relate_user_method_settings
        relate_user_method_settings.__dict__ = {}

    def test_get_masked_profile_not_configured(self):
        with override_settings():
            del settings.RELATE_USER_PROFILE_MASK_METHOD
            self.assertCheckMessages([])

            # make sure it runs without issue
            self.assertIsNotNone(self.user.get_masked_profile())

    def test_get_masked_profile_valid_none(self):
        with override_settings(RELATE_USER_PROFILE_MASK_METHOD=None):
            self.assertCheckMessages([])

            # make sure it runs without issue
            self.assertIsNotNone(self.user.get_masked_profile())

    def test_get_masked_profile_valid_method1(self):
        def custom_method(u):
            return "{}{}".format("User", str(u.pk + 1))

        with override_settings(RELATE_USER_PROFILE_MASK_METHOD=custom_method):
            self.assertCheckMessages([])
            self.assertEqual(self.user.get_masked_profile(),
                             custom_method(self.user))

    def test_get_masked_profile_valid_method2(self):
        def custom_method(user=None):
            if user is not None:
                return "{}{}".format("User", str(user.pk + 1))
            else:
                return ""

        with override_settings(RELATE_USER_PROFILE_MASK_METHOD=custom_method):
            self.assertCheckMessages([])
            self.assertEqual(self.user.get_masked_profile(),
                             custom_method(self.user))

    def test_get_masked_profile_valid_method_path(self):
        with override_settings(
                RELATE_USER_PROFILE_MASK_METHOD=(
                        "tests.resource"
                        ".my_custom_get_masked_profile_method_valid")):
            self.assertCheckMessages([])
            from tests.resource import (
Andreas Klöckner's avatar
Andreas Klöckner committed
                my_custom_get_masked_profile_method_valid as custom_method,
            )
            self.assertEqual(self.user.get_masked_profile(),
                             custom_method(self.user))

    def test_get_masked_profile_param_invalid1(self):
        # the method has 0 args/kwargs
        def custom_method():
            return "profile"

        with override_settings(RELATE_USER_PROFILE_MASK_METHOD=custom_method):
            self.assertCheckMessages(["relate_user_profile_mask_method.E003"])
Loading
Loading full blame...