remote_app='orcid', code='test', state=self._get_state())) httpretty.disable() # Assert database state (Sign-up complete) u = User.query.filter_by(email=self.existing_email).one() UserEXT.query.filter_by( method='orcid', id_user=u.id, id=self.example_data['orcid'] ).one() self.assertEqual(u.given_names, "Josiah") self.assertEqual(u.family_name, "Carberry") # Disconnect link resp = self.client.get( url_for("oauthclient.disconnect", remote_app='orcid')) self.assertStatus(resp, 302) # User exists u = User.query.filter_by(email=self.existing_email).one() # UserEXT removed. assert 0 == UserEXT.query.filter_by( method='orcid', id_user=u.id, id=self.example_data['orcid'] ).count() TEST_SUITE = make_test_suite(OrcidTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
for key,value in iteritems(options): setattr(c, key, value) # add a collection with "one" record coll = Collection() coll.nbrecs = 1 setattr(c, "collection", coll) return c def test_rank_community_with_one_record(self): """communities - test community rank basic""" c = self._create_comunity({'id': self.test_name, 'id_user': 1, 'last_record_accepted': datetime.now()-timedelta(days=100), 'fixed_points': 0}) self.assertEqual(calculate_rank_for_community(c, 2), 5) def test_rank_community_last_accepted(self): """communities - test community rank new record accepted""" c = self._create_comunity({'id': self.test_name, 'id_user': 1, 'last_record_accepted': datetime.now(), 'fixed_points': 20}) self.assertEqual(calculate_rank_for_community(c, 2), 29) TEST_SUITE = make_test_suite(CommunityModelTest, CommunityRankerTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
def test_publi_info(self): """Test if publication info is created correctly""" self.assertEqual(self.sample_latex_eu['publi_info'], self.latex_eu._get_publi_info()) self.assertEqual(self.sample_latex_us['publi_info'], self.latex_us._get_publi_info()) self.assertEqual(self.sample_latex_publi_info['publi_info'], self.latex_eu_publi_info._get_publi_info()) def test_arxiv(self): """Test if arxiv is created correctly""" self.assertEqual(self.sample_latex_eu['arxiv'], self.latex_eu._get_arxiv()) self.assertEqual(self.sample_latex_us['arxiv'], self.latex_us._get_arxiv()) def test_slac_citation(self): """Test if slac citation is created correctly""" self.assertEqual(self.sample_latex_eu['SLACcitation'], self.latex_eu._get_slac_citation()) self.assertEqual(self.sample_latex_us['SLACcitation'], self.latex_us._get_slac_citation()) TEST_SUITE = make_test_suite(LatexTests) if __name__ == "__main__": run_test_suite(TEST_SUITE)
"source": "arXiv", } ]}) res = match_by_arxiv_id(record) self.assertTrue(res) @httpretty.activate def test_doi_results(self): """Test that bad matching results are handled correctly.""" from invenio_records.api import Record from invenio.base.globals import cfg from inspire.modules.workflows.tasks.matching import match_by_doi httpretty.register_uri( httpretty.GET, cfg["WORKFLOWS_MATCH_REMOTE_SERVER_URL"], body="[1234]", content_type="application/json" ) record = Record({"dois": {"value": "10.1086/305772"}}) res = match_by_doi(record) self.assertTrue(res) # FIXME Also test for multiple DOIs TEST_SUITE = make_test_suite(MatchingTests) if __name__ == "__main__": run_test_suite(TEST_SUITE)
"what": "lorem", "where": { "record": 1, "marker": "P.1_T.2a.2_L.100" }, "comment": 1 } a = API.add_annotation(model='annotation_note', **data) # JSONAlchemy issue with overwriting fields self.assert_(len(a.validate()) == 0) ld = a.get_jsonld( "oaf", new_context={"ST": "http://www.w3.org/ns/oa#" "FragmentSelector"}, format="compacted") self.assert_(ld["http://www.w3.org/ns/oa#hasTarget"] ["http://www.w3.org/ns/oa#hasSelector"]["@type"] == "ST") self.assert_(ld["http://www.w3.org/ns/oa#hasTarget"] ["http://www.w3.org/ns/oa#hasSelector"] ["http://www.w3.org/1999/02/22-rdf-syntax-ns#value"] == "P.1_T.2a.2_L.100") TEST_SUITE = make_test_suite(TestAnnotation, TestJSONLD) if __name__ == "__main__": run_test_suite(TEST_SUITE)
def test_prepare_notes(self): """Test note tree preparation""" tree = PREPARE_NOTES([ {'where': {'marker': 'P.1'}, 'what': 'lorem'}, {'where': {'marker': 'P.1_F.2a'}, 'what': 'ipsum'}, {'where': {'marker': 'G'}, 'what': 'dolor'}, {'where': {'marker': 'G'}, 'what': 'elit'}, {'where': {'marker': 'G_T.4'}, 'what': 'adipisicing'}, {'where': {'marker': 'E.4'}, 'what': 'sit amet'}, {'where': {'marker': 'E.4'}, 'what': 'consectetur'}]) self.assert_(tree['P.1']['leaf'][0]['what'] == 'lorem') self.assert_(len(tree['E.4']['leaf']) == 2) self.assert_(tree['E.4']['leaf'][0]['what'] == 'sit amet') self.assert_(tree['E.4']['leaf'][1]['what'] == 'consectetur') self.assert_(tree['G']['path'] == 'G') self.assert_(tree['P.1']['F.2a']['path'] == 'P.1_F.2a') self.assert_(tree['P.1']['F.2a']['leaf'][0]['what'] == 'ipsum') self.assert_(len(tree['G']['leaf']) == 2) self.assert_(tree['G']['T.4']['path'] == 'G_T.4') def test_get_original_comment(self): # FIXME: implement pass TEST_SUITE = make_test_suite(TestExtractNotes) if __name__ == "__main__": run_test_suite(TEST_SUITE)
# Workflow is finished. Test if record is created recid = deposition.get_data('recid') assert recid is not None # Test that record id exists assert record_exists(recid) == 1 # Test that the task exists task_id = deposition.get_data('task_id') assert task_id is not None bibtask = SchTASK.query.filter(SchTASK.id == task_id).first() assert bibtask is not None # Run bibupload, bibindex, webcoll manually cmd = "%s/bin/bibupload %s" % (CFG_PREFIX, task_id) assert not os.system(cmd) rec = get_record(recid) marc = rec.legacy_export_as_marc() for field in form: if isinstance(field, TextAreaField): # If the field is associated with a marc field if field.has_recjson_key() or field.has_cook_function(): assert "test " + field.name in marc TEST_SUITE = make_test_suite(TestWebDepositUtils) if __name__ == "__main__": run_test_suite(TEST_SUITE)
self.assertEqual(obj.get_data(), final_data) self.assertEqual(obj.version, CFG_OBJECT_VERSION.FINAL) self.assertEqual(obj.id_parent, initial_object[0].id) self.assertEqual(initial_object[0].get_data(), initial_data) def _check_workflow_execution(self, objects, initial_data, final_data): # Let's check that we found anything. There should only be one object self.assertEqual(objects.count(), 1) parent_object = objects[0] # The object should be the inital version self.assertEqual(parent_object.version, CFG_OBJECT_VERSION.INITIAL) # The object should have the inital data self.assertEqual(parent_object.get_data(), initial_data) # Fetch final object which should exist final_object = objects[0].child_objects[0] self.assertTrue(final_object) if final_data: # Check that final data is correct self.assertEqual(final_object.get_data(), final_data) TEST_SUITE = make_test_suite(TestWorkflowStart) if __name__ == "__main__": run_test_suite(TEST_SUITE)
"mytoken2", "mysecret2", token_type='t2') assert t2.remote_account.id == acc.id assert t2.token_type == 't2' t3 = RemoteToken.get(self.u1, "dev") t4 = RemoteToken.get(self.u1, "dev", token_type="t2") assert t4.token() != t3.token() assert RemoteToken.query.count() == 2 acc.delete() assert RemoteToken.query.count() == 0 def test_get_regression(self): from invenio_oauthclient.models import RemoteToken t3 = RemoteToken.create(self.u2, "dev", "mytoken", "mysecret") t4 = RemoteToken.create(self.u3, "dev", "mytoken", "mysecret") assert RemoteToken.get(self.u2, "dev").remote_account.user_id == \ t3.remote_account.user_id assert RemoteToken.get(self.u3, "dev").remote_account.user_id == \ t4.remote_account.user_id TEST_SUITE = make_test_suite(RemoteAccountTestCase, RemoteTokenTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
'Odin', 'Eric', 'Frank', 'Theodor', 'Richard' ]) def test_dict1_subfield(self): """bibindex termcollectors - get_field_values - simple field""" fields = self.dict1 phrases = [] get_values_recursively(fields['all']['people'], phrases) self.assertEqual(phrases, ['Frank', 'Theodor', 'Richard']) def test_dict2_all_fields(self): """bibindex termcollectors - get_field_values - nested field""" fields = self.dict2 phrases = [] get_values_recursively(fields['all'], phrases) self.assertEqual(phrases, ['name1', 'name2', 'name4']) TEST_SUITE = make_test_suite( TestListSetOperations, TestWashIndexTerm, TestGetWordsFromPhrase, TestGetPairsFromPhrase, TestGetWordsFromDateTag, TestGetAuthorFamilyNameWords, TestGetValuesFromRecjson, ) if __name__ == "__main__": run_test_suite(TEST_SUITE)
import time from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase class RedisUtilsTest(InvenioTestCase): def setUp(self): from invenio.utils.redis import get_redis self.db = get_redis() def test_set(self): from invenio.config import CFG_REDIS_HOSTS self.db.set('hello_test', 'a') if CFG_REDIS_HOSTS: self.assertEqual(self.db.get('hello_test'), 'a') else: self.assertEqual(self.db.get('hello_test'), None) self.db.delete('hello_test') def test_expire(self): self.db.set('hello', 'a', 1) time.sleep(2) self.assertEqual(self.db.get('hello'), None) TEST_SUITE = make_test_suite(RedisUtilsTest) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
self.useremail) @nottest def test_auth_user_fail(self): """external authentication CERN - authorizing user through CERN system: should fail""" self.assertEqual(self.cern.auth_user('patata', 'patata'), None) @nottest def test_fetch_user_groups_membership(self): """external authentication CERN - fetching user group membership at CERN""" self.assertNotEqual( self.cern.fetch_user_groups_membership(self.useremail, self.userpwd), 0) self.assertEqual( self.cern.fetch_user_groups_membership('patata', 'patata'), {}) @nottest def test_fetch_user_preferences(self): """external authentication CERN - fetching user setting from CERN""" self.assertEqual( self.cern.fetch_user_preferences(self.username, self.userpwd)['email'], self.useremail) #self.assertRaises(KeyError, self.cern.fetch_user_preferences('patata', 'patata')['email']) TEST_SUITE = make_test_suite(ExternalAuthenticationCernTest, ) if __name__ == "__main__": run_test_suite(TEST_SUITE)
website='http://inveniosoftware.org', redirect_uris="http://localhost/oauth/authorized/")) self.assertStatus(res, 302) # Invalid redirect_uri (must be https) res = self.client.post( url_for('oauth2server_settings.client_new'), base_url=cfg['CFG_SITE_SECURE_URL'], data=dict(name='Test', description='Test description', website='http://inveniosoftware.org', redirect_uris="http://example.org/oauth/authorized/")) self.assertStatus(res, 200) # Valid res = self.client.post( url_for('oauth2server_settings.client_new'), base_url=cfg['CFG_SITE_SECURE_URL'], data=dict(name='Test', description='Test description', website='http://inveniosoftware.org', redirect_uris="https://example.org/oauth/authorized/\n" "http://localhost:4000/oauth/authorized/")) self.assertStatus(res, 302) TEST_SUITE = make_test_suite(OAuth2ProviderTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
os.rename(taxonomy_path + 'x', taxonomy_path) # make cache ok (but old), and corrupt source bibclassify_ontology_reader.get_regular_expressions(taxonomy_name, rebuild=True, no_cache=False) try: try: os.rename(taxonomy_path, taxonomy_path + 'x') open(taxonomy_path, 'w').close() bibclassify_ontology_reader.get_regular_expressions( taxonomy_name, rebuild=False, no_cache=False) except: pass finally: os.rename(taxonomy_path + 'x', taxonomy_path) self.log.error('...testing of corrupted states finished.') name, taxonomy_path, taxonomy_url = bibclassify_ontology_reader._get_ontology( taxonomy_name) cache = bibclassify_ontology_reader._get_cache_path(name) os.remove(taxonomy_path) os.remove(cache) TEST_SUITE = make_test_suite(BibClassifyTest) if __name__ == '__main__': run_test_suite(TEST_SUITE)
from invenio.utils.autodiscovery import autodiscover_modules from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase, nottest class AutodiscoveryTest(InvenioTestCase): """ Autodiscovery TestSuite. """ def test_autodiscover_modules(self): """autodiscover modules""" modules = autodiscover_modules(['invenio.base'], related_name_re='config') assert (len(modules) == 1) assert (None not in modules) modules = autodiscover_modules(['invenio.not_an_existing_folder'], related_name_re='foo_.+') assert (len(modules) == 0) assert (None not in modules) modules = autodiscover_modules( ['invenio.modules.formatter.format_elements'], related_name_re='not_an_existing_package_name_.+') assert (len(modules) == 0) assert (None not in modules) TEST_SUITE = make_test_suite(AutodiscoveryTest, ) if __name__ == "__main__": run_test_suite(TEST_SUITE)
'publisher': 'abc' } }, 'Elsevier', { 'publication_info': { 'publisher': 'Elsevier' } }), ('no_publisher', { 'publication_info': {} }, 'Elsevier', { 'publication_info': { 'publisher': 'Elsevier' } }), ('no_pub_info', {}, 'Elsevier', { 'publication_info': { 'publisher': 'Elsevier' } }), )) def test_adding_of_publisher_to_record(self, _, record, publisher, expected_record): _set_publisher = add_publisher._set_publisher self.assertEqual(_set_publisher(publisher, record), expected_record) TEST_SUITE = make_test_suite(TestChanges) if __name__ == "__main__": run_test_suite(TEST_SUITE)
factory = partial(tclient_request_factory, self.client) metadata = dict( upload_type="software", title="Test title", creators=[ dict(name="Doe, John", affiliation="Atlantis"), dict(name="Smith, Jane", affiliation="Atlantis") ], description="Test Description", publication_date="2013-05-08", ) files = [make_pdf_fixture('test.pdf', "upload test")] metadata = upload( self.accesstoken[self.user.id], metadata, files, publish=True, request_factory=factory ) assert 'record_id' in metadata assert 'doi' in metadata TEST_SUITE = make_test_suite(ZenodoUploadTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
compile_role_definition(None))) def test_firerole_uid(self): """firerole - firerole core testing with integer uid""" self.assertEqual(False, acc_firerole_check_user(self.guest, compile_role_definition("deny uid '-1', '0'\nallow all"))) self.assertEqual(True, acc_firerole_check_user(self.user_info, compile_role_definition("deny uid '-1', '0'\nallow all"))) def test_firerole_guest(self): """firerole - firerole core testing with guest""" self.assertEqual(False, acc_firerole_check_user(self.guest, compile_role_definition("deny guest '1'\nallow all"))) self.assertEqual(True, acc_firerole_check_user(self.guest, compile_role_definition("deny guest '0'\nallow all"))) self.assertEqual(True, acc_firerole_check_user(self.user_info, compile_role_definition("deny guest '1'\nallow all"))) self.assertEqual(False, acc_firerole_check_user(self.user_info, compile_role_definition("deny guest '0'\nallow all"))) self.assertEqual(False, acc_firerole_check_user(self.user_info, compile_role_definition("deny guest '1'\ndeny all"))) self.assertEqual(False, acc_firerole_check_user(self.user_info, compile_role_definition("deny guest '0'\ndeny all"))) TEST_SUITE = make_test_suite(AccessControlFireRoleTest,) if __name__ == "__main__": run_test_suite(TEST_SUITE)
assert "Tests" in res.data assert "Simple Test" in res.data self.assert200( self.client.get( url_for('webdeposit.deposition_type_index', deposition_type='simple'))) def test_create_delete(self): """Test create delete.""" self.login("admin", "") dep_id = self.create('simple') self.assert200( self.client.get( url_for('webdeposit.run', deposition_type='simple', uuid=dep_id))) self.assert200( self.client.get(url_for('webdeposit.delete', deposition_type='simple', uuid=dep_id), follow_redirects=True)) TEST_SUITE = make_test_suite(SimpleRecordTest, ) if __name__ == "__main__": run_test_suite(TEST_SUITE)
self.failIf( run_sql("SELECT * FROM user WHERE email=%s", (self.another_email, )), "%s still exists! while it should have been merged into %s: %s, userEXT contains: %s" % (self.another_email, self.a_email, run_sql("SELECT * FROM user WHERE email=%s", (self.another_email, )), run_sql("SELECT * FROM userEXT"))) ## And the corresponding user should not exist anymore as it has been ## merged into id_user self.failIf( run_sql("SELECT * FROM user WHERE id=%s", (id_user2, ))) self.failUnless( run_sql("SELECT * FROM user WHERE id=%s AND email=%s", (id_user, self.a_email))) finally: self._erase_example_user_and_groups() TEST_SUITE = make_test_suite(WebAccessWebPagesAvailabilityTest, WebAccessFireRoleTest, WebAccessUseBasketsTest, WebAccessRobotLoginTest) else: TEST_SUITE = make_test_suite(WebAccessWebPagesAvailabilityTest, WebAccessFireRoleTest, WebAccessUseBasketsTest) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
os.remove(taxonomy_path) os.remove(cache) def xtest_ingest_taxonomy_by_url(self): pass def xtest_ingest_taxonomy_by_name(self): pass def xtest_ingest_taxonomy_by_path(self): pass def xtest_ingest_taxonomy_db_name(self): pass def xtest_ouput_modes(self): pass def xtest_get_single_keywords(self): """test the function returns {<keyword>: [ [spans...] ] }""" def xtest_get_composite_keywords(self): """test the function returns {<keyword>: [ [spans...], [correct component counts] ] }""" TEST_SUITE = make_test_suite(BibClassifyTest) if __name__ == '__main__': run_test_suite(TEST_SUITE)
from invenio.config import CFG_SITE_SECURE_URL from invenio.testsuite import make_test_suite, \ run_test_suite, \ InvenioWebTestCase class InvenioBibFormatWebTest(InvenioWebTestCase): """BibFormat web tests.""" def test_format_many_authors(self): """bibformat - web test format many authors""" self.browser.get(CFG_SITE_SECURE_URL) self.fill_textbox(textbox_name="p", text="recid:10") self.find_element_by_name_with_timeout("action_search") self.browser.find_element_by_name("action_search").click() self.handle_popup_dialog() self.page_source_test(expected_text='Bruneliere, R') self.find_element_by_link_text_with_timeout("Detailed record") self.browser.find_element_by_link_text("Detailed record").click() self.page_source_test(expected_text='Show all 315 authors') self.find_element_by_link_text_with_timeout("Show all 315 authors") self.browser.find_element_by_link_text("Show all 315 authors").click() self.page_source_test(expected_text=['Zobernig, G', 'Hide']) TEST_SUITE = make_test_suite(InvenioBibFormatWebTest, ) if __name__ == '__main__': run_test_suite(TEST_SUITE, warn_user=True)
from invenio.legacy.bibrank.selfcites_task import empty_self_cites_tables from invenio.legacy.dbquery import run_sql empty_self_cites_tables() counts = [ run_sql('SELECT count(*) from rnkRECORDSCACHE')[0][0], run_sql('SELECT count(*) from rnkEXTENDEDAUTHORS')[0][0], run_sql('SELECT count(*) from rnkSELFCITES')[0][0], ] self.assertEqual(counts, [0, 0, 0]) def test_fill_self_cites_tables(self): from invenio.legacy.bibrank.selfcites_task import fill_self_cites_tables from invenio.legacy.dbquery import run_sql config = {'algorithm':'friends', 'friends_threshold': 3} fill_self_cites_tables(config) counts = [ run_sql('SELECT count(*) from rnkRECORDSCACHE')[0][0], run_sql('SELECT count(*) from rnkEXTENDEDAUTHORS')[0][0], run_sql('SELECT count(*) from rnkSELFCITES')[0][0], ] self.assert_(counts[0] > 0) self.assert_(counts[1] > 0) self.assert_(counts[2] > 0) TEST_SUITE = make_test_suite(SelfCitesIndexerTests, SelfCitesTaskTests) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
class BibFormat2ndPassTest(InvenioTestCase): """Check for 2 passes parsing for record""" @property def config(self): data = super(BibFormat2ndPassTest, self).config data['PACKAGES'] = TEST_PACKAGES + data.get('PACKAGES', PACKAGES) return data def setUp(self): self.xml_text = '''<record> <controlfield tag="001">33</controlfield> <datafield tag="980" ind1="" ind2=""> <subfield code="b">thesis </subfield> </datafield> </record>''' def test_format_2_passes(self): from invenio.modules.formatter import format_record result = format_record(recID=None, of="test6", xml_record=self.xml_text) self.assertEqual(result, "helloworld\n") TEST_SUITE = make_test_suite(OutputFormatTest, PatternTest, MiscTest, FormatTest, EscapingAndWashingTest, MarcFilteringTest, BibFormat2ndPassTest) if __name__ == '__main__': run_test_suite(TEST_SUITE)
def test_not_transform_link(self): """htmlutils - not transforming a link""" body_input = '<a href="https://cds.cern.ch/collection/Multimedia%20%26%20Outreach?ln=es">Multimedia</a>' body_expected = '<a href="https://cds.cern.ch/collection/Multimedia%20%26%20Outreach?ln=es">Multimedia</a>' self.assertEqual(self.washer.wash(html_buffer=body_input, automatic_link_transformation=True), body_expected) class HTMLCreation(InvenioTestCase): """Test functions related to creation of HTML markup.""" def test_create_html_select(self): """htmlutils - create HTML <select> list """ self.assertEqual(create_html_select(["foo", "bar"], selected="bar", name="baz"), '<select name="baz"><option value="foo">foo</option>\n<option selected="selected" value="bar">bar</option></select>') TEST_SUITE = make_test_suite(XSSEscapingTest, CharactersEscapingTest, HTMLWashingTest, HTMLMarkupRemovalTest, HTMLTidyingTest, HTMLAutomaticLinksTransformation, HTMLCreation, JavascriptCharactersEscapingTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
lines[-6:-1] = [] compare_references(self, '\n'.join(lines), expected_response()) @unittest.skipUnless(HAS_REQUESTS, 'no request') def test_url(self): from invenio.config import CFG_SITE_URL url = CFG_SITE_URL + '/textmining/api/extract-references-pdf-url' pdf = CFG_SITE_URL + '/textmining/example.pdf' response = requests.post(url, data={'url': pdf}) compare_references(self, response.content, expected_response()) @unittest.skipUnless(HAS_REQUESTS, 'no request') def test_txt(self): from invenio.config import CFG_SITE_URL url = CFG_SITE_URL + '/textmining/api/extract-references-txt' pdf = open(pkg_resources.resource_filename( 'invenio.modules.textminer.testsuite', 'data/example.txt'), 'rb') response = requests.post(url, files={'txt': pdf}) # Remove stats tag lines = response.content.split('\n') lines[-6:-1] = [] compare_references(self, '\n'.join(lines), expected_response()) TEST_SUITE = make_test_suite(DocExtractTest) if __name__ == '__main__': run_test_suite(TEST_SUITE)
recIDs = [121] self.assertEqual(get_low_level_recIDs_from_control_no(control_no), recIDs) def test_bibauthority_get_control_nos_from_recID(self): """bibauthority - test get_control_nos_from_recID()""" self.assertTrue(len(get_control_nos_from_recID(118))) def test_bibauthority_guess_main_name(self): """bibauthority - test guess_main_name_from_authority_recID()""" recID = 118 main_name = 'Ellis, John' self.assertEqual(guess_main_name_from_authority_recID(recID), main_name) def test_authority_record_string_by_control_no(self): """bibauthority - simple test of get_index_strings_by_control_no()""" # vars _type = CFG_BIBAUTHORITY_TYPE_NAMES['AUTHOR'] control_no = _type + CFG_BIBAUTHORITY_PREFIX_SEP + '(SzGeCERN)aaa0005' string = 'Ellis, Jonathan Richard' # run test self.assertTrue(string in get_index_strings_by_control_no(control_no)) TEST_SUITE = make_test_suite( BibAuthorityEngineTest, ) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
for k in test_record.keys(): self.assertEqual(test_record[k], r[k]) def test_pre1900_publication_date(self): from invenio.modules.records.api import Record r = Record.create( '<record><datafield tag="260" ind1="" ind2="">' '<subfield code="c">0900-12-31</subfield>' '</datafield></record>', master_format='marc' ) self.assertEqual(date(900, 12, 31), r['publication_date']) self.assertEqual('0900-12-31', r.dumps()['publication_date']) assert '0900-12-31' in r.legacy_export_as_marc() def test_pre1900_embargo_date(self): from invenio.modules.records.api import Record r = Record.create( '<record><datafield tag="942" ind1="" ind2="">' '<subfield code="a">0900-12-31</subfield>' '</datafield></record>', master_format='marc' ) self.assertEqual(date(900, 12, 31), r['embargo_date']) self.assertEqual('0900-12-31', r.dumps()['embargo_date']) assert '0900-12-31' in r.legacy_export_as_marc() TEST_SUITE = make_test_suite(TestReaders) if __name__ == '__main__': run_test_suite(TEST_SUITE)
def test_preferences_edition(self): browser = self.login('admin', '') browser.open(cfg['CFG_SITE_SECURE_URL'] + "/youraccount/edit/WebTagSettings") browser.select_form(nr=0) browser.form.find_control( name='display_tags_public').items[0].selected = False browser.submit() browser.open(cfg['CFG_SITE_SECURE_URL'] + "/youraccount/edit/WebTagSettings") browser.select_form(nr=0) if browser.form.find_control( name='display_tags_public').items[0].selected == False: self.fail( "Setting 'display_tags_public' saved as False, but is still True" ) browser.form.find_control( name='display_tags_public').items[0].selected = True browser.submit() # Running tests TEST_SUITE = make_test_suite(WebTagDeletionTest, WebTagUserSettingsTest) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
sys.exit = _exit sys.stdout = _stdout def test_update_true_to_false(self): """Test updating an existing value from True to False.""" _stdout = sys.stdout sys.stdout = config.StringIO() side_effect = [ '', # CFG_DATABASE_HOST '', # CFG_DATABASE_NAME '', # CFG_DATABASE_PASS '', # CFG_DATABASE_PORT '', # CFG_DATABASE_SLAVE '', # CFG_DATABASE_TYPE '', # CFG_DATABASE_USER 'False', # DEBUG '', # SECRET_KEY ] with mock.patch('__builtin__.raw_input', side_effect=side_effect): config.update(self.cfg) with open(self._tmp) as f: self.assertRegexpMatches(f.read(), "DEBUG\s*=\s*False") sys.stdout = _stdout TEST_SUITE = make_test_suite(TestConfig)
self.browser.get( CFG_SITE_SECURE_URL + '/admin/webjournal/webjournaladmin.py/configure?action=add&ln=en') self.page_source_test(unexpected_text='Authorization failure') self.browser.get( CFG_SITE_SECURE_URL + '/admin/webjournal/webjournaladmin.py/index?journal_name=AtlantisTimes&action=askDelete&ln=en' ) self.page_source_test(unexpected_text='Authorization failure') self.browser.get( CFG_SITE_SECURE_URL + '/admin/webjournal/webjournaladmin.py/configure?action=edit&journal_name=AtlantisTimes&ln=en' ) self.page_source_test(unexpected_text='Authorization failure') self.browser.get( CFG_SITE_SECURE_URL + '/admin/webjournal/webjournaladmin.py/feature_record?journal_name=AtlantisTimes&ln=en' ) self.page_source_test(unexpected_text='Authorization failure') self.browser.get( CFG_SITE_SECURE_URL + '/admin/webjournal/webjournaladmin.py/feature_record?ln=en') self.page_source_test(unexpected_text='Authorization failure') self.logout() TEST_SUITE = make_test_suite(InvenioWebJournalWebTest, ) if __name__ == '__main__': run_test_suite(TEST_SUITE, warn_user=True)
# Create another temporary dir for the zip file. tmp_tar_dir = tempfile.mkdtemp() # And make an archive out of it tar_file = make_archive(osp.join(tmp_tar_dir, '_tar_with_txt_csv'), 'tar', tmp_dir) self.assertEqual( api.calculate_score([(osp.basename(tar_file), tar_file)]), 100 ) # Remove the temporary directories rmtree(tmp_dir) rmtree(tmp_tar_dir) # Test if the files were removed self.assertEqual(osp.isdir(tmp_dir), False) self.assertEqual(osp.isdir(tmp_tar_dir), False) # Redundant.. directory is deleted. self.assertEqual(osp.exists(tar_file), False) self.assertEqual(osp.exists(txt_file.name), False) self.assertEqual(osp.exists(csv_file.name), False) TEST_SUITE = make_test_suite(CalculateScoreTest) if __name__ == '__main__': run_test_suite(TEST_SUITE)
'ADFS_LOGIN': '******', 'ADFS_EMAIL': self.app.config['CFG_SITE_ADMIN_EMAIL'], } expected_data = { 'email': self.app.config['CFG_SITE_ADMIN_EMAIL'], 'group': [ 'project-invenio-devel (Group)', 'CERN Registered (Group)', 'cern-personnel (Group)' ], } # FIXME mock user table from invenio.ext.sqlalchemy import db from invenio.modules.accounts.models import User admin = User.query.get(1) old_settings = admin.settings admin.settings = {'login_method': 'SSO'} db.session.merge(admin) db.session.commit() run(data, expected_data) admin.settings = old_settings db.session.merge(admin) db.session.commit() TEST_SUITE = make_test_suite(TestSSO) if __name__ == "__main__": run_test_suite(TEST_SUITE)
reject=True).validate() assert not ApprovalForm( message="test", expires_at=tomorrow, accept=True, reject=True).validate() # Accept + date validation assert ApprovalForm(message="", expires_at=tomorrow, accept=True).validate() assert ApprovalForm(message="", expires_at=oneyear, accept=True).validate() assert not ApprovalForm(message="", expires_at=today, accept=True).validate() assert not ApprovalForm(message="", expires_at=yesterday, accept=True).validate() assert not ApprovalForm( message="", expires_at=oneyearoneday, accept=True).validate() # Reject + message assert ApprovalForm(message="a message", expires_at="", reject=True).validate() assert not ApprovalForm(message="", expires_at="", reject=True).validate() assert not ApprovalForm(message=" ", expires_at="", reject=True).validate() TEST_SUITE = make_test_suite(ApprovalFormTestCase, AccessRequestFormTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
Cv_latex_html_text(self.hep_record, 'cv_latex_html', "<br/>"). _get_doi()) self.assertEqual(self.sample_cv_latex_text['doi'], Cv_latex_html_text(self.hep_record, 'cv_latex_text', "\n"). _get_doi()) def test_publi_info(self): """Test if publication info is created correctly""" self.assertEqual(self.sample_cv_latex_html['publi_info'], Cv_latex_html_text(self.hep_record, 'cv_latex_html', "<br/>"). _get_publi_info()) self.assertEqual(self.sample_cv_latex_text['publi_info'], Cv_latex_html_text(self.hep_record, 'cv_latex_text', "\n"). _get_publi_info()) self.assertEqual(self. sample_cv_latex_html_text_publi_info['publi_info'], Cv_latex_html_text(self.hep_record_publi_info, 'cv_latex_text', "\n"). _get_publi_info()) TEST_SUITE = make_test_suite(CvLatexHtmlTextTests) if __name__ == "__main__": run_test_suite(TEST_SUITE)
self.failIfEqual(id_user, id_user2) self.failUnless(run_sql("SELECT * FROM userEXT WHERE id=%s AND id_user=%s AND method=%s", (self.another_nickname, id_user2, method_name)), "Can't find id %s for user %s with metod %s. userEXT contains: %s" % (self.another_nickname, id_user2, method_name, run_sql("SELECT * FROM userEXT"))) ## The first email should still exists self.failUnless(run_sql("SELECT * FROM user WHERE email=%s", (self.a_email, ))) ## We log in with the 1st email but with the second nickname. ## That means the 1st user should be merged into the second. error_messages = test_web_page_content(url3, expected_text=self.another_nickname) if error_messages: self.fail(merge_error_messages(error_messages)) ## The another_email should not exist any longer. self.failIf(run_sql("SELECT * FROM user WHERE email=%s", (self.another_email, )), "%s still exists! while it should have been merged into %s: %s, userEXT contains: %s" % (self.another_email, self.a_email, run_sql("SELECT * FROM user WHERE email=%s", (self.another_email, )), run_sql("SELECT * FROM userEXT"))) ## And the corresponding user should not exist anymore as it has been ## merged into id_user self.failIf(run_sql("SELECT * FROM user WHERE id=%s", (id_user2, ))) self.failUnless(run_sql("SELECT * FROM user WHERE id=%s AND email=%s", (id_user, self.a_email))) finally: self._erase_example_user_and_groups() TEST_SUITE = make_test_suite(WebAccessWebPagesAvailabilityTest, WebAccessFireRoleTest, WebAccessUseBasketsTest, WebAccessRobotLoginTest) else: TEST_SUITE = make_test_suite(WebAccessWebPagesAvailabilityTest, WebAccessFireRoleTest, WebAccessUseBasketsTest) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with ZENODO. If not, see <http://www.gnu.org/licenses/>. ## ## In applying this licence, 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. """Unit tests for testing existing deposit objects.""" from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase class TestDepositObjects(InvenioTestCase): def test_load_workflow(self): from invenio.modules.workflows.models import BibWorkflowObject from invenio.modules.deposit.models import Deposition q = BibWorkflowObject.query.filter(BibWorkflowObject.id_user != 0).all() for b in q: Deposition(b) TEST_SUITE = make_test_suite(TestDepositObjects) if __name__ == '__main__': run_test_suite(TEST_SUITE)
def test_unsupported_versioning(self): httpretty.register_uri( httpretty.GET, self.app.config["ARXIV_API_URL"] + "?verb=GetRecord&metadataPrefix=arXiv&identifier=oai:arXiv.org:1007.5048v1", body=pkg_resources.resource_string("invenio.testsuite", "data/response_export_arxiv_versioning.xml"), status=200, ) response = self.app.extensions["arxiv"].search("1007.5048v1") self.assertEqual(response.status_code, 415) @httpretty.activate def test_malformed_arxiv_id(self): httpretty.register_uri( httpretty.GET, self.app.config["ARXIV_API_URL"] + "?verb=GetRecord&metadataPrefix=arXiv&identifier=oai:arXiv.org:dead.beef", body=pkg_resources.resource_string("invenio.testsuite", "data/response_export_arxiv_malformed.xml"), status=200, ) response = self.app.extensions["arxiv"].search("dead.beef") self.assertEqual(response.status_code, 422) TEST_SUITE = make_test_suite(TestArxiv, TestArxivQuery) if __name__ == "__main__": run_test_suite(TEST_SUITE)
for line in output.splitlines(): line = line.strip() if line: if line not in result: msg = "\nGot: %s\nMissing: \"%s\"" % (result, line) break if msg and output_bad_pdftotext: warn("Standard test failed; let's try a test amended for older pdftotext versions now. If this succeeds, please consider upgrading to the latest version of pdftotext.") msg = "" for line in output_bad_pdftotext.splitlines(): line = line.strip() if line: if line not in result: msg = "\nGot: %s\nMissing: \"%s\"" % (result, line) break if msg: return (False, msg) else: return (True, True) if 'custom' in sys.argv: from unittest import suite TEST_SUITE = suite(BibClassifyRegressionTest) else: TEST_SUITE = make_test_suite(BibClassifyRegressionTest) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
methods = [ self.get, self.put, self.delete, self.head, self.options, self.patch ] for m in methods: m( 'receivereventlistresource', urlargs=dict(receiver_id='test-receiver'), code=405, ) def test_webhook_post(self): r = Receiver(self.callable) Receiver.register('test-receiver-no-scope', r) payload = dict(somekey='somevalue') self.post( 'receivereventlistresource', urlargs=dict(receiver_id='test-receiver-no-scope'), data=payload, code=403, user_id=self.user.id, ) TEST_SUITE = make_test_suite(WebHooksTestCase, WebHooksScopesTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
# Expect both version and general handlers. out = run_py_func(main, 'inveniomanage version').out lines = out.split('\n') expected = ('>>> pre_handler_version', '>>> post_handler_version', '>>> pre_handler_general', '>>> post_handler_general') for line in expected: self.assertTrue(line in lines, "%s was not found in output %s" % (line, lines)) # Expect only general handlers. out = run_py_func(db_main, 'database uri').out lines = out.split('\n') expected = ('>>> pre_handler_general', '>>> post_handler_general') for line in expected: self.assertTrue(line in lines, "%s was not found in output %s" % (line, lines)) notexpected = ('>>> pre_handler_version', '>>> post_handler_version') for line in notexpected: self.assertFalse( line in lines, "%s was not expected in output %s" % (line, lines)) TEST_SUITE = make_test_suite(InveniomanageTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
</datafield> </record>''' def tearDown(self): from invenio.modules.formatter.registry import output_formats_lookup output_formats_lookup.expunge() del self.app.extensions['registry']['output_formats'] del self.app.extensions['registry']['format_templates'] del self.app.extensions['registry']['format_elements'] def test_format_2_passes(self): from invenio.modules.formatter import format_record result = format_record(recID=None, of="test6", xml_record=self.xml_text) self.assertEqual(result, "helloworld\n") TEST_SUITE = make_test_suite(FormatTemplateTest, OutputFormatTest, FormatElementTest, PatternTest, MiscTest, FormatTest, EscapingAndWashingTest, MarcFilteringTest, BibFormat2ndPassTest) if __name__ == '__main__': run_test_suite(TEST_SUITE)
self.assertEqual(self.app.config.get('OAUTH2_CACHE_TYPE'), 'redis') self.assertEqual(connargs['host'], "example.org") self.assertEqual(connargs['port'], 1234) self.assertEqual(connargs['db'], 2) self.assertEqual(connargs['password'], "mypw") class UtilsTestCase(InvenioTestCase): def test_urleencode(self): from invenio.modules.oauth2server.views.server import urlreencode # Test encoding of unencoded colon which oauthlib will choke on if is # not re-encoded, testurl = '/test?a=b:d&a=d' def test_fun(*args, **kwargs): pass with self.app.test_request_context(testurl): self.assertEqual(request.url, "http://localhost" + testurl) urlreencode(test_fun)() self.assertEqual(request.url, "http://localhost/test?a=b%3Ad&a=d") TEST_SUITE = make_test_suite(OAuth2ProviderTestCase, OAuth2ProviderExpirationTestCase, UtilsTestCase, RedisTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
"//input[@value='Add OAI Source']").click() self.page_source_test( expected_text= 'Please enter a valid name of or a full path to a BibConvert config file or change postprocess mode.' ) self.fill_textbox(textbox_name="oai_src_config", text="oaimarc2marcxml.xsl") self.find_element_by_xpath_with_timeout( "//input[@value='Add OAI Source']") self.browser.find_element_by_xpath( "//input[@value='Add OAI Source']").click() self.find_element_by_link_text_with_timeout( "Go back to the OAI sources overview") self.browser.find_element_by_link_text( "Go back to the OAI sources overview").click() self.page_source_test(expected_text='AtlantisOAI') self.find_element_by_link_text_with_timeout("delete") self.browser.find_element_by_link_text("delete").click() self.browser.find_element_by_class_name("adminbutton").click() self.find_element_by_link_text_with_timeout( "Go back to the OAI sources overview") self.browser.find_element_by_link_text( "Go back to the OAI sources overview").click() self.logout() TEST_SUITE = make_test_suite(InvenioOaiHarvestWebTest, ) if __name__ == '__main__': run_test_suite(TEST_SUITE, warn_user=True)
def test_detect_corruption(self): """bibdocfile - detect corruption in Md5Folder""" open(os.path.join(self.path, 'test.txt'), "w").write("test") md5s = Md5Folder(self.path) open(os.path.join(self.path, 'test.txt'), "w").write("second test") self.failIf(md5s.check('test.txt')) md5s.update(only_new=False) self.failUnless(md5s.check('test.txt')) self.assertEqual(md5s.get_checksum('test.txt'), 'f5a6496b3ed4f2d6e5d602c7be8e6b42') if False: #FIXME cfg['CFG_PATH_MD5SUM']: def test_md5_algorithms(self): """bibdocfile - compare md5 algorithms""" from invenio.legacy.bibdocfile.api import calculate_md5, \ calculate_md5_external filepath = os.path.join(self.path, 'test.txt') open(filepath, "w").write("test") self.assertEqual(calculate_md5(filepath, force_internal=True), calculate_md5_external(filepath)) TEST_SUITE = make_test_suite(BibDocFileMd5FolderTests, BibRecDocsTest, BibDocsTest, BibDocFilesTest, MoreInfoTest, BibRelationTest, BibDocFileURLTest, CheckBibDocAuthorizationTest, BibDocFsInfoTest, BibDocFileGuessFormat) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
def test_datetime_strftime_before_1900(self): new_datetime = dateutils.datetime(1765, 1, 3, 10, 2, 13) expected = "Thu, 03 Jan 1765 10:02:13 +0000" result = new_datetime.strftime("%a, %d %b %Y %H:%M:%S +0000") self.assertEqual(expected, result) def test_datatime_combine(self): expected = datetime.datetime(1987, 6, 5, 4, 3, 2, 1, None) result = dateutils.datetime.combine(datetime.date(1987, 6, 5), datetime.time(4, 3, 2, 1)) self.assertEqual(expected, result) def test_datetime_date(self): expected = datetime.date(1987, 6, 5) dt = dateutils.datetime(1987, 6, 5, 4, 3, 2, 1, None) self.assertEqual(expected, dt.date()) TEST_SUITE = make_test_suite(ConvertDateStructIntoGUI, ConvertFromDateCVSTest, ConvertIntoDateGUITest, ConvertIntoDateStructTest, ParseRuntimeLimitTest, STRFTimeTest, DateTest, DateTimeTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
)) def test_getting_of_doc_ids(self, _, recid, expected_doc_ids, expected_exception=None): with patch('invenio.legacy.bibdocfile.api.BibRecDocs', mock_BibRecDocs): get_doc_ids = common.get_doc_ids if expected_exception: self.assertRaises(expected_exception, get_doc_ids, recid) else: self.assertItemsEqual(get_doc_ids(recid), expected_doc_ids) @parameterized.expand(( # test_name , doc_id, expected_file , expceted_exception ('multiple' , 1 , '/opt/invenio/var/data/files/g1/1/bc;32;sth.xml' ), ('one' , 2 , '/opt/invenio/var/data/files/g1/2/filename;2;bar.xml'), ('fail' , 3 , None ), ('none' , 4 , None ), )) def test_getting_of_latest_file(self, _, doc_id, expected_file): with patch('glob.glob', mock_glob(doc_id)) as mocked_glob: get_latest_file = common.get_latest_file self.assertEquals(expected_file, get_latest_file(doc_id)) # self.assertEquals(mocked_glob.call_args[0], # (os.path.join("/opt/invenio/var/data/files/g0/", str(doc_id)), 'xml')) TEST_SUITE = make_test_suite(TestChanges) if __name__ == "__main__": run_test_suite(TEST_SUITE)
'Yang-Mills': 2, 'gauge field theory': 5, 'membrane model': 46}, 'Filtered Core keywords': {'Born-Infeld model': 4, 'Yang-Mills': 2, 'gauge field theory': 5, 'membrane model': 46}}}, 'fast_mode': False}, 'template': 'workflows/results/classifier.html' } output = render_template( sample_result.get("template"), results=sample_result ) beauty = BeautifulSoup(output) expected_output = [ u'\n46\nmembrane model\n', u'\n5\ngauge field theory\n', u'\n4\nBorn-Infeld model\n', u'\n2\nYang-Mills\n' ] result = [b.text for b in beauty.find_all("li")] self.assertEqual(result, expected_output) TEST_SUITE = make_test_suite(HoldingPenTests) if __name__ == "__main__": run_test_suite(TEST_SUITE)
def test_controlfield_equality(self): field = BibRecordControlField('11211') self.assertEqual(field, BibRecordControlField('11211')) self.assertNotEqual(field, BibRecordControlField('11212')) def test_get_subfield_values(self): field = BibRecordField(ind1='1', ind2='2') field.add_subfield('a', 'title') self.assertEqual(field.get_subfield_values('a'), ['title']) self.assertEqual(field['a'], ['title']) def test_find_subfields(self): field = BibRecordField(ind1='1', ind2='2') field.add_subfield('a', 'title') field.add_subfield('b', 'not title') self.assertEqual(field.find_subfields('a'), [BibRecordSubField('a', 'title')]) def test_find_subfields2(self): record = create_record(self.xml) record.add_subfield('10012b', 'not title') found_subfields = record.find_subfields('100__a') expected_subfields = [BibRecordSubField('a', 'our title')] self.assertEqual(found_subfields, expected_subfields) TEST_SUITE = make_test_suite(BibRecordTest) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
# Copyright (C) 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # 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. """Unit tests for the user handling library.""" # Note: unit tests located here were moved to the regression test # suite. Keeping this file here with empty test case set in order to # overwrite any previously installed file. Also, keeping TEST_SUITE # empty so that `inveniocfg --run-unit-tests' would not complain. #from invenio.base.wrappers import lazy_import from invenio.testsuite import make_test_suite, run_test_suite # , InvenioTestCase TEST_SUITE = make_test_suite() if __name__ == "__main__": run_test_suite(TEST_SUITE)
self.assertEqual( self.bibfield_json['field_categories'][0]['name'], self.record['field_categories'][0] ) def test_urls(self): self.assertEqual( self.bibfield_json['urls'][0]['value'], self.record['urls'][0]['value'] ) self.assertEqual( self.bibfield_json['urls'][0]['description'], self.record['urls'][0]['description'] ) def test_collections(self): self.assertEqual( self.bibfield_json['collections']['primary'], self.record['collections'][0]['primary'] ) self.assertEqual( self.bibfield_json['urls'][0]['description'], self.record['urls'][0]['description'] ) TEST_SUITE = make_test_suite(AuthorBibFieldToJSONTests) if __name__ == "__main__": run_test_suite(TEST_SUITE)
get_record_patch.return_value = r @patch('invenio.modules.pidstore.tasks.datacite.get_record') @httpretty.activate def test_sync_registered(self, get_record_patch): self.patch_get_record(get_record_patch) httpretty.register_uri( httpretty.GET, "https://mds.example.org/doi/10.1234/invenio.1234", body='http://invenio-software.org/record/1234', status=200) from invenio.modules.pidstore.tasks import datacite_sync from invenio.modules.pidstore.models import PersistentIdentifier pid = PersistentIdentifier.get("doi", "10.1234/invenio.1234") self.assertEqual(pid.status, self.app.config['PIDSTORE_STATUS_NEW']) datacite_sync(1) pid = PersistentIdentifier.get("doi", "10.1234/invenio.1234") self.assertEqual(pid.status, self.app.config['PIDSTORE_STATUS_REGISTERED']) TEST_SUITE = make_test_suite(DataCiteTasksTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
from mock import MagicMock, Mock, patch from sqlalchemy.exc import SQLAlchemyError class FormTestCase(InvenioTestCase): @patch('invenio.modules.oauthclient.forms.User') def test_validate_email(self, User): from invenio.modules.oauthclient.forms import EmailSignUpForm self.assertFalse(EmailSignUpForm(email='invalidemail').validate()) # Mock query obj = MagicMock() obj.one = MagicMock(side_effect=SQLAlchemyError()) User.query.filter = Mock(return_value=obj) self.assertTrue( EmailSignUpForm(email='*****@*****.**').validate() ) User.query.filter = MagicMock() self.assertFalse( EmailSignUpForm(email='*****@*****.**').validate() ) TEST_SUITE = make_test_suite(FormTestCase) if __name__ == "__main__": run_test_suite(TEST_SUITE)
'fieldlist': [ ['d', 'e'], ['f', 'g'] ] } form = TestForm(formdata=self.multidict(object_data)) self.assertEqual(form.data, object_data) self.assertTrue(form.validate()) form = TestForm(formdata=self.multidict(formdata)) self.assertEqual(form.data, object_data) self.assertTrue(form.validate()) # Skip these tests due to changed API # data = object_data.copy() # data['fieldlist'] = {'somefield': 'should have been a list'} # form = TestForm(formdata=self.multidict(data)) # self.assertFalse(form.validate()) # data = object_data.copy() # data['formfield'] = "should have been a dict" # form = TestForm(formdata=self.multidict(data)) # self.assertFalse(form.validate()) TEST_SUITE = make_test_suite(WebDepositFormTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
control_no = _type + CFG_BIBAUTHORITY_PREFIX_SEP + "(SzGeCERN)iii0002" recIDs = [121] self.assertEqual(get_low_level_recIDs_from_control_no(control_no), recIDs) def test_bibauthority_get_control_nos_from_recID(self): """bibauthority - test get_control_nos_from_recID()""" self.assertTrue(len(get_control_nos_from_recID(118))) def test_bibauthority_guess_main_name(self): """bibauthority - test guess_main_name_from_authority_recID()""" recID = 118 main_name = 'Ellis, John' self.assertEqual(guess_main_name_from_authority_recID(recID), main_name) def test_authority_record_string_by_control_no(self): """bibauthority - simple test of get_index_strings_by_control_no()""" # vars _type = CFG_BIBAUTHORITY_TYPE_NAMES['AUTHOR'] control_no = _type + CFG_BIBAUTHORITY_PREFIX_SEP + '(SzGeCERN)aaa0005' string = 'Ellis, Jonathan Richard' # run test self.assertTrue(string in get_index_strings_by_control_no(control_no)) TEST_SUITE = make_test_suite(BibAuthorityEngineTest, ) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
def test_task_invenio_version(self): """ Test calling of tasks """ from invenio_base.globals import cfg from invenio.celery.tasks import invenio_version # Call task function without celery self.assertEqual(invenio_version(), cfg['CFG_VERSION']) # Call task via Celery machinery self.assertEqual(invenio_version.delay().get(), cfg['CFG_VERSION']) def test_task_invenio_db_test(self): """ Test Flask request context in tasks """ from invenio.celery.tasks import invenio_db_test # Call task via Celery machinery self.assertEqual(invenio_db_test.delay(1).get(), 1) self.assertEqual(invenio_db_test.delay(2).get(), 2) self.assertEqual(invenio_db_test.delay(3).get(), 3) # Call task without Celery machinery. with self.celery_app.loader.flask_app.test_request_context(): self.assertEqual(invenio_db_test(1), 1) TEST_SUITE = make_test_suite(CeleryTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
'url': 'http://rjfreijoiregjreoijgoirg.fr' }, { 'url': 'http://1.2.3.4/' }] def cb_finished(pagegetter, check, current_time): """Function called when a page is received.""" is_ok = pagegetter.status is not None if 'content' in check and is_ok: is_ok = pagegetter.data.find(check['content']) > 0 check['result'] = is_ok == ('content' in check) pagegetters = [HTTPAsyncPageGetter(check['url']) for check in checks] finished_list = async_download(pagegetters, cb_finished, checks, 20) for (finished, check) in zip(finished_list, checks): if not finished: check['result'] = 'content' not in check errors = [check for check in checks if not check['result']] self.assertEqual(errors, []) TEST_SUITE = make_test_suite(AsyncDownloadTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)