def test_synchronize_all_external_groups(self):
     """webgroup - synchronizing all external groups"""
     synchronize_all_external_groups = lazy_import('invenio.legacy.websession.webgroup:synchronize_external_groups')
     get_external_groups = lazy_import('invenio.legacy.websession.dblayer:get_external_groups')
     get_all_login_method_groups = lazy_import('invenio.legacy.websession.dblayer:get_all_login_method_groups')
     synchronize_all_external_groups({'group1' : ('descr1', [self.email, self.email2])}, self.login_method)
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 1)
     synchronize_all_external_groups({'group2' : ('descr1', [self.email, self.email2])}, self.login_method)
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 1)
     self.assertEqual(groups[0][1], 'group2')
     self.assertEqual(groups[0][2], 'descr1')
     synchronize_all_external_groups({'group2' : ('descr2', [self.email])}, self.login_method)
     groups = get_external_groups(self.uid)
     self.assertEqual(groups[0][2], 'descr2')
     groups = get_external_groups(self.uid)
     self.assertEqual(len(groups), 1)
     self.assertEqual(groups[0][1], 'group2')
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 0)
     synchronize_all_external_groups({}, self.login_method)
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 0)
     groups = get_all_login_method_groups(self.login_method)
     self.failIf(groups)
 def test_synchronize_all_external_groups(self):
     """webgroup - synchronizing all external groups"""
     synchronize_all_external_groups = lazy_import(
         'invenio.legacy.websession.webgroup:synchronize_external_groups')
     get_external_groups = lazy_import(
         'invenio.legacy.websession.dblayer:get_external_groups')
     get_all_login_method_groups = lazy_import(
         'invenio.legacy.websession.dblayer:get_all_login_method_groups')
     synchronize_all_external_groups(
         {'group1': ('descr1', [self.email, self.email2])},
         self.login_method)
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 1)
     synchronize_all_external_groups(
         {'group2': ('descr1', [self.email, self.email2])},
         self.login_method)
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 1)
     self.assertEqual(groups[0][1], 'group2')
     self.assertEqual(groups[0][2], 'descr1')
     synchronize_all_external_groups({'group2': ('descr2', [self.email])},
                                     self.login_method)
     groups = get_external_groups(self.uid)
     self.assertEqual(groups[0][2], 'descr2')
     groups = get_external_groups(self.uid)
     self.assertEqual(len(groups), 1)
     self.assertEqual(groups[0][1], 'group2')
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 0)
     synchronize_all_external_groups({}, self.login_method)
     groups = get_external_groups(self.uid2)
     self.assertEqual(len(groups), 0)
     groups = get_all_login_method_groups(self.login_method)
     self.failIf(groups)
    def test_synchronize_external_groups(self):
        """webgroup - synchronizing one user external groups"""

        synchronize_external_groups = lazy_import('invenio.legacy.websession.webgroup:synchronize_external_groups')
        get_external_groups = lazy_import('invenio.legacy.websession.dblayer:get_external_groups')
        synchronize_external_groups(self.uid, {'group1' : 'descr1', 'group2' : 'descr2'}, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless('group1' in groups_names)
        self.failUnless('group2' in groups_names)
        synchronize_external_groups(self.uid, {'group1' : 'descr1', 'group2' : 'descr2'}, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless('group1' in groups_names)
        self.failUnless('group2' in groups_names)
        self.failUnless(len(groups_names) == 2)
        synchronize_external_groups(self.uid, {'group1' : 'descr1', 'group3' : 'descr2'}, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless('group1' in groups_names)
        self.failUnless('group3' in groups_names)
        self.failUnless(len(groups_names) == 2)
        synchronize_external_groups(self.uid, {}, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless(len(groups_names) == 0)
Exemple #4
0
 def test_kbd_retrieval_as_json(self):
     """bibknowledge - retrieve dynamic kb as json list"""
     get_kbd_values_json = lazy_import(
         'invenio.modules.knowledge.api:get_kbd_values_json')
     api_returns = get_kbd_values_json(self.dyn_kbname, 'Rodentia')
     expected = '["Charles Darwin"]'
     self.assertEqual(expected, api_returns)
Exemple #5
0
 def test_kb_for_bibedit(self):
     """bibknowledge - test a bibedit-style *very* dynamic kb"""
     get_kbd_values_for_bibedit = lazy_import(
         'invenio.modules.knowledge.api:get_kbd_values_for_bibedit')
     myvalues = get_kbd_values_for_bibedit("100__a",
                                           searchwith="Ellis",
                                           expression="100__a:*%*")
     self.assertEqual(1, len(myvalues))
    def test_your_alerts_pages_availability(self):
        """webalert - HTML to text conversion"""
        get_as_text = lazy_import('invenio.legacy.webalert.htmlparser:get_as_text')

        out = get_as_text(5)
        self.assertIn("High energy cosmic rays striking atoms at the top of the atmosphere give the rise to showers of particles striking the Earth's surface", out)
        self.assertIn("Des rayons cosmiques de haute energie heurtent des atomes dans la haute atmosphere et donnent ainsi naissance a des gerbes de particules projetees sur la surface terrestre", out)
        self.assertIn("CERN-DI-9905005", out)

        out = get_as_text(74)
        self.assertIn("Quasinormal modes of Reissner-Nordstrom Anti-de Sitter Black Holes", out)
        self.assertIn("hep-th/0003295", out)
        self.assertIn("Complex frequencies associated with quasinormal modes for large Reissner-Nordstr$\\ddot{o}$m Anti-de Sitter black holes have been computed.", out)
        self.assertIn("Phys. Lett., B :481 2000 79-88", out)
    def test_your_alerts_pages_availability(self):
        """webalert - HTML to text conversion"""
        get_as_text = lazy_import('invenio.legacy.webalert.htmlparser:get_as_text')

        out = get_as_text(5)
        self.assertIn("High energy cosmic rays striking atoms at the top of the atmosphere give the rise to showers of particles striking the Earth's surface", out)
        self.assertIn("Des rayons cosmiques de haute energie heurtent des atomes dans la haute atmosphere et donnent ainsi naissance a des gerbes de particules projetees sur la surface terrestre", out)
        self.assertIn("CERN-DI-9905005", out)

        out = get_as_text(74)
        self.assertIn("Quasinormal modes of Reissner-Nordstrom Anti-de Sitter Black Holes", out)
        self.assertIn("hep-th/0003295", out)
        self.assertIn("Complex frequencies associated with quasinormal modes for large Reissner-Nordstr$\\ddot{o}$m Anti-de Sitter black holes have been computed.", out)
        self.assertIn("Phys. Lett., B :481 2000 79-88", out)
    def test_synchronize_external_groups(self):
        """webgroup - synchronizing one user external groups"""

        synchronize_external_groups = lazy_import(
            'invenio.legacy.websession.webgroup:synchronize_external_groups')
        get_external_groups = lazy_import(
            'invenio.legacy.websession.dblayer:get_external_groups')
        synchronize_external_groups(self.uid, {
            'group1': 'descr1',
            'group2': 'descr2'
        }, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless('group1' in groups_names)
        self.failUnless('group2' in groups_names)
        synchronize_external_groups(self.uid, {
            'group1': 'descr1',
            'group2': 'descr2'
        }, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless('group1' in groups_names)
        self.failUnless('group2' in groups_names)
        self.failUnless(len(groups_names) == 2)
        synchronize_external_groups(self.uid, {
            'group1': 'descr1',
            'group3': 'descr2'
        }, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless('group1' in groups_names)
        self.failUnless('group3' in groups_names)
        self.failUnless(len(groups_names) == 2)
        synchronize_external_groups(self.uid, {}, self.login_method)
        groups = get_external_groups(self.uid)
        groups_names = [name[1] for name in groups]
        self.failUnless(len(groups_names) == 0)
Exemple #9
0
import random
import time
import glob
import re
import traceback
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound


from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import

from invenio.utils.shell import (run_shell_command,
                                 Timeout)
from invenio.utils.plotextractor.converter import untar

bibtask = lazy_import("invenio.legacy.bibsched.bibtask")
records_api = lazy_import("invenio.modules.records.api")
workflows_error = lazy_import("invenio.modules.workflows.errors")
plotextractor_getter = lazy_import("invenio.utils.plotextractor.getter")

REGEXP_REFS = re.compile("<record.*?>.*?<controlfield .*?>.*?</controlfield>(.*?)</record>", re.DOTALL)
REGEXP_AUTHLIST = re.compile("<collaborationauthorlist.*?</collaborationauthorlist>", re.DOTALL)


def add_metadata_to_extra_data(obj, eng):
    """
    Creates bibrecord from object data and
    populates extra_data with metadata
    :param obj: Bibworkflow Object to process
    :param eng: BibWorkflowEngine processing the object
    """
Exemple #10
0
except ImportError:
    pass
from invenio.legacy.dbquery import run_sql, OperationalError
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.legacy.websession.dblayer import get_groups
from invenio.modules.accounts.models import User

from invenio.legacy.websession.webuser_config import CFG_WEBUSER_USER_TABLES

acc_get_role_id = lazy_import('invenio.modules.access.control:acc_get_role_id')
acc_get_action_roles = lazy_import('invenio.modules.access.control:acc_get_action_roles')
acc_get_action_id = lazy_import('invenio.modules.access.control:acc_get_action_id')
acc_is_user_in_role = lazy_import('invenio.modules.access.control:acc_is_user_in_role')
acc_find_possible_activities = lazy_import('invenio.modules.access.control:acc_find_possible_activities')
mail_cookie_create_mail_activation = lazy_import('invenio.modules.access.mailcookie:mail_cookie_create_mail_activation')
acc_firerole_check_user = lazy_import('invenio.modules.access.firerole:acc_firerole_check_user')
load_role_definition = lazy_import('invenio.modules.access.firerole:load_role_definition')
SUPERADMINROLE = lazy_import('invenio.modules.access.local_config:SUPERADMINROLE')
CFG_EXTERNAL_AUTH_USING_SSO = lazy_import('invenio.modules.access.local_config:CFG_EXTERNAL_AUTH_USING_SSO')
CFG_EXTERNAL_AUTHENTICATION = lazy_import('invenio.modules.access.local_config:CFG_EXTERNAL_AUTHENTICATION')
CFG_WEBACCESS_MSGS = lazy_import('invenio.modules.access.local_config:CFG_WEBACCESS_MSGS')
CFG_WEBACCESS_WARNING_MSGS = lazy_import('invenio.modules.access.local_config:CFG_WEBACCESS_WARNING_MSGS')
CFG_EXTERNAL_AUTH_DEFAULT = lazy_import('invenio.modules.access.local_config:CFG_EXTERNAL_AUTH_DEFAULT')
CFG_TEMP_EMAIL_ADDRESS = lazy_import('invenio.modules.access.local_config:CFG_TEMP_EMAIL_ADDRESS')
Exemple #11
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.
"""BibAuthority Regression Test Suite."""

__revision__ = "$Id$"

from invenio.legacy.bibauthority.config import \
    CFG_BIBAUTHORITY_RECORD_CONTROL_NUMBER_FIELD, \
    CFG_BIBAUTHORITY_TYPE_NAMES, \
    CFG_BIBAUTHORITY_PREFIX_SEP

from invenio.testsuite import make_test_suite, run_test_suite, \
    InvenioTestCase
from invenio.base.wrappers import lazy_import
is_authority_record = lazy_import(
    'invenio.legacy.bibauthority.engine:is_authority_record')
get_dependent_records_for_control_no = lazy_import(
    'invenio.legacy.bibauthority.engine:get_dependent_records_for_control_no')
get_dependent_records_for_recID = lazy_import(
    'invenio.legacy.bibauthority.engine:get_dependent_records_for_recID')
guess_authority_types = lazy_import(
    'invenio.legacy.bibauthority.engine:guess_authority_types')
get_low_level_recIDs_from_control_no = lazy_import(
    'invenio.legacy.bibauthority.engine:get_low_level_recIDs_from_control_no')
get_control_nos_from_recID = lazy_import(
    'invenio.legacy.bibauthority.engine:get_control_nos_from_recID')
get_index_strings_by_control_no = lazy_import(
    'invenio.legacy.bibauthority.engine:get_index_strings_by_control_no')
guess_main_name_from_authority_recID = lazy_import(
    'invenio.legacy.bibauthority.engine:guess_main_name_from_authority_recID')
get_fieldvalues = lazy_import('invenio.legacy.bibrecord:get_fieldvalues')
__revision__ = "$Id$"

# pylint: disable=C0301

import os
import pkg_resources
import sys

from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
from invenio.ext.registry import ModuleAutoDiscoverySubRegistry
from flask.ext.registry import PkgResourcesDirDiscoveryRegistry, RegistryProxy, \
    ImportPathRegistry

bibformat = lazy_import('invenio.modules.formatter')
bibformat_engine = lazy_import('invenio.modules.formatter.engine')
bibformat_utils = lazy_import('invenio.modules.formatter.utils')
bibformat_config = lazy_import('invenio.modules.formatter.config')
bibformatadminlib = lazy_import('invenio.legacy.bibformat.adminlib')
format_templates = lazy_import('invenio.modules.formatter.testsuite.format_templates')
gettext_set_language = lazy_import('invenio.base.i18n:gettext_set_language')

TEST_PACKAGES = [
    'invenio.modules.formatter.testsuite.overlay',
    'invenio.modules.formatter.testsuite',
]


test_registry = RegistryProxy('test_registry', ImportPathRegistry,
                              initial=TEST_PACKAGES)
__revision__ = "$Id$"

import os
from logging import StreamHandler, DEBUG
from cStringIO import StringIO

#from invenio.ext.logging import register_exception
#from invenio.config import CFG_SITE_URL, CFG_PREFIX, CFG_TMPDIR, CFG_PATH_PDFTK
from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, \
                              test_web_page_content, merge_error_messages, \
                              InvenioTestCase
from invenio.base.factory import with_app_context

register_exception = lazy_import('invenio.ext.logging:register_exception')
websubmit_file_stamper = lazy_import('invenio.legacy.websubmit.file_stamper')

class WebSubmitWebPagesAvailabilityTest(InvenioTestCase):
    """Check WebSubmit web pages whether they are up or not."""

    def test_submission_pages_availability(self):
        """websubmit - availability of submission pages"""

        baseurl = cfg['CFG_SITE_URL'] + '/submit/'

        _exports = ['', 'direct']

        error_messages = []
        for url in [baseurl + page for page in _exports]:
            error_messages.extend(test_web_page_content(url))
## 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 add_orcid."""

import os

from mock import patch, Mock
from nose_parameterized import parameterized
from xml.dom.minidom import parse

from common import mock_open
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

add_publisher = lazy_import(
    'invenio.modules.checker.checkerext.checks.scoap3_add_publisher')


class TestChanges(InvenioTestCase):
    """Test if desired changes occured."""
    @parameterized.expand((
        ('known_publisher', 'Physics Letters B', 'Elsevier'),
        ('unknown_publisher', 'HURR DURR', None),
        ('emptystring', '', None),
    ))
    def test_resolving_of_publisher(self, _, journal, expected_publisher):
        _resolve_publisher = add_publisher._resolve_publisher
        publisher = _resolve_publisher(journal)
        self.assertEquals(publisher, expected_publisher)

    @parameterized.expand((
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""WebJournal Regression Test Suite."""

__revision__ = "$Id$"

import datetime
import urllib

from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, \
     test_web_page_content, merge_error_messages, InvenioTestCase

wju = lazy_import('invenio.legacy.webjournal.utils')


class ArticlesRelated(InvenioTestCase):
    """Functions about articles"""

    def test_is_new_article(self):
        """webjournal - checks if an article is new or not """
        article = wju.is_new_article('AtlantisTimes', '03/2009', 99)
        self.assertEqual(article, False)

        article = wju.is_new_article('AtlantisTimes', '03/2009', 103)
        self.assertEqual(article, True)


class CategoriesRelated(InvenioTestCase):
__revision__ = "$Id$"

# pylint: disable=C0301

import os
import pkg_resources
import sys

from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
from invenio.ext.registry import ModuleAutoDiscoverySubRegistry
from flask_registry import PkgResourcesDirDiscoveryRegistry, RegistryProxy, \
    ImportPathRegistry, ModuleAutoDiscoveryRegistry

bibformat = lazy_import('invenio.modules.formatter')
bibformat_engine = lazy_import('invenio.modules.formatter.engine')
bibformat_utils = lazy_import('invenio.modules.formatter.utils')
bibformat_config = lazy_import('invenio.modules.formatter.config')
bibformatadminlib = lazy_import('invenio.legacy.bibformat.adminlib')
format_templates = lazy_import(
    'invenio.modules.formatter.testsuite.format_templates')
gettext_set_language = lazy_import('invenio.base.i18n:gettext_set_language')

TEST_PACKAGES = [
    'invenio.modules.formatter.testsuite.overlay',
    'invenio.modules.formatter.testsuite',
]

test_registry = RegistryProxy('test_registry',
                              ImportPathRegistry,
"""
Unit tests for DataCite API wrapper

CFG_DATACITE_USERNAME and CFG_DATACITE_PASSWORD has to be set to be able to run
the tests.
"""

import string
import os
import random

from invenio.base.factory import with_app_context
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

dataciteutils = lazy_import('invenio.utils.datacite')


class DataCiteTestCase(InvenioTestCase):
    def setUp(self):
        # Force API in test mode
        self.d = dataciteutils.DataCite(test_mode=True)

    def tearDown(self):
        self.d = None

    def _random_doi(self):
        rand_string = ''.join(
            random.choice(string.lowercase + string.digits)
            for i in xrange(8)).upper()
        rand_string = "%s-%s" % (rand_string[0:4], rand_string[4:8])
Exemple #18
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.modules.annotations.noteutils:extract_notes_from_comment')
GET_NOTE_TITLE = \
    lazy_import('invenio.modules.annotations.noteutils:get_note_title')
PREPARE_NOTES = \
    lazy_import('invenio.modules.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]
# 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.
"""dbquery Regression Test Suite."""

__revision__ = "$Id$"

from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite

dbquery = lazy_import('invenio.legacy:dbquery')


class RunSqlReturnListOfDictionaries(InvenioTestCase):
    """Test run_sql behavior when with_dict parameter is provided"""
    def test_select_simple_columns_query(self):
        """dbquery - select simple columns query"""
        res = dbquery.run_sql(
            "SELECT id,name,dbquery FROM collection WHERE id<3",
            with_dict=True)
        self.assertEqual(res, ([{
            'dbquery': None,
            'id': 1,
            'name': cfg['CFG_SITE_NAME']
        }, {
            'dbquery': '980:"PREPRINT"',
Exemple #20
0
import os
import pkg_resources

from flask.ext.registry import (
    ImportPathRegistry, PkgResourcesDirDiscoveryRegistry, RegistryProxy
)

from invenio.base.wrappers import lazy_import
from invenio.ext.registry import ModuleAutoDiscoverySubRegistry
from invenio.testsuite import (
    InvenioTestCase, make_test_suite, nottest, run_test_suite
)

from mock import patch

Record = lazy_import('invenio.modules.records.api:Record')
Document = lazy_import('invenio.modules.documents.api:Document')

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

TEST_PACKAGE = 'invenio.modules.records.testsuite'

test_registry = RegistryProxy('testsuite', ImportPathRegistry,
                              initial=[TEST_PACKAGE])


def field_definitions():
    """Load field definitions."""
    return PkgResourcesDirDiscoveryRegistry(
        'fields', registry_namespace=test_registry)
Exemple #21
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 pages."""

from flask import url_for

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

Page = lazy_import('invenio.modules.pages.models:Page')


class PagesTestViews(InvenioTestCase):
    """ Test pages functionality."""
    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'
        self.test_page.content = "Testing pages"
        db.session.add(self.test_page)
        db.session.commit()
import os

from mock import patch, Mock
from nose_parameterized import parameterized
from xml.dom.minidom import parse

from common import mock_open
from invenio.base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase
from invenio.base.wrappers import lazy_import
import random
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase


common = lazy_import('invenio.modules.checker.checkerext.checks.common')

bibdoc_ids = {
    1: (11, 12, 13),
    2: (21, ),
    3: (),
}


def mock_glob(doc_id):
    directory_contents = {
        1: ['/opt/invenio/var/data/files/g5/1/a:5.xml',
            '/opt/invenio/var/data/files/g1/1/bc;32;sth.xml',
            '/opt/invenio/var/data/files/g1/1/kl;3.xml',
            '/opt/invenio/var/data/files/g1/1/foo bar;44.xml'],
Exemple #23
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.
"""WebMessage Regression Test Suite."""

__revision__ = "$Id$"

from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, \
                              test_web_page_content, merge_error_messages, \
                              InvenioTestCase
webmessage = lazy_import('invenio.legacy.webmessage.api')

CFG_WEBMESSAGE_STATUS_CODE = lazy_import(
    'invenio.modules.messages.query:CFG_WEBMESSAGE_STATUS_CODE')
check_quota = lazy_import('invenio.modules.messages.query:check_quota')
count_nb_messages = lazy_import(
    'invenio.modules.messages.query:count_nb_messages')
create_message = lazy_import('invenio.modules.messages.query:create_message')
datetext_default = lazy_import(
    'invenio.modules.messages.query:datetext_default')
delete_all_messages = lazy_import(
    'invenio.modules.messages.query:delete_all_messages')
delete_message_from_user_inbox = lazy_import(
    'invenio.modules.messages.query:delete_message_from_user_inbox')
get_all_messages_for_user = lazy_import(
    'invenio.modules.messages.query:get_all_messages_for_user')
Exemple #24
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.modules.annotations.noteutils:extract_notes_from_comment')
GET_NOTE_TITLE = \
    lazy_import('invenio.modules.annotations.noteutils:get_note_title')
PREPARE_NOTES = \
    lazy_import('invenio.modules.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]
import urllib2
import urlparse
import socket
from urllib import urlencode
from werkzeug.local import LocalProxy

from invenio.testsuite import make_test_suite, run_test_suite
from invenio.utils.json import json
from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.utils.shell import run_shell_command
from invenio.utils.url import make_user_agent_string

from invenio_demosite.testsuite.regression.test_bibupload import GenericBibUploadTest

run_sql = lazy_import('invenio.legacy.dbquery:run_sql')
get_last_taskid = lazy_import('invenio.legacy.bibsched.cli:get_last_taskid')
delete_task = lazy_import('invenio.legacy.bibsched.cli:delete_task')

CFG_HAS_CURL = os.path.exists("/usr/bin/curl")

# NOTE: default invenio.conf authorization are granted only to 127.0.0.1
# or 127.0.1.1, a.k.a. localhost, so the following checks if the current host
# is well recognized as localhost. Otherwise disable tests since they would
# fail due to not enough authorizations.

#FIXME
CFG_LOCALHOST_OK = LocalProxy(lambda: socket.gethostbyname(
    urlparse.urlparse(cfg['CFG_SITE_URL'])[1].split(':')[0]) in
                              ('127.0.0.1', '127.0.1.1'))
## 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)
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}
# 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 INSPIRE; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

import pkg_resources
import os

from dojson.contrib.marc21.utils import create_record

from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite
from inspirehep.dojson.hep import hep
from invenio.base.wrappers import lazy_import
Latex = lazy_import('inspirehep.utils.latex.Latex')


class LatexTests(InvenioTestCase):

    def setUp(self):
        self.marcxml = pkg_resources.resource_string('tests',
                                                     os.path.join(
                                                         'fixtures',
                                                         'test_hep_formats.xml')
                                                     )

        self.marcxml_publi_info = pkg_resources.resource_string('tests',
                                                                os.path.join(
                                                                    'fixtures',
                                                                    'test_hep_publi_info.xml')
## 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 arxiv_prefix."""

from nose_parameterized import parameterized, param

from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
from datetime import datetime

amend_publication_info = lazy_import('invenio.modules.checker.checkerext.checks.scoap3_amend_publication_info')


class TestChanges(InvenioTestCase):
    """Test if desired changes occured."""

    @parameterized.expand((
        # record, expected_year
        ('no_creation_date',  {},                                      None),
        ('yes_creation_date', {'creation_date': datetime(1995, 1, 4)}, 1995),
    ))
    def test_resolution_of_year_from_creation_date(self, _, record, expected_year):
        _resolve_year_from_creation_date = amend_publication_info._resolve_year_from_creation_date
        resolved_year = _resolve_year_from_creation_date(record)
        self.assertEquals(resolved_year, expected_year)
## 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 scoap3_arxiv_category."""

import os

from mock import patch
from nose_parameterized import parameterized

from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
from common import mock_open


arxiv_category = lazy_import("invenio.modules.checker.checkerext.plugins.scoap3_arxiv_category")


class TestChanges(InvenioTestCase):
    """Test if desired changes occured."""

    # def test_primary_report_number_is_correctly_changed(self):
    #     check_record = arxiv_category.check_record
    #     cases = (
    #         (Record({'primary_report_number': '12.34'}        , 'arXiv:12.34'),
    #         (Record({'primary_report_number': 'ab12.34 '}     , 'ab12.34 '),
    #         (Record({'primary_report_number': '012.55'}       , 'arXiv:012.55'),
    #         (Record({'primary_report_number': '12.341'}       , 'arXiv:12.341'),
    #         (Record({'primary_report_number': '12,34'})        , '12,34'),
    #         (Record({'primary_report_number': '12,.34'}       , '12,.34'),
    #         (Record({'primary_report_number': 'one 12.34 two'}, 'one 12.34 two'),
Exemple #31
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.
"""Test tags REST API."""

from __future__ import print_function
from collections import OrderedDict
from datetime import datetime
from dateutil.tz import tzutc
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite
from invenio.ext.restful.utils import APITestCase
from invenio.ext.restful import validation_errors

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


class TestTagsRestfulAPI(APITestCase):
    """Test REST API of tags."""
    def setUp(self):
        """Run before each test."""
        from invenio.modules.accounts.models import User

        self.user_a = User(email='*****@*****.**',
                           _password='******',
                           nickname='user_a')
        try:
            db.session.add(self.user_a)
            db.session.commit()
        except Exception:
# 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 indexing engine."""

__revision__ = \
    "$Id$"

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

bibindex_engine = lazy_import('invenio.legacy.bibindex.engine')
load_tokenizers = lazy_import(
    'invenio.legacy.bibindex.engine_utils.load_tokenizers')
list_union = lazy_import('invenio.legacy.bibindex.engine_utils.list_union')
get_values_recursively = lazy_import(
    'invenio.legacy.bibindex.engine_utils.get_values_recursively')


class TestListSetOperations(InvenioTestCase):
    """Tests for list set operations."""
    def test_list_union(self):
        """bibindex engine utils - list union"""
        self.assertEqual([1, 2, 3, 4], list_union([1, 2, 3], [1, 3, 4]))

    def test_list_unique(self):
        """bibindex engine - list unique"""
Exemple #33
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 INSPIRE; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

import pkg_resources
import os

from dojson.contrib.marc21.utils import create_record

from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite
from inspire.dojson.hep import hep
from invenio.base.wrappers import lazy_import
Export = lazy_import('inspire.utils.export.Export')


class ExportTests(InvenioTestCase):

    def setUp(self):
        self.marcxml = pkg_resources.resource_string('inspire.testsuite',
                                                     os.path.join(
                                                         'fixtures',
                                                         'test_hep_formats.xml')
                                                     )
        record = create_record(self.marcxml)

        self.hep_record = hep.do(record)

        self.export = Export(self.hep_record)
# 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 indexing engine."""

__revision__ = "$Id$"

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

bibindex_engine = lazy_import("invenio.legacy.bibindex.engine")
load_tokenizers = lazy_import("invenio.legacy.bibindex.engine_utils.load_tokenizers")
list_union = lazy_import("invenio.legacy.bibindex.engine_utils.list_union")
get_values_recursively = lazy_import("invenio.legacy.bibindex.engine_utils.get_values_recursively")


class TestListSetOperations(InvenioTestCase):
    """Tests for list set operations."""

    def test_list_union(self):
        """bibindex engine utils - list union"""
        self.assertEqual([1, 2, 3, 4], list_union([1, 2, 3], [1, 3, 4]))

    def test_list_unique(self):
        """bibindex engine - list unique"""
        self.assertEqual([1, 2, 3], bibindex_engine.list_unique([1, 2, 3, 3, 1, 2]))
Exemple #35
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 Acl JSONAlchemy extension."""

from invenio.base.wrappers import lazy_import
from flask.ext.registry import PkgResourcesDirDiscoveryRegistry, \
    ImportPathRegistry, RegistryProxy
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase

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

TEST_PACKAGE = 'invenio.modules.access.testsuite'

test_registry = RegistryProxy('testsuite', ImportPathRegistry,
                              initial=[TEST_PACKAGE])

model_definitions = lambda: PkgResourcesDirDiscoveryRegistry(
    'models', registry_namespace=test_registry)


class TestAclExtension(InvenioTestCase):

    @classmethod
    def setUpClass(cls):
        """Invalidate any previous field definition"""
# 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')
collect_user_info = lazy_import('invenio.legacy.webuser:collect_user_info')


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

    def setUp(self):
        """setting up helper variables for tests"""
        self.user_info = {'email' : '*****@*****.**', 'uid': 1000,
            'group' : ['patata', 'cetriolo'], 'remote_ip' : '127.0.0.1',
            'guest' : '0'}
        self.guest = collect_user_info(None)
Exemple #37
0
    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.legacy.websession.dblayer import get_groups
from invenio.modules.accounts.models import User

from invenio.legacy.websession.webuser_config import CFG_WEBUSER_USER_TABLES

from sqlalchemy.exc import OperationalError

acc_get_role_id = lazy_import('invenio.modules.access.control:acc_get_role_id')
acc_get_action_roles = lazy_import(
    'invenio.modules.access.control:acc_get_action_roles')
acc_get_action_id = lazy_import(
    'invenio.modules.access.control:acc_get_action_id')
acc_is_user_in_role = lazy_import(
    'invenio.modules.access.control:acc_is_user_in_role')
acc_find_possible_activities = lazy_import(
    'invenio.modules.access.control:acc_find_possible_activities')
mail_cookie_create_mail_activation = lazy_import(
    'invenio.modules.access.mailcookie:mail_cookie_create_mail_activation')
acc_firerole_check_user = lazy_import(
    'invenio.modules.access.firerole:acc_firerole_check_user')
load_role_definition = lazy_import(
    'invenio.modules.access.firerole:load_role_definition')
SUPERADMINROLE = lazy_import(
__revision__ = "$Id$"

import socket
import time
import cgi

from urlparse import urlparse, urlunparse
from urllib import urlopen, urlencode

from invenio.base.globals import cfg
from invenio.testsuite import make_test_suite, run_test_suite, \
                              test_web_page_content, merge_error_messages, \
                              get_authenticated_mechanize_browser, \
                              InvenioTestCase
from invenio.base.wrappers import lazy_import
run_sql = lazy_import('invenio.legacy.dbquery:run_sql')


class WebAccessWebPagesAvailabilityTest(InvenioTestCase):
    """Check WebAccess web pages whether they are up or not."""
    def test_webaccess_admin_interface_availability(self):
        """webaccess - availability of WebAccess Admin interface pages"""

        baseurl = cfg['CFG_SITE_URL'] + '/admin/webaccess/webaccessadmin.py/'

        _exports = [
            '', 'delegate_startarea', 'manageaccounts', 'rolearea',
            'actionarea', 'userarea', 'managerobotlogin', 'listgroups',
            'resetarea', ''
        ]
# 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,
Exemple #40
0
__revision__ = "$Id$"

# pylint: disable=C0301

import pkg_resources
import sys

from invenio.base.config import PACKAGES
from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
from flask_registry import PkgResourcesDirDiscoveryRegistry, RegistryProxy, \
    ImportPathRegistry, ModuleAutoDiscoveryRegistry

bibformat = lazy_import('invenio.modules.formatter')
bibformat_engine = lazy_import('invenio.modules.formatter.engine')
bibformat_utils = lazy_import('invenio.modules.formatter.utils')
bibformat_config = lazy_import('invenio.modules.formatter.config')
gettext_set_language = lazy_import('invenio.base.i18n:gettext_set_language')

TEST_PACKAGES = [
    'invenio.modules.formatter.testsuite.overlay',
    'invenio.modules.formatter.testsuite',
]

test_registry = RegistryProxy('test_registry',
                              ImportPathRegistry,
                              initial=TEST_PACKAGES)

output_formats_directories_registry = lambda: ModuleAutoDiscoveryRegistry(
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""
The Refextract unit test suite

The tests will not modifiy the database.
"""


import re

from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
# Import the minimal necessary methods and variables needed to run Refextract
refextract_re = lazy_import('invenio.legacy.refextract.regexs')
setup_loggers = lazy_import('invenio.legacy.docextract.utils:setup_loggers')
search_from_reference = lazy_import('invenio.legacy.refextract.api:search_from_reference')


class ReTest(InvenioTestCase):
    def setUp(self):
        setup_loggers(verbosity=1)

    def test_word(self):
        r = refextract_re._create_regex_pattern_add_optional_spaces_to_word_characters('ABC')
        self.assertEqual(r, ur'A\s*B\s*C\s*')

    def test_reference_section_title_pattern(self):
        r = refextract_re.get_reference_section_title_patterns()
        self.assert_(len(r) > 2)
#
# 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)

    def tearDown(self):
## 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 arxiv_prefix."""

from nose_parameterized import parameterized, param

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

find_erratum = lazy_import('invenio.modules.checker.checkerext.plugins.scoap3_find_erratum')


class TestChanges(InvenioTestCase):
    """Test if desired changes occured."""

    @parameterized.expand((
        ('space_sep' , 'this is erratum for'    , {'ERRATUM'})     ,
        ('nothing'   , 'this is nothing'        , set())           ,
        ('colon_sep' , 'corrigendum: something' , {'CORRIGENDUM'}) ,
        ('two'       , 'corrigendum: erratum'   , {'CORRIGENDUM'   , 'ERRATUM'}) ,
    ))
    def test_finding_of_collections_in_title(self, _, title, expected_collections):
        _collections_in_title = find_erratum._collections_in_title
        collections_found = _collections_in_title(title)
        self.assertEquals(collections_found, expected_collections)
Exemple #44
0
"""BibDocFile Regression Test Suite."""

__revision__ = "$Id$"

import os
import pkg_resources
import shutil
import time
from datetime import datetime
from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite

from invenio.utils.mimetype import CFG_HAS_MAGIC

CFG_WEBACCESS_WARNING_MSGS = lazy_import(
    'invenio.modules.access.local_config:CFG_WEBACCESS_WARNING_MSGS')
MoreInfo = lazy_import('invenio.legacy.bibdocfile.api:MoreInfo')
Md5Folder = lazy_import('invenio.legacy.bibdocfile.api:Md5Folder')
guess_format_from_url = lazy_import(
    'invenio.legacy.bibdocfile.api:guess_format_from_url')


class BibDocFsInfoTest(InvenioTestCase):
    """Regression tests about the table bibdocfsinfo"""
    def setUp(self):
        from invenio.legacy.bibdocfile.api import BibRecDocs
        self.my_bibrecdoc = BibRecDocs(2)
        self.unique_name = self.my_bibrecdoc.propose_unique_docname('file')
        self.my_bibdoc = self.my_bibrecdoc.add_new_file(
            pkg_resources.resource_filename(
                'invenio_demosite.testsuite.regression', 'data/test.jpg'),
__revision__ = "$Id$"

import socket
import time
import cgi

from urlparse import urlparse, urlunparse
from urllib import urlopen, urlencode

from invenio.base.globals import cfg
from invenio.testsuite import make_test_suite, run_test_suite, \
                              test_web_page_content, merge_error_messages, \
                              get_authenticated_mechanize_browser, \
                              InvenioTestCase
from invenio.base.wrappers import lazy_import
run_sql = lazy_import('invenio.legacy.dbquery:run_sql')


class WebAccessWebPagesAvailabilityTest(InvenioTestCase):
    """Check WebAccess web pages whether they are up or not."""

    def test_webaccess_admin_interface_availability(self):
        """webaccess - availability of WebAccess Admin interface pages"""

        baseurl = cfg['CFG_SITE_URL'] + '/admin/webaccess/webaccessadmin.py/'

        _exports = ['', 'delegate_startarea', 'manageaccounts', 'rolearea',
                    'actionarea', 'userarea', 'managerobotlogin', 'listgroups',
                    'resetarea', '']

        error_messages = []
Exemple #46
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.

from invenio.base.wrappers import lazy_import
from invenio.testsuite import InvenioXmlTestCase
from invenio.testsuite import make_test_suite, run_test_suite

BibRecord = lazy_import('invenio.legacy.docextract.record:BibRecord')
BibRecordControlField = lazy_import('invenio.legacy.docextract.record:'
                                    'BibRecordControlField')
BibRecordField = lazy_import('invenio.legacy.docextract.record:BibRecordField')
BibRecordSubField = lazy_import('invenio.legacy.docextract.record:'
                                'BibRecordSubField')
create_record = lazy_import('invenio.legacy.docextract.record:create_record')


class BibRecordTest(InvenioXmlTestCase):
    def setUp(self):
        self.xml = """<record>
            <datafield tag="100" ind1=" " ind2=" ">
                <subfield code="a">our title</subfield>
            </datafield>
        </record>"""
# 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"""
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

import os

from dojson.contrib.marc21.utils import create_record

from inspirehep.dojson.hep import hep

from invenio.base.wrappers import lazy_import

from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite

import pkg_resources


Cv_latex_html_text = lazy_import('inspirehep.utils.cv_latex_html_text.Cv_latex_html_text')


class CvLatexHtmlTextTests(InvenioTestCase):

    def setUp(self):
        self.marcxml = pkg_resources.resource_string('tests',
                                                     os.path.join(
                                                         'fixtures',
                                                         'test_hep_formats.xml')
                                                     )
        self.marcxml_publi_info = pkg_resources.resource_string('tests',
                                                                os.path.join(
                                                                    'fixtures',
                                                                    'test_hep_publi_info.xml')
                                                                )
## 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 nose_parameterized import parameterized

from invenio.base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase

from common import is_exception_of

nations = lazy_import('invenio.modules.checker.checkerext.plugins.scoap3_nations')



class TestChanges(InvenioTestCase):
    """Test if desired changes occured."""

    @parameterized.expand((
        # test_name         , unstructured_affiliations                         , expected_countries
        ('one_affiliation'                 , [u'Institute of Nuclear Physics, Cracow, Poland']  , set(('Poland',))),
        ('multiple_affiliations'           , [u'National University of Singapore',
                                              u'The Marian Smoluchowski Institute of Physics, Jagiellonian University, Łojasiewicza 11, 30-348 Kraków, Poland',
                                              u'School of Physics and Material Science, Anhui University, 230039, Hefei, Anhui, People’s Republic of China']
                                                                                                , set(('Singapore', 'Poland', 'China'))),
        ('newline_and_dot_in_data'         , [u'National University of\nSingapore.']            , set(('Singapore',))),
        ('no_affiliation'                  , []                                                 , KeyError),
Exemple #50
0
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.


"""BibClassify Regression Test Suite. This modules IS NOT standalone safe"""

import sys
import os
from warnings import warn

from invenio.bibclassify_unit_tests import BibClassifyTestCase
from invenio.config import CFG_SITE_URL
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, \
    test_web_page_content

bconfig = lazy_import('invenio.legacy.bibclassify.config')
bibclassify_cli = lazy_import('invenio.legacy.bibclassify.cli')
bibclassify_engine = lazy_import('invenio.legacy.bibclassify.engine')
bibclassify_ontology_reader = lazy_import('invenio.legacy.bibclassify.ontology_reader')


class BibClassifyRegressionTest(BibClassifyTestCase):
    """Check BibClassify web pages whether they are up or not."""

    def test_availability_bibclassify_admin_guide(self):
        """bibclassify - availability of BibClassify Admin Guide page"""
        self.assertEqual([], test_web_page_content(CFG_SITE_URL +
            '/help/admin/bibclassify-admin-guide',
            expected_text="BibClassify Admin Guide"))
        return
Exemple #51
0
__revision__ = "$Id$"

import time
from datetime import datetime, timedelta
import re

from cStringIO import StringIO

from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from intbitset import intbitset
from invenio.testsuite import make_test_suite, run_test_suite, \
                              test_web_page_content, merge_error_messages, \
                              InvenioTestCase

oai_repository_server = lazy_import('invenio.legacy.oairepository.server')
search_engine = lazy_import('invenio.legacy.search_engine')
run_sql = lazy_import('invenio.legacy.dbquery:run_sql')


class OAIRepositoryTouchSetTest(InvenioTestCase):
    """Check OAI-PMH consistency when touching a set."""
    def setUp(self):
        """Backup the current configuration"""
        self.timestamps = run_sql("SELECT id, last_updated FROM oaiREPOSITORY")

    def tearDown(self):
        """Restore timestamps"""
        for id, last_updated in self.timestamps:
            run_sql("UPDATE oaiREPOSITORY SET last_updated=%s WHERE id=%s",
                    (last_updated, id))
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Unit tests for add_orcid."""

import os

from mock import patch, Mock
from nose_parameterized import parameterized
from xml.dom.minidom import parse

from common import mock_open
from invenio.base.wrappers import lazy_import
from invenio.testsuite import InvenioTestCase


add_orcid = lazy_import('invenio.modules.checker.checkerext.checks.scoap3_add_orcid')


class TestChanges(InvenioTestCase):
    """Test if desired changes occured."""

    @parameterized.expand((
        # test_name           , xml_basename               , expected_orcids , expceted_exception
        ('ce_author'          , 'orcid_ce:author'          , ["", "ORCID:0000-0001-6037-7975", ""]),
        ('contrib'            , 'orcid_contrib'            , ["ORCID:0000-0003-2078-3535", "ORCID:0000-0001-5604-2531", "ORCID:0000-0003-1281-7977", "ORCID:0000-0001-6322-1386", "ORCID:0000-0003-3606-0104"]),
        ('ce_author_no_orcid' , 'orcid_ce:author_no_orcid' , ["", "", ""]),
    ))
    def test_getting_of_orcids_from_xml_document(self, _, xml_basename, expected_orcids):
        _get_orcids = add_orcid._get_orcids
        with mock_open(xml_basename, 'r') as xml_file:  # TODO: Rename to xml_open
            xml_data = parse(xml_file)
Exemple #53
0
## 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 search engine."""

__revision__ = \
    "$Id: search_engine_tests.py,v 1.20 2008/08/11 12:49:27 kaplun Exp $"


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

QueryResult = lazy_import('invenio.legacy.bibexport.fieldexporter_dblayer:QueryResult')


def _create_record_marc_xml():
    """Creates MARC XML containing one record"""
    xml_text="""
    <record>
      <datafield tag="260" ind1=" " ind2=" ">
        <subfield code="c">14 Dec 1998</subfield>
      </datafield>
      <datafield tag="260" ind1="A" ind2="B">
        <subfield code="c">14 Dec 1999</subfield>
      </datafield>
      <datafield tag="300" ind1=" " ind2=" ">
        <subfield code="a">6 p</subfield>
      </datafield>
Exemple #54
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.modules.annotations.api')
NOTEUTILS = lazy_import('invenio.modules.annotations.noteutils')
COMMENT = lazy_import('invenio.modules.comments.models.CmtRECORDCOMMENT')


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


class TestAnnotation(AnnotationTestCase):
    def test_initialization(self):
        u = USER(id=1)
# 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.
"""Testing functions for the page getter module.
"""

import sys

from StringIO import StringIO

from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
HTTPAsyncPageGetter = lazy_import(
    'invenio.legacy.websearch_external_collections.getter:HTTPAsyncPageGetter')
async_download = lazy_import(
    'invenio.legacy.websearch_external_collections.getter:async_download')


class AsyncDownloadTest(InvenioTestCase):
    """Test suite for websearch_external_collections_*"""
    def setUp(self):
        # We redirect stderr because the test for an invalid logs
        # a warning on stderr and xunit does not like it.
        # This only happens with python2.6.
        self.old_stderr = sys.stderr
        sys.stderr = StringIO()

    def tearDown(self):
        sys.stderr = self.old_stderr
Exemple #56
0
from invenio.base.wrappers import lazy_import
from flask import url_for, current_app
from six import iteritems
from invenio.testsuite import InvenioTestCase, \
    make_test_suite, \
    run_test_suite
from invenio.ext.sqlalchemy import db
from flask.ext.login import current_user

from invenio.modules.communities.config import COMMUNITIES_ID_PREFIX, \
    COMMUNITIES_ID_PREFIX_PROVISIONAL, \
    COMMUNITIES_OUTPUTFORMAT, \
    COMMUNITIES_OUTPUTFORMAT_PROVISIONAL

Community = lazy_import('invenio.modules.communities.models:Community')
Collection = lazy_import('invenio.modules.search.models:Collection')
calculate_rank_for_community = lazy_import('invenio.modules.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}
        self.c = Community(id_user=uid, **data)
        db.session.add(self.c)
Exemple #57
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.
"""WebTag Regression Tests"""

from invenio.base.globals import cfg
from invenio.base.wrappers import lazy_import
from invenio.ext.sqlalchemy import db
from invenio.testsuite import \
    InvenioTestCase, \
    make_test_suite, \
    run_test_suite
from mechanize import Browser

models = lazy_import('invenio.modules.tags.models')


class WebTagDeletionTest(InvenioTestCase):
    """Check if deleting w WtgTAG clears all associations"""
    def test_record_association_deletion(self):
        """webtag - are WtgTAGRecord rows deleted when WtgTAG is deleted?"""

        # (1) Create a new tag
        new_tag = models.WtgTAG()
        new_tag.id_user = 1
        new_tag.name = 'test record association deletion'
        db.session.add(new_tag)
        db.session.commit()
        db.session.refresh(new_tag)
Exemple #58
0
# General imports.
from cPickle import dumps, loads
from datetime import datetime, timedelta
from random import random
from sqlalchemy import bindparam
from sqlalchemy.orm import validates, column_property, undefer

from invenio.base.wrappers import lazy_import
from invenio.ext.sqlalchemy import db
from invenio.ext.sqlalchemy.utils import session_manager
from invenio.utils.hash import md5

from .errors import (
    InvenioWebAccessMailCookieError, InvenioWebAccessMailCookieDeletedError)

SUPERADMINROLE = lazy_import(
    'invenio.modules.access.local_config.SUPERADMINROLE')
CFG_ACC_ACTIVITIES_URLS = lazy_import(
    'invenio.modules.access.local_config.CFG_ACC_ACTIVITIES_URLS')

# Create your models here.

from invenio.modules.accounts.models import User


class AccACTION(db.Model):

    """Represent an access action."""

    __tablename__ = 'accACTION'
    id = db.Column(db.Integer(15, unsigned=True),
                   primary_key=True, autoincrement=True)
Exemple #59
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.modules.annotations.api')
NOTEUTILS = lazy_import('invenio.modules.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):