How to use the invenio.testsuite.InvenioTestCase function in invenio

To help you get started, we’ve selected a few invenio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github inveniosoftware / invenio / invenio / modules / textminer / testsuite / test_textminer_references.py View on Github external
def setUp(self):
        setup_loggers(verbosity=1)

    def test_identify_ibids_empty(self):
        from invenio.legacy.refextract.tag import identify_ibids
        r = identify_ibids("")
        self.assertEqual(r, ({}, ''))

    def test_identify_ibids_simple(self):
        from invenio.legacy.refextract.tag import identify_ibids
        ref_line = u"""[46] E. Schrodinger, Sitzungsber. Preuss. Akad. Wiss. Phys. Math. Kl. 24, 418(1930); ibid, 3, 1(1931)"""
        r = identify_ibids(ref_line.upper())
        self.assertEqual(r, ({85: u'IBID'}, u'[46] E. SCHRODINGER, SITZUNGSBER. PREUSS. AKAD. WISS. PHYS. MATH. KL. 24, 418(1930); ____, 3, 1(1931)'))


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

    def test_vol_page_year(self):
        ",  ()"
        from invenio.legacy.refextract.tag import find_numeration
        ref_line = u"""24, 418 (1930)"""
        r = find_numeration(ref_line)
        self.assertEqual(r['volume'], u"24")
        self.assertEqual(r['year'], u"1930")
        self.assertEqual(r['page'], u"418")

    def test_vol_year_page(self):
        ", ()  "
        from invenio.legacy.refextract.tag import find_numeration
        ref_line = u"""24, (1930) 418"""
github inveniosoftware / invenio / invenio / modules / upgrader / testsuite / test_upgrader.py View on Github external
TestUpgrade('5', ['3', '4'], 'invenio'),
            TestUpgrade('6', ['5', ], 'invenio'),
        ])

        history = dictify(['1', '2', '4'], value=1)
        m = InvenioUpgrader()
        self.assertEqual(upgrades_str(m.order_upgrades(upgrades, history)),
                         "[3, 5, 6]")

        history = dictify(['3', '5'], value=1)
        m = InvenioUpgrader()
        self.assertEqual(
            upgrades_str(m.order_upgrades(upgrades, history)), "[6]")


class TestInvenioUpgraderRecipe(InvenioTestCase):
    def setUp(self):
        """
        Setup a test python package, to test upgrade recipe creation.
        """
        self.tmpdir = tempfile.mkdtemp()
        self.pkg_path = os.path.join(self.tmpdir, 'invenio_upgrader_test')
        os.makedirs(self.pkg_path)
        open(os.path.join(self.pkg_path, '__init__.py'), 'a').close()
        self.pkg_path_mymod = os.path.join(
            self.tmpdir, 'invenio_upgrader_test/mymod'
        )
        os.makedirs(self.pkg_path_mymod)

        open(os.path.join(self.pkg_path, '__init__.py'), 'a').close()
        open(os.path.join(self.pkg_path_mymod, '__init__.py'), 'a').close()
github inveniosoftware / invenio / invenio_demosite / testsuite / regression / test_bibrank.py View on Github external
def test_search_results_ranked_by_citations_verbose(self):
        """bibrank - search results ranked by number of citations, verbose output"""
        #FIXME verbose is not supported in jinja2 templates
        self.assertEqual([],
                         test_web_page_content(CFG_SITE_URL + '/search?cc=Articles+%26+Preprints&p=Klebanov&rm=citation&verbose=2',
                                               username="admin",
                                               expected_text="find_citations retlist [[85, 0], [77, 2], [84, 3]]"))

    def test_detailed_record_citations_tab(self):
        """bibrank - detailed record, citations tab"""
        self.assertEqual([],
                         test_web_page_content(CFG_SITE_URL + '/'+ CFG_SITE_RECORD +'/79/citations',
                                               expected_text=["Cited by: 1 records",
                                                              "Co-cited with: 2 records"]))

class BibRankExtCitesTest(InvenioTestCase):
    """Check BibRank citation ranking tools with respect to the external cites."""

    def _detect_extcite_info(self, extcitepubinfo):
        """
        Helper function to return list of recIDs citing given
        extcitepubinfo.  Could be move to the business logic, if
        interesting for other callers.
        """
        res = run_sql("""SELECT id_bibrec FROM rnkCITATIONDATAEXT
                          WHERE extcitepubinfo=%s""",
                      (extcitepubinfo,))
        return [int(x[0]) for x in res]

    def test_extcite_via_report_number(self):
        """bibrank - external cites, via report number"""
        # The external paper hep-th/0112258 is cited by 9 demo
github inveniosoftware / invenio / invenio / testsuite / test_emergency_recipients.py View on Github external
# 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.

""" Test unit for the miscutil/errorlib module. """

__revision__ = "$Id$"

import datetime
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase


class TestGetEmergencyRecipients(InvenioTestCase):

    def test_get_emergency_recipients(self):
        """errorlib - test return of proper set of recipients"""
        from invenio.legacy.bibsched.cli import get_emergency_recipients

        now = datetime.datetime(year=2000, month=1, day=20,
                                hour=14, minute=0)
        tomorrow = now + datetime.timedelta(days=1)
        diff_day = now + datetime.timedelta(days=4)
        later = now.replace(hour=(now.hour + 1) % 24)
        earlier = now.replace(hour=(now.hour - 1) % 24)
        constraint_now = "%s %s-%s" % (
            now.strftime("%a"),
            earlier.strftime("%H:00"),
            later.strftime("%H:00"),
        )
github inveniosoftware / invenio / invenio / legacy / bibsword / client_tester.py View on Github external
from invenio.legacy.bibsword.client_http import RemoteSwordServer
from invenio.legacy.bibsword.client_dblayer import get_remote_server_auth, \
                                            insert_into_swr_clientdata, \
                                            update_submission_status, \
                                            select_submitted_record_infos, \
                                            delete_from_swr_clientdata
from invenio.legacy.dbquery import run_sql
from invenio.legacy.bibsword.config import CFG_SUBMISSION_STATUS_SUBMITTED, \
                                    CFG_SUBMISSION_STATUS_PUBLISHED, \
                                    CFG_SUBMISSION_STATUS_REMOVED
from xml.dom import minidom

TEST_DATA = pkg_resources.resource_filename('invenio.legacy.bibsword', 'data')


class Test_format_marcxml_file(InvenioTestCase):
    """ bibsword_format - test the parsing and extracting of marcxml nodes"""

    def test_extract_marcxml_1(self):
        """Test_format_marcxml_file - extract marcxml without id, report_nos and comment"""
        # Test with marcxml file 1
        marcxml = open("%s%sTest_marcxml_file_1.xml" % (TEST_DATA, os.sep)).read()
        metadata = format_marcxml_file(marcxml)
        self.assertEqual(metadata['id'], '')
        self.assertEqual(metadata['title'],  "Calorimetry triggering in ATLAS")
        self.assertEqual(metadata['contributors'][0]['name'], "Igonkina, O")
        self.assertEqual(metadata['contributors'][0]['affiliation'][0], "NIKHEF, Amsterdam")
        self.assertEqual(metadata['summary'], "The ATLAS experiment is preparing for data taking at 14 TeV collision energy. A rich discovery physics program is being prepared in addition to the detailed study of Standard Model processes which will be produced in abundance. The ATLAS multi-level trigger system is designed to accept one event in 2 105 to enable the selection of rare and unusual physics events. The ATLAS calorimeter system is a precise instrument, which includes liquid Argon electro-magnetic and hadronic components as well as a scintillator-tile hadronic calorimeter. All these components are used in the various levels of the trigger system. A wide physics coverage is ensured by inclusively selecting events with candidate electrons, photons, taus, jets or those with large missing transverse energy. The commissioning of the trigger system is being performed with cosmic ray events and by replaying simulated Monte Carlo events through the trigger and data acquisition system.")
        self.assertEqual(metadata['contributors'][1]['name'], "Achenbach, R")
        self.assertEqual(metadata['contributors'][1]['affiliation'][0], "Kirchhoff Inst. Phys.")
        self.assertEqual(metadata['contributors'][2]['name'], "Adragna, P")
        self.assertEqual(metadata['contributors'][2]['affiliation'][0], "Queen Mary, U. of London")
github inveniosoftware / invenio / invenio / testsuite / test_ext_passlib.py View on Github external
"""Test mysql_aes_encrypt."""
        self.assertEqual(
            mysql_aes_decrypt(unhexlify("9e9ce44cd9df2b201f51947e03bccbe2"),
                              "key"),
            "test"
        )
        self.assertEqual(
            mysql_aes_decrypt(unhexlify(u"9e9ce44cd9df2b201f51947e03bccbe2"),
                              u"key"),
            "test"
        )
        self.assertRaises(AssertionError, mysql_aes_decrypt, object(), "key")
        self.assertRaises(AssertionError, mysql_aes_decrypt, "val", object())


class PasslibTestCase(InvenioTestCase):

    """Test passlib extensions."""

    config = {
        'PASSLIB_SCHEMES': ['sha512_crypt', 'invenio_aes_encrypted_email'],
        'PASSLIB_DEPRECATED_SCHEMES': ['invenio_aes_encrypted_email']
    }

    def test_context(self):
        """Test passlib password context."""
        ctx = self.app.extensions['passlib']
        hashval = ctx.encrypt("test")
        assert hashval != "test"
        assert ctx.verify("test", hashval)
        assert not ctx.needs_update(hashval)
        assert ctx.encrypt("test") != ctx.encrypt("test")
github inveniosoftware / invenio / invenio / testsuite / test_utils_hepdata.py View on Github external
bibrecord = lazy_import('invenio.legacy.bibrecord')


class TestParsingSystematics(InvenioTestCase):
    """ Systematics strings to be parsed (we check only that they parse
    at all not generating exceptions)
    """

    def test_guess_minimum_encoding(self):
        """textutils - guess_minimum_encoding."""
#        self.assertEqual(guess_minimum_encoding('patata'), ('patata', 'ascii'))
#        self.assertEqual(False, True, "ble")
        # we make sure that this does not cauase any exception !
        pass

class TestDatasetPaperLogic(InvenioTestCase):
    """ Testing the business logic classes
    """

    def test_parse_systematics(self):
        """
        To be filled when it becomes more clear how to treat systematics
        http://hepdata.cedar.ac.uk/view/ins1720
        http://hepdata.cedar.ac.uk/view/ins215359
        """
        pass

    def test_copy_245_fields_correct_caption(self):
        """Test the case when original record contains already some
           instances of 245 field and we want to extend by the HEPDATA
           caption """
        rec_string = """
github inveniosoftware / invenio / invenio_demosite / testsuite / regression / test_sequencegenerator.py View on Github external
'',
            3)],
            '270': [([('m', 'dummy@dummy.com')], ' ', ' ', '', 5)],
            '856': [([('u', 'http://dummy.com/')], '4', ' ', '', 6)],
            '970': [([('a', 'CONF-XXXXXX')], ' ', ' ', '', 2)],
            '980': [([('a', 'CONFERENCES')], ' ', ' ', '', 7)]}


class IntSeq(SequenceGenerator):
    seq_name = 'test_int'

    def _next_value(self, x):
        return x + 1


class TestIntSequenceGeneratorClass(InvenioTestCase):

    def test_sequence_next_int(self):
        int_seq = IntSeq()
        next_int = int_seq.next_value(1)
        self.assertEqual(next_int, 2)

        # Check if the value was stored in the DB
        res = run_sql("""SELECT seq_value FROM seqSTORE
                         WHERE seq_value=%s AND seq_name=%s""",
                         (2, int_seq.seq_name))
        self.assertEqual(int(res[0][0]), 2)

        # Clean DB entries
        run_sql(""" DELETE FROM seqSTORE WHERE seq_name="test_int" """)
github inveniosoftware / invenio / invenio / modules / records / testsuite / test_legacy_record.py View on Github external
bibrecord.record_add_subfield_into(self.rec, "245", "z", "Ulriken",
            subfield_position=2, field_position_global=4)
        bibrecord.record_add_subfield_into(self.rec, "245", "z",
            "Stortinget", subfield_position=999, field_position_global=4)
        self.assertEqual(bibrecord.record_get_field_values(self.rec, "245", " ", "1", "%"),
                         ['Fiskeflue', 'On the foo and bar1', 'Ulriken', 'Elgokse', 'Stortinget'])
        # Some crash tests
        self.assertRaises(bibrecord.InvenioBibRecordFieldError,
            bibrecord.record_add_subfield_into, self.rec, "187", "x", "Crash",
            field_position_global=1)
        self.assertRaises(bibrecord.InvenioBibRecordFieldError,
            bibrecord.record_add_subfield_into, self.rec, "245", "x", "Crash",
            field_position_global=999)


class BibRecordModifyControlfieldTest(InvenioTestCase):
    """ bibrecord - testing controlfield modification """

    def setUp(self):
        """Initialize stuff"""
        xml_example_record = """
        
        33
        A Foo's Tale
        Skeech Skeech
        Whoop Whoop
        
        eng
        
        
        On the foo and bar2
github zenodo / zenodo / zenodo / modules / accessrequests / testsuite / test_tokens.py View on Github external
t1 = s.create_token(98765, dict(recid=4321))
        t2 = s.create_token(98765, dict(recid=4321))
        self.assertNotEqual(t1, t2)

    def test_noencryption(self):
        """Test that token is not encrypted."""
        s = SecretLinkSerializer()
        t1 = s.create_token(1, dict(recid=1))
        self.assertRaises(
            BadSignature,
            JSONWebSignatureSerializer('anotherkey').loads,
            t1
        )


class EncryptedTokenMixinTestCase(InvenioTestCase):

    """Test case for encrypted tokens."""

    class TestSerializer(EncryptedTokenMixIn, SecretLinkSerializer):
        pass

    def test_create_validate(self):
        """Test token creation."""
        s = self.TestSerializer()
        t = s.create_token(1234, dict(recid=56789))
        data = s.validate_token(t)
        self.assertEqual(data['id'], 1234)
        self.assertEqual(data['data']['recid'], 56789)

    def test_creation(self):
        """Ensure that no two tokens are identical."""