-
Notifications
You must be signed in to change notification settings - Fork 10
/
conftest.py
177 lines (144 loc) · 5.23 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015, 2016 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.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Pytest configuration."""
from __future__ import absolute_import, print_function
import os
import shutil
import tempfile
from os.path import dirname, join
import pytest
from elasticsearch.exceptions import RequestError
from flask import Flask
from flask.cli import ScriptInfo
from flask_login import LoginManager
from invenio_celery import InvenioCelery
from invenio_db import InvenioDB
from invenio_db import db as db_
from invenio_indexer import InvenioIndexer
from invenio_indexer.api import RecordIndexer
from invenio_jsonschemas import InvenioJSONSchemas
from invenio_pidstore import InvenioPIDStore
from invenio_records import InvenioRecords
from invenio_records.models import RecordMetadata
from invenio_records_rest.utils import PIDConverter, PIDPathConverter
from invenio_search import InvenioSearch, current_search
from invenio_search.errors import IndexAlreadyExistsError
from sqlalchemy_utils.functions import create_database, database_exists
from invenio_openaire import InvenioOpenAIRE
from invenio_openaire.tasks import harvest_fundref, harvest_openaire_projects
class MockSickle(object):
"""Mock of the OAI-PMH harvester.
Load the grant XML data from file and mock the Sickle datatype.
"""
def __init__(self, source):
"""Initialize the harvester."""
self.source = source
fname = join(dirname(__file__), 'testdata/mock_oai_pmh.txt')
with open(fname, 'r') as f:
self.data = f.readlines()
class MockRecordType(object):
"""Mock the OAI-PMH data type."""
def __init__(self, raw_data):
"""Init the data type."""
self.raw = raw_data
def ListRecords(self, metadataPrefix=None, set=None):
"""Record list generator."""
for grant_xml in self.data:
yield self.MockRecordType(grant_xml)
@pytest.yield_fixture()
def app(request):
"""Flask application fixture."""
# Set temporary instance path for sqlite
instance_path = tempfile.mkdtemp()
app = Flask('testapp', instance_path=instance_path)
app.config.update(
SQLALCHEMY_DATABASE_URI=os.environ.get(
'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
INDEXER_REPLACE_REFS=True,
CELERY_ALWAYS_EAGER=True,
CELERY_RESULT_BACKEND="cache",
CELERY_CACHE_BACKEND="memory",
CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
JSONSCHEMAS_HOST='inveniosoftware.org',
OPENAIRE_OAI_LOCAL_SOURCE='invenio_openaire/data/oaire_local.sqlite',
TESTING=True,
)
app.url_map.converters['pid'] = PIDConverter
app.url_map.converters['pidpath'] = PIDPathConverter
LoginManager(app)
InvenioDB(app)
InvenioIndexer(app)
InvenioRecords(app)
InvenioCelery(app)
InvenioPIDStore(app)
InvenioOpenAIRE(app)
InvenioSearch(app)
InvenioJSONSchemas(app)
with app.app_context():
yield app
shutil.rmtree(instance_path)
@pytest.yield_fixture()
def db(app):
"""Setup database."""
if not database_exists(str(db_.engine.url)):
create_database(str(db_.engine.url))
db_.create_all()
yield db_
db_.session.remove()
db_.drop_all()
@pytest.yield_fixture()
def script_info(app, db):
"""CLI object."""
with app.app_context():
yield ScriptInfo(create_app=lambda info: app)
@pytest.yield_fixture()
def es(app):
"""Provide elasticsearch access."""
try:
list(current_search.create())
except (IndexAlreadyExistsError, RequestError):
list(current_search.delete(ignore=[404]))
list(current_search.create(ignore=[400]))
yield current_search
list(current_search.delete(ignore=[404]))
@pytest.yield_fixture()
def funders(app, es, db):
"""Funder records fixture."""
harvest_fundref(source='tests/testdata/fundref_test.rdf')
@pytest.yield_fixture()
def grants(app, es, db, funders):
"""Grant records fixture."""
harvest_openaire_projects(source='tests/testdata/openaire_test.sqlite')
records = []
for record in RecordMetadata.query.all():
records.append(record.id)
RecordIndexer().index_by_id(record.id)
es.flush_and_refresh('_all')
yield records
@pytest.yield_fixture()
def sqlite_tmpdb():
"""Create a temporary sqlite database file."""
fd, path = tempfile.mkstemp("_db.sqlite")
yield path
os.remove(path)