<commit_before># -*- coding: utf-8 -*-

# Copyright (c) 2014 CoNWeT Lab., Universidad Politécnica de Madrid

# This file is part of CKAN Private Dataset Extension.

# CKAN Private Dataset Extension is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# CKAN Private Dataset Extension is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with CKAN Private Dataset Extension.  If not, see <http://www.gnu.org/licenses/>.

import unittest
import ckanext.privatedatasets.helpers as helpers

from mock import MagicMock
from parameterized import parameterized


class HelpersTest(unittest.TestCase):

    def setUp(self):
        # Create mocks
        self._model = helpers.model
        helpers.model = MagicMock()

        self._tk = helpers.tk
        helpers.tk = MagicMock()
        helpers.tk.config = {}

        self._db = helpers.db
        helpers.db = MagicMock()


        self._request = helpers.request
        helpers.request = MagicMock()

    def tearDown(self):
        helpers.model = self._model
        helpers.tk = self._tk
        helpers.db = self._db
        helpers.request = self._request

    @parameterized.expand([
        (False, 'user', False),
        (True,  'user', True),
        (False, None,   False),
        (True,  None,   False),
    ])
    def test_is_dataset_acquired(self, db_acquired, user, acquired):
        # Configure test
        helpers.tk.c.user = user
        pkg_dict = {'id': 'package_id'}

        db_response = []
        if db_acquired is True:
            out = helpers.db.AllowedUser()
            out.package_id = 'package_id'
            out.user_name = user
            db_response.append(out)

        helpers.db.AllowedUser.get = MagicMock(return_value=db_response)

        # Check the function returns the expected result
        self.assertEquals(acquired, helpers.is_dataset_acquired(pkg_dict))

        # Check that the database has been initialized properly
        helpers.db.init_db.assert_called_once_with(helpers.model)

    @parameterized.expand([
        (1, 1,    True),
        (1, 2,    False),
        (1, None, False)
    ])
    def test_is_owner(self, creator_user_id, user_id, owner):
        # Configure test
        if user_id:
            user = MagicMock()
            user.id = user_id
            helpers.tk.c.userobj = user
        else:
            helpers.tk.c.userobj = None

        pkg_dict = {'creator_user_id': creator_user_id}

        # Check that the functions return the expected result
        self.assertEquals(owner, helpers.is_owner(pkg_dict))

    @parameterized.expand([
        ([],                   ''),
        (['a'],                'a'),
        (['a', 'b'],           'a,b'),
        (['a', 'b', 'c', 'd'], 'a,b,c,d'),
    ])
    def test_get_allowed_users_str(self, allowed_users, expected_result):
        self.assertEquals(expected_result, helpers.get_allowed_users_str(allowed_users))

    @parameterized.expand([
        (False,),
        (True,)
    ])
    def test_can_read(self, auth):
        # Recover exception
        helpers.tk.NotAuthorized = self._tk.NotAuthorized

        def _check_access(function_name, context, data_dict):
            if not auth:
                raise helpers.tk.NotAuthorized()
            else:
                return True

        helpers.tk.check_access = MagicMock(side_effect=_check_access)

        # Call the function and check the result
        package = {'id': 1}
        self.assertEquals(auth, helpers.can_read(package))

        # Assert called with
        context = {'user': helpers.tk.c.user, 'userobj': helpers.tk.c.userobj, 'model': helpers.model}
        helpers.tk.check_access.assert_called_once_with('package_show', context, package)

    @parameterized.expand([
        (None,    False),
        ('True',  True),
        ('False', False)
    ])
    def test_show_acquire_url_on_create(self, config_value, expected_value):
        if config_value is not None:
            helpers.tk.config['ckan.privatedatasets.show_acquire_url_on_create'] = config_value

        # Call the function
        self.assertEquals(expected_value, helpers.show_acquire_url_on_create())

    @parameterized.expand([
        (None,    False),
        ('True',  True),
        ('False', False)
    ])
    def test_show_acquire_url_on_edit(self, config_value, expected_value):
        if config_value is not None:
            helpers.tk.config['ckan.privatedatasets.show_acquire_url_on_edit'] = config_value

        # Call the function
        self.assertEquals(expected_value, helpers.show_acquire_url_on_edit())

    @parameterized.expand([
        ({}, '/dataset', False),
        ({'acquire_url': 'http://fiware.org'}, '/dataset', True),
        ({'acquire_url': ''}, '/dataset', False),
        ({'acquire_url': 'http://fiware.org'}, '/user', False),
    ])
    def test_acquire_button(self, package, path, button_expected):

        # Mocking
        helpers.request.path = path

        # Call the function and check response
        result = helpers.acquire_button(package)
<commit_msg>Test evironment configuration<commit_after># -*- coding: utf-8 -*-

# Copyright (c) 2014 CoNWeT Lab., Universidad Politécnica de Madrid
# Copyright (c) 2018 Future Internet Consulting and Development Solutions S.L.

# This file is part of CKAN Private Dataset Extension.

# CKAN Private Dataset Extension is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# CKAN Private Dataset Extension is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with CKAN Private Dataset Extension.  If not, see <http://www.gnu.org/licenses/>.

import unittest
import ckanext.privatedatasets.helpers as helpers

from mock import patch, MagicMock
from parameterized import parameterized


class HelpersTest(unittest.TestCase):

    def setUp(self):
        # Create mocks
        self._model = helpers.model
        helpers.model = MagicMock()

        self._tk = helpers.tk
        helpers.tk = MagicMock()
        helpers.tk.config = {}

        self._db = helpers.db
        helpers.db = MagicMock()


        self._request = helpers.request
        helpers.request = MagicMock()

    def tearDown(self):
        helpers.model = self._model
        helpers.tk = self._tk
        helpers.db = self._db
        helpers.request = self._request

    @parameterized.expand([
        (False, 'user', False),
        (True,  'user', True),
        (False, None,   False),
        (True,  None,   False),
    ])
    def test_is_dataset_acquired(self, db_acquired, user, acquired):
        # Configure test
        helpers.tk.c.user = user
        pkg_dict = {'id': 'package_id'}

        db_response = []
        if db_acquired is True:
            out = helpers.db.AllowedUser()
            out.package_id = 'package_id'
            out.user_name = user
            db_response.append(out)

        helpers.db.AllowedUser.get = MagicMock(return_value=db_response)

        # Check the function returns the expected result
        self.assertEquals(acquired, helpers.is_dataset_acquired(pkg_dict))

        # Check that the database has been initialized properly
        helpers.db.init_db.assert_called_once_with(helpers.model)

    @parameterized.expand([
        (1, 1,    True),
        (1, 2,    False),
        (1, None, False)
    ])
    def test_is_owner(self, creator_user_id, user_id, owner):
        # Configure test
        if user_id:
            user = MagicMock()
            user.id = user_id
            helpers.tk.c.userobj = user
        else:
            helpers.tk.c.userobj = None

        pkg_dict = {'creator_user_id': creator_user_id}

        # Check that the functions return the expected result
        self.assertEquals(owner, helpers.is_owner(pkg_dict))

    @parameterized.expand([
        ([],                   ''),
        (['a'],                'a'),
        (['a', 'b'],           'a,b'),
        (['a', 'b', 'c', 'd'], 'a,b,c,d'),
    ])
    def test_get_allowed_users_str(self, allowed_users, expected_result):
        self.assertEquals(expected_result, helpers.get_allowed_users_str(allowed_users))

    @parameterized.expand([
        (False,),
        (True,)
    ])
    def test_can_read(self, auth):
        # Recover exception
        helpers.tk.NotAuthorized = self._tk.NotAuthorized

        def _check_access(function_name, context, data_dict):
            if not auth:
                raise helpers.tk.NotAuthorized()
            else:
                return True

        helpers.tk.check_access = MagicMock(side_effect=_check_access)

        # Call the function and check the result
        package = {'id': 1}
        self.assertEquals(auth, helpers.can_read(package))

        # Assert called with
        context = {'user': helpers.tk.c.user, 'userobj': helpers.tk.c.userobj, 'model': helpers.model}
        helpers.tk.check_access.assert_called_once_with('package_show', context, package)

    @parameterized.expand([
        (None,    False, None),
        ('True',  True,  None),
        ('False', False, None),
        ('afa  ', False, None),
        (True,    True,  None),
        (False,   False, None),
        (False,   True , 'true'),
        (False,   True , 'on'),
        (False,   True , '1'),
        (True,    False, '0'),
        (True,    False, 'off'),
        (True,    False, 'fAlsE'),
        (True,    False, 'fAlsE'),
    ])
    @patch("ckanext.privatedatasets.helpers.os.environ", new={})
    def test_show_acquire_url_on_create(self, config_value, expected_value, env_val):
        # {} is shared between tests, so we have clear it each time
        helpers.os.environ.clear()

        if config_value is not None:
            helpers.tk.config['ckan.privatedatasets.show_acquire_url_on_create'] = config_value

        if env_val:
            helpers.os.environ['CKAN_PRIVATEDATASETS_SHOW_ACQUIRE_URL_ON_CREATE'] = env_val

        # Call the function
        self.assertEquals(expected_value, helpers.show_acquire_url_on_create())

    @parameterized.expand([
        (None,    False, None),
        ('True',  True,  None),
        (' tRUe', True,  None),
        ('False', False, None),
        (True,    True,  None),
        (False,   False, None),
        (False,   True , 'trUe'),
        (False,   True , 'on'),
        (False,   True , '1'),
        (True,    False, '0'),
        (True,    False, 'off'),
        (True,    False, 'fAlsE'),
        (True,    False, 'potato'),
    ])
    @patch("ckanext.privatedatasets.helpers.os.environ", new={})
    def test_show_acquire_url_on_edit(self, config_value, expected_value, env_val):
        # {} is shared between tests, so we have clear it each time
        helpers.os.environ.clear()

        if config_value is not None:
            helpers.tk.config['ckan.privatedatasets.show_acquire_url_on_edit'] = config_value

        if env_val:
            helpers.os.environ['CKAN_PRIVATEDATASETS_SHOW_ACQUIRE_URL_ON_EDIT'] = env_val

        # Call the function
        self.assertEquals(expected_value, helpers.show_acquire_url_on_edit())

    @parameterized.expand([
        ({}, '/dataset', False),
        ({'acquire_url': 'http://fiware.org'}, '/dataset', True),
        ({'acquire_url': ''}, '/dataset', False),
        ({'acquire_url': 'http://fiware.org'}, '/user', False),
    ])
    def test_acquire_button(self, package, path, button_expected):

        # Mocking
        helpers.request.path = path

        # Call the function and check response
        result = helpers.acquire_button(package)

{'fraction_non_alphanumeric': 0.11126384733565133, 'fraction_numerical': 0.0025875313333872402, 'mean_word_length': 2.4384209063108147, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '924703', 'n_tokens_mistral': 3772, 'n_tokens_neox': 3672, 'n_words': 949}