API Docs

Fixtures

Pytest fixtures for Invenio.

class pytest_invenio.fixtures.MockDistribution(extra_entry_points)[source]

A mocked distribution that we can inject entry points with.

Initialise the extra entry point.

class pytest_invenio.fixtures.MockImportlibDistribution(extra_entry_points)[source]

A mocked distribution where we can inject entry points.

Entry points for the distribution.

property entry_points

Iterate over entry points.

property name

Return the ‘Name’ metadata for the distribution package.

pytest_invenio.fixtures.UserFixture()[source]

Fixture to help create user fixtures.

Scope: session

@pytest.fixture()
def myuser(UserFixture, app, db):
    u = UserFixture(
        email="myuser@inveniosoftware.org",
        password="auser",
    )
    u.create(app, db)
    return u

def test_with_user(service, myuser):
    service.dosomething(myuser.identity)
pytest_invenio.fixtures.app(base_app, search, database)[source]

Invenio application with database and search.

Scope: module

See also base_app for an Invenio application fixture that does not initialize database and search.

pytest_invenio.fixtures.app_config(db_uri, broker_uri, celery_config_ext)[source]

Application configuration fixture.

Scope: module

This fixture sets default configuration for an Invenio application to make it suitable for testing. The database and broker URL are injected into the config, CSRF-protection in forms disabled, HTTP secure headers is disabled, mail sending is output to console.

The fixture can easily be customized in your conftest.py or specific test module:

# conftest.py
import pytest

pytest.fixture(scope='module')
def app_config(app_config):
    app_config['MYVAR'] = 'test'
    return app_config
pytest_invenio.fixtures.appctx(base_app)[source]

Application context for the current base application.

Scope: module

This fixture pushes an application context on the stack, so that current_app is defined and e.g url_for will also work.

pytest_invenio.fixtures.base_app(create_app, app_config, request, default_handler)[source]

Base application fixture (without database, search and cache).

Scope: module.

This fixture is responsible for creating the Invenio application. It depends on an application factory fixture that must be defined by the user.

# confest.py
import pytest

@pytest.fixture(scope='module)
def create_app():
    from invenio_app.factory import create_api
    return create_api

It is possible to overide the application factory for a specific test module, either by defining a fixture like above example, or simply setting the create_app property on the module:

# test_something.py

from invenio_app.factory import create_api
create_app = create_api

def test_acase(base_app):
    # ...
pytest_invenio.fixtures.base_client(base_app)[source]

Test client for the base application fixture.

Scope: function

If you need the database and search indexes initialized, simply use the Pytest-Flask fixture client instead. This fixture is mainly useful if you need a test client without needing to initialize both the database and search indexes.

pytest_invenio.fixtures.broker_uri()[source]

Broker URI (defaults to an RabbitMQ on localhost).

Scope: module

The broker can be overwritten by setting the BROKER_URL environment variable.

pytest_invenio.fixtures.browser(request)[source]

Selenium webdriver fixture.

Scope: session

The fixture initializes a Selenium webdriver which can be used for end-to-end testing of your application:

from flask import url_for

def test_browser(live_server, browser):
    browser.get(url_for('index', _external=True))

The live_server fixture is provided by Pytest-Flask and uses the app fixture to determine which application to start.

Note

End-to-end test are only executed if the environment variable E2E is set to yes:

$ export E2E=yes

This allows you to easily switch on/off end-to-end tests.

By default, a Chrome webdriver client will be created. However, you can customize which browsers to test via the E2E_WEBDRIVER_BROWSERS environment variable:

$ export E2E_WEBDRIVER_BROWSERS="Chrome Firefox"

If multiple browsers are requested, each test case using the browser fixture will be parameterized with the list of browsers.

In case the test fail, a screenshot will be taken and saved in folder .e2e_screenshots.

pytest_invenio.fixtures.bucket_from_dir(db, location)[source]

Creates a bucket from the specified directory.

Scope: function

Use this fixture if your test requires a files bucket. The bucket_from_dir fixture returns a function with the following signature:

def create_bucket_from_dir(source_dir, location_obj=None):
    """Create bucket from the specified source directory.

    :param source_dir: The directory to create the bucket from.
    :param location_obj: Optional location object to use. If None
        is specified, get the current default location.
    :returns: The new bucket object.
    """

Below is an example of how to use the bucket_from_dir fixture:

def test_with_bucket(bucket_from_dir):
    bucket = bucket_from_dir('/my/directory/path')
    # ... use the bucket for your test
pytest_invenio.fixtures.celery_config()[source]

Empty celery config.

pytest_invenio.fixtures.celery_config_ext(celery_config)

Celery configuration (defaults to eager tasks).

Scope: module

This fixture provides the default Celery configuration (eager tasks, in-memory result backend and exception propagation). It can easily be overwritten in a specific test module:

# test_something.py
import pytest

pytest.fixture(scope='module')
def celery_config_ext(celery_config_ext):
    celery_config_ext['CELERY_TASK_ALWAYS_EAGER'] = False
    return celery_config_ext
pytest_invenio.fixtures.cli_runner(base_app)[source]

Create a CLI runner for testing a CLI command.

Scope: module

def test_cmd(cli_runner):
    result = cli_runner(mycmd)
    assert result.exit_code == 0
pytest_invenio.fixtures.database(appctx)[source]

Setup database.

Scope: module

Normally, tests should use the function-scoped db fixture instead. This fixture takes care of creating the database/tables and removing the tables once tests are done.

pytest_invenio.fixtures.db(database)[source]

Creates a new database session for a test.

Scope: function

You must use this fixture if your test connects to the database. The fixture will set a save point and rollback all changes performed during the test (this is much faster than recreating the entire database).

pytest_invenio.fixtures.db_uri(instance_path)[source]

Database URI (defaults to an SQLite datbase in the instance path).

Scope: module

The database can be overwritten by setting the SQLALCHEMY_DATABASE_URI environment variable to a SQLAlchemy database URI.

pytest_invenio.fixtures.default_handler()[source]

Flask default logging handler.

Flask 0.13/1.0 changed logging to not add the default handler in case a handler is already installed. pytest automatically adds a handler to the root logger, causing Flask not to add a handler. This is an issue when testing Click output which uses the logger to output to the console.

pytest_invenio.fixtures.entry_points(extra_entry_points)[source]

Entry points fixture.

Scope: module

Invenio relies heavily on Python entry points for constructing an application and it can be rather cumbersome to try to register database models, search mappings etc yourself afterwards.

This fixture allows you to inject extra entry points into the application loading, so that you can load e.g. a testing module or test mapping.

To use the fixture simply define the extra_entry_points() fixture, and then depend on the entry_points() fixture in your create_app fixture:

@pytest.fixture(scope="module")
def extra_entry_points():
    return {
        'invenio_db.models': [
            'mock_module = mock_module.models',
        ]
    }

@pytest.fixture(scope="module")
def create_app(instance_path, entry_points):
    return _create_api
pytest_invenio.fixtures.es(search)[source]

Alias for search fixture.

pytest_invenio.fixtures.es_clear(search_clear)[source]

Alias for search_clear fixture.

pytest_invenio.fixtures.extra_entry_points()[source]

Extra entry points.

Overwrite this fixture to define extra entry points.

pytest_invenio.fixtures.instance_path()[source]

Temporary instance path.

Scope: module

This fixture creates a temporary directory and sets the INSTANCE_PATH environment variable to this directory. The directory is automatically removed.

pytest_invenio.fixtures.location(database)[source]

Creates a simple default location for a test.

Scope: function

Use this fixture if your test requires a files location. The location will be a default location with the name pytest-location.

pytest_invenio.fixtures.mailbox(base_app)[source]

Mailbox fixture.

Scope: function

This fixture provides a mailbox that captures all outgoing emails and thus easily allow you to test mail sending in your app:

def test_mailbox(appctx, mailbox):
    appctx.extensions['mail'].send_message(
        sender='no-reply@localhost',
        subject='Testing',
        body='Test',
        recipients=['no-reply@localhost'])
    assert len(mailbox) == 1
pytest_invenio.fixtures.script_info(base_app)[source]

Get ScriptInfo object for testing a CLI command (DEPRECATED).

Scope: module

Use the cli_runner runner fixture directly, or use the base_app:

pytest_invenio.fixtures.search(appctx)[source]

Setup and teardown all registered search indices.

Scope: module

This fixture will create all registered indexes in search and remove once done. Fixtures that perform changes (e.g. index or remove documents), should used the function-scoped search_clear fixture to leave the indexes clean for the following tests.

pytest_invenio.fixtures.search_clear(search)[source]

Clear search indices after test finishes (function scope).

Scope: function

This fixture rollback any changes performed to the indexes during a test, in order to leave search in a clean state for the next test.

Plugin

Pytest plugin for Invenio.

The plugin adds fixtures to help with creation of applications as well as configuring and initializing the database and search engine.

Additional the plugin helps with configuring end-to-end tests with selenium and taking screenshots of failed selenium tests (useful for inspecting why the test failed on CI systems).

pytest_invenio.plugin.pytest_generate_tests(metafunc)[source]

Skip end-to-end tests unless requested via E2E env variable.

A screenshot is taken in case of test failures. Set the environment variable E2E_OUTPUT to base64 to have the base64 encoded screenshot printed to stdout (useful in e.g. CI systems). Screenshots are saved to an .e2e_screenshots folder.

Overrides pytest’s default test collection function to skip tests using the browser fixture, unless the environment variable E2E is set to yes.

Each test using the browser fixture is parameterized with the list of browsers declared by the E2E_WEBDRIVER_BROWSERS environment variable. By default only Chrome is tested.

pytest_invenio.plugin.pytest_runtest_makereport(item, call)[source]

Add hook to track if the test passed or failed.