Exemplo n.º 1
0
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for the urlutils library."""

__revision__ = "$Id$"

from invenio_base.wrappers import lazy_import
from invenio_testing import InvenioTestCase

WASH_HTML_ID = lazy_import('invenio_utils.washers:wash_html_id')


class TestWashUrlArgd(InvenioTestCase):
    # FIXME: test invenio_utils.washers.wash_urlargd
    pass


class TestWashHTMLId(InvenioTestCase):
    def test_clean_input(self):
        self.assert_(WASH_HTML_ID('abcd') == 'abcd')
        self.assert_(WASH_HTML_ID('a1b2') == 'a1b2')

    def test_dirty_input(self):
        self.assert_(WASH_HTML_ID('1234') == 'i1234')
        self.assert_(WASH_HTML_ID('1aaa') == 'i1aaa')
Exemplo n.º 2
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for WebMessage."""

__revision__ = \
    "$Id$"


from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
webmessage_mailutils = lazy_import('invenio.utils.mail')


class TestQuotingMessage(InvenioTestCase):
    """Test for quoting messages."""

    def test_simple_quoting_per_block(self):
        """webmessage - test quoting simple message (HTML, per block)"""
        text = """Dear romeo
I received your mail
>>Would you like to come with me to the restaurant?
Of course!
>>>>When could we get together?
Reply to my question please.
    see you..."""
        expected_text = """Dear romeo<br/>
Exemplo n.º 3
0
__revision__ = "$Id$"


try:
    import chardet
    CHARDET_AVAILABLE = True
except ImportError:
    CHARDET_AVAILABLE = False

from unidecode import unidecode

from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

decode_to_unicode = lazy_import('invenio_utils.text:decode_to_unicode')
escape_latex = lazy_import('invenio_utils.text:escape_latex')
guess_minimum_encoding = lazy_import('invenio_utils.text:guess_minimum_encoding')
show_diff = lazy_import('invenio_utils.text:show_diff')
strip_accents = lazy_import('invenio_utils.text:strip_accents')
translate_latex2unicode = lazy_import('invenio_utils.text:translate_latex2unicode')
translate_to_ascii = lazy_import('invenio_utils.text:translate_to_ascii')
transliterate_ala_lc = lazy_import('invenio_utils.text:transliterate_ala_lc')
wash_for_utf8 = lazy_import('invenio_utils.text:wash_for_utf8')
wash_for_xml = lazy_import('invenio_utils.text:wash_for_xml')
wrap_text_in_a_box = lazy_import('invenio_utils.text:wrap_text_in_a_box')


class GuessMinimumEncodingTest(InvenioTestCase):
    """Test functions related to guess_minimum_encoding function."""
    def test_guess_minimum_encoding(self):
Exemplo n.º 4
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

__revision__ = "$Id$"

from datetime import datetime

from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, nottest, \
    InvenioTestCase

CFG = lazy_import('invenio_base.globals.cfg')
USER = lazy_import('invenio.modules.accounts.models.User')
API = lazy_import('invenio_annotations.api')
NOTEUTILS = lazy_import('invenio_annotations.noteutils')
COMMENT = lazy_import('invenio_comments.models.CmtRECORDCOMMENT')


class AnnotationTestCase(InvenioTestCase):

    def setUp(self):
        self.app.config['ANNOTATIONS_ENGINE'] = \
            "invenio.modules.jsonalchemy.jsonext.engines.memory:MemoryStorage"


class TestAnnotation(AnnotationTestCase):
Exemplo n.º 5
0
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.

"""Matcher engines test helpers."""

from invenio_base.wrappers import lazy_import

from invenio_matcher.models import MatchResult


Record = lazy_import('invenio_records.api.Record')


no_query_config = {
    'MATCHER_QUERIES': {
        'es': {}
    }
}


single_query_config = {
    'MATCHER_QUERIES': {
        'es': {
            'records': {
                'record': [
                    {'type': 'exact', 'match': 'titles.title'}
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Test tags REST API."""

from __future__ import print_function, unicode_literals

from collections import OrderedDict
from datetime import datetime

from invenio_base.wrappers import lazy_import
from invenio.ext.restful import validation_errors
from invenio.ext.restful.utils import APITestCase
from invenio.testsuite import make_test_suite, run_test_suite


db = lazy_import('invenio.ext.sqlalchemy.db')


class TestTagsRestfulAPI(APITestCase):

    """Test REST API of tags."""

    @property
    def config(self):
        """Config."""
        cfg = super(TestTagsRestfulAPI, self).config
        cfg['PACKAGES'] = [
            'invenio_accounts',
            'invenio_groups',
            'invenio_oauth2server',
            'invenio_tags',
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Tests for featured community model."""

import datetime

from invenio_base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite
from invenio.ext.sqlalchemy import db

FeaturedCommunity = lazy_import('invenio_communities.models:'
                                'FeaturedCommunity')
Community = lazy_import('invenio_communities.models:Community')


class FeaturedCommunityModelTest(InvenioTestCase):

    test_name = "test_featured_comm"
    test_day = datetime.datetime(2010, 10, 10)

    def setUp(self):
        FeaturedCommunity.query.delete()

        withStartDate = {'id': 1,
                         'id_community': self.test_name,
                         'start_date': self.test_day}
        withoutStartDate = {'id': 2,
Exemplo n.º 8
0
from invenio_base.decorators import templated
from invenio_base.i18n import _
from invenio_base.wrappers import lazy_import
from invenio_ext.principal import permission_required
from invenio_ext.sqlalchemy import db
from invenio.utils import forms
from invenio_checker.api import create_task, delete_task, edit_task, run_task, create_reporter, edit_reporter, remove_reporter

from invenio_checker.acl import modifychecker, viewchecker
from ..recids import ids_from_input
from ..registry import plugin_files, reporters_files
from ..views.config import check_mapping, log_mapping, task_mapping
from invenio_checker.models import get_reporter_db
from sqlalchemy.orm.exc import NoResultFound

CheckerRule = lazy_import('invenio_checker.models.CheckerRule')
CheckerRuleExecution = \
    lazy_import('invenio_checker.models.CheckerRuleExecution')
CheckerReporter = lazy_import('invenio_checker.models.CheckerReporter')
default_date = lazy_import('invenio_checker.models._default_date')
ranges_str = lazy_import('invenio_checker.models.ranges_str')

blueprint = Blueprint(
    'invenio_checker_admin',
    __name__,
    url_prefix="/admin/checker",
    template_folder='../templates',
    static_folder='../static'
)

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for the access_control_firerole library."""

__revision__ = "$Id$"


from invenio_base.wrappers import lazy_import
from invenio_testing import InvenioTestCase

acc_firerole_check_user = lazy_import("invenio_access.firerole:acc_firerole_check_user")
compile_role_definition = lazy_import("invenio_access.firerole:compile_role_definition")
deserialize = lazy_import("invenio_access.firerole:deserialize")
serialize = lazy_import("invenio_access.firerole:serialize")


class AccessControlFireRoleTest(InvenioTestCase):
    """Test functions related to the firewall like role definitions."""

    def setUp(self):
        """setting up helper variables for tests"""
        from invenio_ext.login import UserInfo

        self.user_info = {
            "email": "*****@*****.**",
            "uid": 1000,
# License, or (at your option) any later version.
#
# Invenio 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

from invenio_base.wrappers import lazy_import

from invenio_testing import InvenioTestCase

calculate_start_date = lazy_import('invenio_comments.api:calculate_start_date')


class TestCalculateStartDate(InvenioTestCase):
    """Test for calculating previous date."""
    def test_previous_year(self):
        """webcomment - calculate_start_date, values bigger than one year"""
        self.assert_(int(calculate_start_date('1y')[:4]) > 2007)
        self.assert_(int(calculate_start_date('13m')[:4]) > 2007)
        self.assert_(int(calculate_start_date('55w')[:4]) > 2007)
        self.assert_(int(calculate_start_date('370d')[:4]) > 2007)

    def test_with_random_values(self):
        """webcomment - calculate_start_date, various random values"""
        self.assert_(calculate_start_date('1d') > '2009-07-08 14:39:39')
        self.assert_(calculate_start_date('2w') > '2009-07-08 14:39:39')
Exemplo n.º 11
0
from inspirehep.utils.arxiv import get_arxiv_id_from_record
from inspirehep.utils.datefilter import date_older_than
from inspirehep.utils.helpers import get_record_from_model, get_record_from_obj

from invenio_base.globals import cfg
from invenio_base.wrappers import lazy_import

from invenio_matcher.api import match as _match

import requests

import six


BibWorkflowObject = lazy_import("invenio_workflows.models.BibWorkflowObject")


def search(query):
    """Perform a search and returns the matching ids."""
    params = dict(p=query, of="id")

    try:
        return requests.get(cfg["WORKFLOWS_MATCH_REMOTE_SERVER_URL"], params=params).json()
    except requests.ConnectionError:
        current_app.logger.error("Error connecting to remote server:\n {0}".format(traceback.format_exc()))
        raise
    except ValueError:
        current_app.logger.error("Error decoding results from remote server:\n {0}".format(traceback.format_exc()))
        raise
from mock import PropertyMock, patch

from invenio_base.wrappers import lazy_import
from six import iteritems
from invenio.testsuite import InvenioTestCase, \
    make_test_suite, \
    run_test_suite
from invenio.ext.sqlalchemy import db
from flask_login import current_user

from invenio_communities.config import COMMUNITIES_ID_PREFIX, \
    COMMUNITIES_ID_PREFIX_PROVISIONAL, \
    COMMUNITIES_OUTPUTFORMAT, \
    COMMUNITIES_OUTPUTFORMAT_PROVISIONAL

Community = lazy_import('invenio_communities.models:Community')
Collection = lazy_import('invenio.modules.collections.models:Collection')
calculate_rank_for_community = lazy_import(
    'invenio_communities.tasks:calculate_rank_for_community')


class CommunityModelTest(InvenioTestCase):

    test_name = 'test_comm'

    def setUp(self):
        Community.query.delete()
        self.login('admin', '')
        uid = current_user.get_id()
        data = {'id': self.test_name,
                'title': self.test_name}
Exemplo n.º 13
0
# License, or (at your option) any later version.
#
# Invenio 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Unit tests for Access Mail Cookies."""

from invenio_base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite

Model_parser = lazy_import('invenio.modules.jsonalchemy.parser:ModelParser')

TEST_PACKAGE = 'invenio_access.testsuite'


class TestAccMailCookie(InvenioTestCase):
    """Test Mail cookie."""
    def setUp(self):
        """Set up."""
        pass

    def tearDown(self):
        """Tear down."""
        pass

    def test_mail_cookie(self):
Exemplo n.º 14
0
    EXIT_NOTESTSCOLLECTED,
)

from invenio_base.wrappers import lazy_import
from sqlalchemy.orm.exc import NoResultFound

from datetime import datetime
from flask_login import current_user
from invenio.ext.sqlalchemy import db  # pylint: disable=no-name-in-module,import-error
from croniter import croniter
from .redis_helpers import (
    get_lock_partial,
    get_redis_conn,
)

User = lazy_import('invenio_accounts.models.User')
CheckerRule = lazy_import('invenio_checker.models.CheckerRule')
CheckerRuleExecution = lazy_import(
    'invenio_checker.models.CheckerRuleExecution')

this_file_dir = os.path.dirname(os.path.realpath(__file__))
conftest_ini = os.path.join(this_file_dir, '..', 'conftest',
                            'conftest_checker.ini')


def _chunks(list_, size):
    """Yield successive `size`-sized chunks from `list_`."""
    list_ = list(list_)
    if size == 0:
        yield []
    else:
Exemplo n.º 15
0
from invenio_base.decorators import templated
from invenio_base.i18n import _
from invenio_base.wrappers import lazy_import
from invenio_ext.principal import permission_required
from invenio_ext.sqlalchemy import db
from invenio.utils import forms
from invenio_checker.api import create_task, delete_task, edit_task, run_task, create_reporter, edit_reporter, remove_reporter

from invenio_checker.acl import modifychecker, viewchecker
from ..recids import ids_from_input
from ..registry import plugin_files, reporters_files
from ..views.config import check_mapping, log_mapping, task_mapping
from invenio_checker.models import get_reporter_db
from sqlalchemy.orm.exc import NoResultFound

CheckerRule = lazy_import('invenio_checker.models.CheckerRule')
CheckerRuleExecution = \
    lazy_import('invenio_checker.models.CheckerRuleExecution')
CheckerReporter = lazy_import('invenio_checker.models.CheckerReporter')
default_date = lazy_import('invenio_checker.models._default_date')
ranges_str = lazy_import('invenio_checker.models.ranges_str')

blueprint = Blueprint('invenio_checker_admin',
                      __name__,
                      url_prefix="/admin/checker",
                      template_folder='../templates',
                      static_folder='../static')


def get_NewTaskForm(*args, **kwargs):
    class NewTaskForm(Form):
Exemplo n.º 16
0
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.

# from invenio_checker.clients.worker import (
#     RedisWorker,
#     get_lock_partial,
# )
import pytest
from copy import deepcopy
from mock import call, create_autospec
from frozendict import frozendict as fd
from invenio_base.wrappers import lazy_import
from intbitset import intbitset as ibs

get_record = lazy_import('invenio_checker.conftest.conftest_checker.get_record')
_pytest_sessionfinish = lazy_import('invenio_checker.conftest.conftest_checker._pytest_sessionfinish')
pytest_sessionstart = lazy_import('invenio_checker.conftest.conftest_checker.pytest_sessionstart')
_get_fullpatches_of_last_run = lazy_import('invenio_checker.conftest.conftest_checker._get_fullpatches_of_last_run')


class TestConftest(object):

    def test_sessionfinish_sends_patches_to_redis(self, mocker, m_conn):

        # Given some expected patches
        patch1 = {'task_id': 'abc', 'recid': 1, 'patch': '[{"path": "/recid", "value": 10, "op": "replace"}]'}
        patch2 = {'task_id': 'abc', 'recid': 2, 'patch': '[{"path": "/recid", "value": 20, "op": "replace"}]'}
        m_get_fullpatches_of_last_run = mocker.Mock(return_value=(patch1, patch2))
        mocker.patch('invenio_checker.conftest.conftest_checker._get_fullpatches_of_last_run', m_get_fullpatches_of_last_run)
Exemplo n.º 17
0
except ImportError:
    pass
from invenio.legacy.dbquery import run_sql
from invenio_utils.serializers import serialize_via_marshal


from invenio_base.i18n import gettext_set_language, wash_languages, wash_language
from invenio.ext.email import send_email
from invenio.ext.logging import register_exception
from invenio.ext.sqlalchemy import db
from invenio_accounts.models import User

from sqlalchemy.exc import OperationalError


acc_get_role_id = lazy_import('invenio_access.control:acc_get_role_id')
acc_get_action_roles = lazy_import('invenio_access.control:acc_get_action_roles')
acc_get_action_id = lazy_import('invenio_access.control:acc_get_action_id')
acc_is_user_in_role = lazy_import('invenio_access.control:acc_is_user_in_role')
acc_find_possible_activities = lazy_import('invenio_access.control:acc_find_possible_activities')
mail_cookie_create_mail_activation = lazy_import('invenio_access.mailcookie:mail_cookie_create_mail_activation')
acc_firerole_check_user = lazy_import('invenio_access.firerole:acc_firerole_check_user')
load_role_definition = lazy_import('invenio_access.firerole:load_role_definition')
from invenio_access.local_config import SUPERADMINROLE
CFG_EXTERNAL_AUTH_USING_SSO = lazy_import('invenio_access.local_config:CFG_EXTERNAL_AUTH_USING_SSO')
CFG_EXTERNAL_AUTHENTICATION = lazy_import('invenio_access.local_config:CFG_EXTERNAL_AUTHENTICATION')
CFG_WEBACCESS_MSGS = lazy_import('invenio_access.local_config:CFG_WEBACCESS_MSGS')
CFG_WEBACCESS_WARNING_MSGS = lazy_import('invenio_access.local_config:CFG_WEBACCESS_WARNING_MSGS')
CFG_EXTERNAL_AUTH_DEFAULT = lazy_import('invenio_access.local_config:CFG_EXTERNAL_AUTH_DEFAULT')
CFG_TEMP_EMAIL_ADDRESS = lazy_import('invenio_access.local_config:CFG_TEMP_EMAIL_ADDRESS')
Exemplo n.º 18
0
    EXIT_NOTESTSCOLLECTED,
)

from invenio_base.wrappers import lazy_import
from sqlalchemy.orm.exc import NoResultFound

from datetime import datetime
from flask_login import current_user
from invenio.ext.sqlalchemy import db  # pylint: disable=no-name-in-module,import-error
from croniter import croniter
from .redis_helpers import (
    get_lock_partial,
    get_redis_conn,
)

User = lazy_import('invenio_accounts.models.User')
CheckerRule = lazy_import('invenio_checker.models.CheckerRule')
CheckerRuleExecution = lazy_import('invenio_checker.models.CheckerRuleExecution')

this_file_dir = os.path.dirname(os.path.realpath(__file__))
conftest_ini = os.path.join(this_file_dir, '..', 'conftest', 'conftest_checker.ini')

def _chunks(list_, size):
    """Yield successive `size`-sized chunks from `list_`."""
    list_ = list(list_)
    if size == 0:
        yield []
    else:
        for i in xrange(0, len(list_), size):
            yield list_[i:i+size]
Exemplo n.º 19
0
# Invenio 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

__revision__ = "$Id$"

from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

EXTRACT_NOTES_FROM_COMMENT = \
    lazy_import(
        'invenio_annotations.noteutils:extract_notes_from_comment')
GET_NOTE_TITLE = \
    lazy_import('invenio_annotations.noteutils:get_note_title')
PREPARE_NOTES = \
    lazy_import('invenio_annotations.noteutils:prepare_notes')


class TestExtractNotes(InvenioTestCase):
    """Tests for comment note extraction"""

    def test_extract_notes_from_comment(self):
        """Tests note extraction from single comments"""
        fun = EXTRACT_NOTES_FROM_COMMENT

        # marker collection tests; no corners or invalids here, just
        # [MARKER.LOCATION(S): BODY]
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Test knowledge REST API."""

from __future__ import print_function

from invenio_base.wrappers import lazy_import
from invenio.ext.restful.utils import APITestCase
from invenio.ext.sqlalchemy.utils import session_manager
from invenio.testsuite import make_test_suite, run_test_suite

db = lazy_import("invenio.ext.sqlalchemy.db")


class TestKnowledgeRestfulAPI(APITestCase):

    """Test REST API of mappings."""

    @session_manager
    def setUp(self):
        """Run before each test."""
        from invenio_knowledge.models import KnwKB, KnwKBRVAL

        self.kb_a = KnwKB(name="example1", description="test description", kbtype="w")
        db.session.add(self.kb_a)

        # add kbrval
Exemplo n.º 21
0
import pytest
import sys
import os
from os.path import join as pjoin

from invenio_base.wrappers import lazy_import
from sqlalchemy.orm.exc import NoResultFound
from importlib import import_module

from invenio.testsuite import InvenioTestCase
from intbitset import intbitset  # pylint: disable=no-name-in-module
from mock import patch, MagicMock, Mock, PropertyMock
from invenio_celery import celery
from invenio.ext.sqlalchemy import db  # pylint: disable=no-name-in-module, import-error

CheckerRule = lazy_import('invenio_checker.models.CheckerRule')
CheckerRuleExecution = lazy_import('invenio_checker.models.CheckerRuleExecution')
CheckerReporter = lazy_import('invenio_checker.models.CheckerReporter')

conflict_check_count = 0
CLEANUP_AT_END = False
celery.conf['CELERY_ALWAYS_EAGER'] = True

# These ranges are used to pin-point recids to test with
_start = 5000000
small_rng = range(_start, _start + 4)
large_rng = range(_start, _start + 1000)

# Resolve the location demo check files for patching.
_current_dir = os.path.dirname(__file__)
_tests_dir = os.path.dirname(_current_dir)
Exemplo n.º 22
0
#
# Invenio 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for Access Mail Cookies."""

from invenio_base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite

Model_parser = lazy_import('invenio.modules.jsonalchemy.parser:ModelParser')

TEST_PACKAGE = 'invenio_access.testsuite'


class TestAccMailCookie(InvenioTestCase):

    """Test Mail cookie."""

    def setUp(self):
        """Set up."""
        pass

    def tearDown(self):
        """Tear down."""
        pass
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Test tags REST API."""

from __future__ import print_function, unicode_literals

from collections import OrderedDict
from datetime import datetime

from invenio_base.wrappers import lazy_import
from invenio_ext.restful import validation_errors
from invenio_ext.restful.utils import APITestCase

db = lazy_import('invenio_ext.sqlalchemy.db')


class TestTagsRestfulAPI(APITestCase):
    """Test REST API of tags."""
    @property
    def config(self):
        """Config."""
        cfg = super(TestTagsRestfulAPI, self).config
        cfg['PACKAGES'] = [
            'invenio_accounts',
            'invenio_groups',
            'invenio_oauth2server',
            'invenio_tags',
            'invenio_records',
            'invenio_search',
Exemplo n.º 24
0
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.A

"""Test invenio.base.scripts.config."""

import os
import sys
import mock
import tempfile

from flask import current_app
from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, InvenioTestCase

config = lazy_import("invenio.base.scripts.config")


class TestConfig(InvenioTestCase):

    """Testing the config command utility."""

    def setUp(self):
        """Set up default configuration file."""
        fp, self._tmp = tempfile.mkstemp(dir=current_app.instance_path,
                                         text=True)
        os.write(fp, """SECRET_KEY = "53Cr37 k3Y"
DEBUG = True
""")
        os.close(fp)
        self.cfg = os.path.basename(self._tmp)
Exemplo n.º 25
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for the access_control_firerole library."""

__revision__ = "$Id$"


from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

acc_firerole_check_user = lazy_import('invenio_access.firerole:acc_firerole_check_user')
compile_role_definition = lazy_import('invenio_access.firerole:compile_role_definition')
deserialize = lazy_import('invenio_access.firerole:deserialize')
serialize = lazy_import('invenio_access.firerole:serialize')


class AccessControlFireRoleTest(InvenioTestCase):
    """Test functions related to the firewall like role definitions."""

    def setUp(self):
        """setting up helper variables for tests"""
        from invenio_ext.login import UserInfo
        self.user_info = {'email' : '*****@*****.**', 'uid': 1000,
            'group' : ['patata', 'cetriolo'], 'remote_ip' : '127.0.0.1',
            'guest' : '0'}
        self.guest = UserInfo(None)
Exemplo n.º 26
0
from invenio_base.wrappers import lazy_import
import sys
import re
import traceback
from contextlib import contextmanager

import pytest
from _pytest.runner import pytest_runtest_makereport as orig_pytest_runtest_makereport
from _pytest.terminal import TerminalReporter
from six import StringIO

from .check_fixtures import *  # pylint: disable=wildcard-import
import jsonpatch
from functools import wraps, partial
Query = lazy_import('invenio_search.api.Query')
from invenio_checker.clients.worker import (
    RedisWorker,
    StatusWorker,
    make_fullpatch,
    get_workers_with_unprocessed_results,
    workers_are_compatible,
)
import eliot
from eliot import Message
import mock
from invenio_checker.config import get_eliot_log_file
from .check_helpers import LocationTuple
from _pytest.main import EXIT_OK
from intbitset import intbitset  # pylint: disable=no-name-in-module
Exemplo n.º 27
0
"""Invenio Matcher Elasticsearch engine."""

from flask import current_app

from invenio_base.wrappers import lazy_import

from invenio_matcher.errors import NoQueryDefined
from invenio_matcher.models import MatchResult

import six

from werkzeug.utils import import_string


ES = lazy_import('invenio_ext.es.es')
Record = lazy_import('invenio_records.api.Record')


def exact(index, doc_type, match, values, **kwargs):
    """Build an exact query and send it to Elasticsearch."""
    exact_query = _build_exact_query(match, values, **kwargs)
    result = ES.search(index=index, doc_type=doc_type, body=exact_query)
    hits = result['hits']['hits']

    return [MatchResult(Record(hit['_source']), hit['_score']) for hit in hits]


def fuzzy(index, doc_type, match, values, **kwargs):
    """Build a fuzzy query and send it to Elasticsearch."""
    fuzzy_query = _build_fuzzy_query(index, doc_type, match, values, **kwargs)
Exemplo n.º 28
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for the access_control_firerole library."""

__revision__ = "$Id$"


from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

acc_firerole_check_user = lazy_import('invenio_access.firerole:acc_firerole_check_user')
compile_role_definition = lazy_import('invenio_access.firerole:compile_role_definition')
deserialize = lazy_import('invenio_access.firerole:deserialize')
serialize = lazy_import('invenio_access.firerole:serialize')


class AccessControlFireRoleTest(InvenioTestCase):
    """Test functions related to the firewall like role definitions."""

    def setUp(self):
        """setting up helper variables for tests"""
        from invenio.ext.login import UserInfo
        self.user_info = {'email' : '*****@*****.**', 'uid': 1000,
            'group' : ['patata', 'cetriolo'], 'remote_ip' : '127.0.0.1',
            'guest' : '0'}
        self.guest = UserInfo(None)
Exemplo n.º 29
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for the urlutils library."""

__revision__ = "$Id$"

from cgi import parse_qs
from invenio_base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

HASHLIB_IMPORTED = lazy_import('invenio_utils.url:HASHLIB_IMPORTED')
create_AWS_request_url = lazy_import('invenio_utils.url:create_AWS_request_url')
create_Indico_request_url = lazy_import('invenio_utils.url:create_Indico_request_url')
create_html_link = lazy_import('invenio_utils.url:create_html_link')
create_html_mailto = lazy_import('invenio_utils.url:create_html_mailto')
create_url = lazy_import('invenio_utils.url:create_url')
get_relative_url = lazy_import('invenio_utils.url:get_relative_url')
make_canonical_urlargd = lazy_import('invenio_utils.url:make_canonical_urlargd')
rewrite_to_secure_url = lazy_import('invenio_utils.url:rewrite_to_secure_url')
same_urls_p = lazy_import('invenio_utils.url:same_urls_p')
string_to_numeric_char_reference = lazy_import('invenio_utils.url:string_to_numeric_char_reference')
wash_url_argument = lazy_import('invenio_utils.url:wash_url_argument')


class TestWashUrlArgument(InvenioTestCase):
    def test_wash_url_argument(self):
Exemplo n.º 30
0
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for pages."""

from flask import url_for

from invenio_base.wrappers import lazy_import

from invenio_ext.sqlalchemy import db

from invenio_testing import InvenioTestCase

Page = lazy_import('invenio_pages.models:Page')


class PagesTestViews(InvenioTestCase):

    """ Test pages functionality."""

    render_templates = False

    def setUp(self):
        Page.query.delete()
        self.test_page = Page()
        self.test_page.id = 1
        self.test_page.url = "pages/test"
        self.test_page.title = "My test title"
        self.test_page.template_name = 'pages/default.html'
Exemplo n.º 31
0
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Provide initialization and configuration for `flask_login` module."""

import urllib
from datetime import datetime

from flask import current_app, flash, g, redirect, request, session, url_for

from flask_login import LoginManager, current_user, \
    login_user as flask_login_user, logout_user, user_logged_in

from invenio_base.wrappers import lazy_import

UserInfo = lazy_import('invenio_ext.login.legacy_user:UserInfo')


def login_user(user, *args, **kwargs):
    """Allow login user by its id."""
    if type(user) in [int, long]:
        user = UserInfo(user)
    return flask_login_user(user, *args, **kwargs)


def login_redirect(referer=None):
    """Redirect to url after login."""
    if referer is None:
        referer = request.values.get('referer')
    if referer:
        from six.moves.urllib.parse import urlparse
Exemplo n.º 32
0
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

from invenio_base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite

calculate_start_date = lazy_import(
    'invenio_comments.api:calculate_start_date')


class TestCalculateStartDate(InvenioTestCase):

    """Test for calculating previous date."""

    def test_previous_year(self):
        """webcomment - calculate_start_date, values bigger than one year"""
        self.assert_(int(calculate_start_date('1y')[:4]) > 2007)
        self.assert_(int(calculate_start_date('13m')[:4]) > 2007)
        self.assert_(int(calculate_start_date('55w')[:4]) > 2007)
        self.assert_(int(calculate_start_date('370d')[:4]) > 2007)

    def test_with_random_values(self):
        """webcomment - calculate_start_date, various random values"""