-
Notifications
You must be signed in to change notification settings - Fork 22
/
test_fixtures.py
391 lines (321 loc) · 12.7 KB
/
test_fixtures.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# -*- coding: utf-8 -*-
#
# This file is part of pytest-invenio.
# Copyright (C) 2017-2018 CERN.
#
# pytest-invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
from __future__ import absolute_import, print_function
import os
import pytest
def test_version():
"""Test version import."""
from pytest_invenio import __version__
assert __version__
def test_instance_path(testdir):
"""Test instance path."""
assert 'INVENIO_INSTANCE_PATH' not in os.environ
testdir.makepyfile("""
import os
def test_instance_path(instance_path):
assert os.environ['INVENIO_INSTANCE_PATH'] == instance_path
assert os.path.exists(instance_path)
assert os.path.isdir(instance_path)
""")
testdir.runpytest().assert_outcomes(passed=1)
assert 'INVENIO_INSTANCE_PATH' not in os.environ
def test_db_uri(testdir):
"""Test default db uri."""
testdir.makepyfile("""
import os
def test_db_uri(db_uri, instance_path):
assert 'SQLALCHEMY_DATABASE_URI' not in os.environ
assert db_uri.startswith('sqlite:///{}'.format(instance_path))
""")
testdir.runpytest().assert_outcomes(passed=1)
def test_db_uri_env(testdir, monkeypatch):
"""Test db uri defined in environment variable."""
monkeypatch.setenv('SQLALCHEMY_DATABASE_URI', 'sqlite://')
testdir.makepyfile("""
def test_db_uri(db_uri):
assert db_uri == 'sqlite://'
""")
testdir.runpytest().assert_outcomes(passed=1)
monkeypatch.undo()
def test_broker_uri(testdir):
"""Test default broker uri."""
testdir.makepyfile("""
import os
def test_broker_uri(broker_uri):
assert 'BROKER_URL' not in os.environ
assert broker_uri == 'amqp://guest:guest@localhost:5672//'
""")
testdir.runpytest().assert_outcomes(passed=1)
def test_broker_uri_env(testdir, monkeypatch):
"""Test default broker uri."""
monkeypatch.setenv('BROKER_URL', 'env-value')
testdir.makepyfile("""
def test_broker_uri(broker_uri):
assert broker_uri == 'env-value'
""")
testdir.runpytest().assert_outcomes(passed=1)
monkeypatch.undo()
def test_app_config(testdir):
"""Test application and celery config."""
testdir.makepyfile(test_app="""
def test_app_config(app_config, db_uri, broker_uri):
assert app_config['SQLALCHEMY_DATABASE_URI'] == db_uri
assert app_config['BROKER_URL'] == broker_uri
assert app_config['SECRET_KEY'] == 'test-secret-key'
assert app_config['CELERY_ALWAYS_EAGER'] == True
""")
# Test that application fixture can be overwritten in each module.
testdir.makepyfile(test_app_overwrite="""
import pytest
@pytest.fixture()
def app_config(app_config):
app_config.update({
'MYSTUFF': True
})
return app_config
def test_app_config(app_config, db_uri, broker_uri):
assert app_config['SQLALCHEMY_DATABASE_URI'] == db_uri
assert app_config['MYSTUFF']
""")
testdir.runpytest().assert_outcomes(passed=2)
def test_base_app(conftest_testdir):
"""Test application factories."""
# `conftest_testdir` defines a create_app fixture which are used by
# base_app fixture to create a Flask application and inject the
# configuration into the application.
conftest_testdir.makepyfile("""
def test_base_app(base_app, db_uri):
assert base_app.config['SQLALCHEMY_DATABASE_URI'] == db_uri
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_base_client_jsonresponse(conftest_testdir):
"""Test the test client and json attribute on response object."""
conftest_testdir.makepyfile("""
def test_base_app(base_app, base_client):
res = base_client.get('/api/')
res.json == {'app_name': base_app.name}
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_appctx(conftest_testdir):
"""Test application factories."""
conftest_testdir.makepyfile("""
from flask import current_app
def test_appctx(base_app, appctx):
assert base_app.name == current_app.name
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_script_info(conftest_testdir):
"""Test script info command."""
conftest_testdir.makepyfile("""
import click
from click.testing import CliRunner
from flask import current_app
from flask.cli import with_appcontext
# Define a command which requires app context
@click.command()
@with_appcontext
def mycmd():
click.echo(current_app.name)
# Run test on just defined CLI command.
def test_cli(script_info, base_app):
runner = CliRunner()
result = runner.invoke(mycmd, obj=script_info)
assert result.exit_code == 0
assert result.output.startswith(base_app.name)
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_clirunner(conftest_testdir):
"""Test script info command."""
conftest_testdir.makepyfile("""
import click
from flask import current_app
from flask.cli import with_appcontext
# Define a command which requires app context
@click.command()
@with_appcontext
def mycmd():
click.echo(current_app.name)
# Run test on just defined CLI command.
def test_cli(cli_runner):
assert cli_runner(mycmd).exit_code == 0
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_clirunner_output(conftest_testdir):
"""Test script info command."""
conftest_testdir.makepyfile("""
import click
from flask import current_app
from flask.cli import with_appcontext
# Define a command which logs to the application logger
@click.command()
@with_appcontext
def mycmd():
current_app.logger.error('My error')
# Run test that output is captured
def test_cli(cli_runner):
res = cli_runner(mycmd)
assert 'My error' in res.output
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_es(conftest_testdir):
"""Test Elasticsearch initialization."""
conftest_testdir.makepyfile("""
def test_es(es):
assert es.ping()
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_es_clear(conftest_testdir):
"""Test Elasticsearch clearing."""
# Create an Elasticsearch mapping for Invenio-Search
conftest_testdir.mkpydir('data')
conftest_testdir.mkpydir('data/v5')
conftest_testdir.mkdir('data/v5/demo')
with open('data/v5/demo/default-v1.0.0.json', 'w') as fp:
fp.write("""{"mappings": { "example": { "properties": { "title": {
"type": "string",
"fielddata": true
}}}}}""")
# Create test
conftest_testdir.makepyfile("""
import pytest
from elasticsearch.exceptions import NotFoundError
from invenio_search import current_search_client, current_search
# Just a UUID
doc_id = 'deadbeef-dae9-4c19-9b7c-49056374bc6c'
@pytest.fixture(scope='module')
def base_app(base_app):
# Registers the Elasticsearch mapping on the application
search = base_app.extensions['invenio-search']
search.register_mappings('demo', 'data')
return base_app
def test_es1(es, es_clear):
# Index a document
current_search_client.index(
index='demo-default-v1.0.0',
doc_type='demo-default-v1.0.0',
id=doc_id,
body={'title': 'Test'},
op_type='create',
)
# Wait for document to be available
current_search.flush_and_refresh('demo-default-v1.0.0')
# Get the document (will raise exception if not found)
current_search_client.get(
index='demo-default-v1.0.0',
id=doc_id,
)
def test_es2(es):
# Get the document create in test above (should not be possible)
pytest.raises(
NotFoundError,
current_search_client.get,
index='demo-default-v1.0.0',
id=doc_id,
)
# But the index should exist
assert current_search_client.indices.exists(
index='demo-default-v1.0.0')
""")
conftest_testdir.runpytest().assert_outcomes(passed=2)
def test_database(conftest_testdir):
"""Test database creation and initialization."""
conftest_testdir.makepyfile("""
def test_database(database, db_uri):
assert str(database.engine.url) == db_uri
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_db(conftest_testdir):
"""Test database creation and initialization."""
conftest_testdir.makepyfile("""
from invenio_db import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
def test_db1(db):
assert User.query.count() == 0
db.session.add(User(username='alice'))
db.session.commit()
assert User.query.count() == 1
def test_db2(db):
assert User.query.count() == 0
db.session.add(User(username='alice'))
db.session.add(User(username='bob'))
db.session.commit()
assert User.query.count() == 2
""")
conftest_testdir.runpytest().assert_outcomes(passed=2)
def test_app(conftest_testdir):
"""Test database creation and initialization."""
conftest_testdir.makepyfile("""
from invenio_db import db
from invenio_search import current_search_client
class Place(db.Model):
id = db.Column(db.Integer, primary_key=True)
def test_app(app):
assert Place.query.count() == 0
assert current_search_client.ping()
""")
conftest_testdir.runpytest().assert_outcomes(passed=1)
def test_mailbox(conftest_testdir):
"""Test database creation and initialization."""
conftest_testdir.makepyfile(test_mailbox="""
def test_mailbox(appctx, mailbox):
assert len(mailbox) == 0
appctx.extensions['mail'].send_message(
sender='no-reply@localhost',
subject='testing',
body='test',
recipients=['no-reply@localhost'],)
assert len(mailbox) == 1
""")
# Test what happens if Invenio-Mail is not installed.
conftest_testdir.makepyfile(test_mailbox_fail="""
import pytest
@pytest.fixture(scope='module')
def base_app(base_app):
del base_app.extensions['mail']
return base_app
def test_mailbox(appctx, mailbox):
pass # Will never reach here.
""")
conftest_testdir.runpytest().assert_outcomes(passed=1, error=1)
def test_browser_skipped(conftest_testdir):
"""Test that end-to-end tests are skipped unless E2E env var is set."""
conftest_testdir.makepyfile("""
def test_browser(live_server, browser):
browser.get(url_for('index', _external=True))
""")
conftest_testdir.runpytest().assert_outcomes(skipped=1)
def test_browser(conftest_testdir, monkeypatch):
"""Test live server and selenium."""
monkeypatch.setenv('E2E', 'yes')
monkeypatch.setenv('E2E_OUTPUT', 'file')
conftest_testdir.makepyfile(test_browsers="""
from flask import url_for
def test_browser(live_server, browser):
browser.get(url_for('index', _external=True))
assert browser.title == 'pytest-invenio'
def test_browser_fail(live_server, browser):
browser.get(url_for('index', _external=True))
assert browser.title != 'pytest-invenio'
""")
conftest_testdir.runpytest().assert_outcomes(passed=1, failed=1)
assert os.path.exists(
os.path.join(str(conftest_testdir.tmpdir), '.e2e_screenshots'))
monkeypatch.undo()
def test_celery_config(testdir):
"""Test celery config."""
testdir.makepyfile(test_app="""
def test_celery_config_with_celery(celery_config):
assert celery_config['CELERY_ALWAYS_EAGER'] == True
assert celery_config['CELERY_CACHE_BACKEND'] == 'memory'
assert celery_config['CELERY_EAGER_PROPAGATES_EXCEPTIONS'] == True
assert celery_config['CELERY_RESULT_BACKEND'] == 'cache'
""")
testdir.runpytest().assert_outcomes(passed=1)