<commit_before># -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
#          you to buy us beer if we meet and you like the software.

from amivapi.tests import util

from jsonschema import Draft4Validator


class GroupPermissionTest(util.WebTest):
    def test_validator_schema(self):
        """
        Test to verify that the validator correctly aborts
        if the jsonschema is not valid
        """

        # Will raise an exception if the schema is broken
        Draft4Validator.check_schema(
            self.app.config['GROUP_PERMISSIONS_JSONSCHEMA']
        )

    def test_validator_input(self):
        """
        Test to verify that inputs are validated correctly
        """
        token = self.new_session(user_id=0).token  # root login

        def _gen():
            i = 0
            while True:
                i += 1
                yield i

        gen = _gen()

        # Helper function to post group
        def p_post(permissions, status):
            self.api.post("/groups", data={
                "name": "Testgroup%i" % gen.next(),
                "permissions": permissions,
                "moderator_id": 0,
                "allow_self_enrollment": False,
                "has_zoidberg_share": False
            }, token=token, status_code=status)

        # Empty is ok
        p_post({}, 201)
        # None is ok
        p_post(None, 201)
        # resources with no methods ok
        p_post({"users": {}}, 201)
        # More resources
        p_post({
            "users": {
                "POST": True,
                "DELETE": False},
            "events": {
                "GET": True}
        }, 201)

        # Wrong resource
        p_post({
            "users": {},
            "Idontexist": {}
        }, 422)

        # Wrong method
        p_post({
            "users": {
               "POST": True,
               "SUPERWRONG": False}
        }, 422)

        # All possible eve endpoints
        all = {}
        methods = ["GET", "PATCH", "PUT", "POST", "DELETE"]

        for endpoint in self.app.config["DOMAIN"]:
            all[endpoint] = {
                method: True for method in methods
            }

        p_post(all, 201)

    def check_group_permission(self, user_id, resource, method):
        """
        This function checks wether the user is permitted to access
        the given resource with the given method based on the groups
        he is in.

        :param user_id: the id of the user to check
        :param resource: the requested resource
        :param method: the used method

        :returns: Boolean, True if permitted, False otherwise
        """
        from amivapi.models import Group, GroupUserMember

        query = self.db.query(Group).filter(
            Group.user_subscribers.any(GroupUserMember.user_id == user_id))

        # All entries are dictionaries
        # If any dicitionary contains the permission it is good.
        for row in query:
            if row.permissions.get(resource, {}).get(method, False):
                return True

        return False

    def test_permissions(self):
        # Create 3 groups
        g1 = self.new_group(permissions={"events": {"POST": True}}).id<commit_msg>Cleanups in test_group_permissions<commit_after># -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
#          you to buy us beer if we meet and you like the software.

from amivapi.tests import util

from jsonschema import Draft4Validator


class GroupPermissionTest(util.WebTest):
    def test_validator_schema(self):
        """
        Test to verify that the validator correctly aborts
        if the jsonschema is not valid
        """

        # Will raise an exception if the schema is broken
        Draft4Validator.check_schema(
            self.app.config['GROUP_PERMISSIONS_JSONSCHEMA']
        )

    def test_validator_input(self):
        """
        Test to verify that inputs are validated correctly
        """
        token = self.new_session(user_id=0).token  # root login

        def _gen():
            i = 0
            while True:
                i += 1
                yield i

        gen = _gen()

        # Helper function to post group
        def p_post(permissions, status):
            self.api.post("/groups", data={
                "name": "Testgroup%i" % gen.next(),
                "permissions": permissions,
                "moderator_id": 0,
                "allow_self_enrollment": False,
                "has_zoidberg_share": False
            }, token=token, status_code=status)

        # Empty is ok
        p_post({}, 201)
        # None is ok
        p_post(None, 201)
        # resources with no methods ok
        p_post({"users": {}}, 201)
        # More resources
        p_post({
            "users": {
                "POST": True,
                "DELETE": False},
            "events": {
                "GET": True}
        }, 201)

        # Wrong resource
        p_post({
            "users": {},
            "Idontexist": {}
        }, 422)

        # Wrong method
        p_post({
            "users": {
               "POST": True,
               "SUPERWRONG": False}
        }, 422)

        # All possible eve endpoints
        all = {}
        methods = ["GET", "PATCH", "PUT", "POST", "DELETE"]

        for endpoint in self.app.config["DOMAIN"]:
            all[endpoint] = {
                method: True for method in methods
            }

        p_post(all, 201)

    def test_permissions(self):
        # Create 3 groups
        g1 = self.new_group(permissions={"events": {"POST": True}}).id
{'fraction_non_alphanumeric': 0.09952523298751538, 'fraction_numerical': 0.010902057323720767, 'mean_word_length': 1.6382189239332097, 'pattern_counts': {'":': 36, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '961311', 'n_tokens_mistral': 1630, 'n_tokens_neox': 1517, 'n_words': 470}