lee-pai-long
9/25/2017 - 7:55 AM

Modularize pytest fixtures and helpers

[flake8]
...
exclude         =
    tests/__init__.py,
    tests/units/__init__.py,
    tests/fixtures/__init__.py,
    tests/helpers/__init__.py,
    tests/conftest.py
...

# External
import pytest

from my_app import mod1
from my_app.errors import UnknownLanguage

def test_mod1_greeting(name):
    
    unknown_lang = 'xx'
    pytest.helpers.assert_raised(
        mod1.greeting,
        UnknownLanguage,
        f"unknown language {unknown_lang}",
        lang=unknown_lang
    )
    assert mod1.greeting(name) == f"Hello, {name}"
    
"""Importing all necessary fixtures and helpers."""
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
#         We need to import with wildcard
#         to inject the names in the current scope
#         without having to list every fixtures and helpers
#         individually.

# Fixtures.
from tests.fixtures.fix1 import *

# Helpers.
from tests.helpers.help1 import *
# require pytest-helpers-namespace

# External
import pytest


@pytest.helpers.register
def assert_raised(func, error, message, *args, **kwargs):
    """Assert error is raise with message by func.

    :parameters:
        - func (function): The function or method to execute.
        - error (Exception): The exception expected to be raised by func.
        - message (string): The error message expected.
        - args/kwargs to pass to func.
    """
    with pytest.raises(error) as exc:
        func(*args, **kwargs)
    assert exc.value.message == message
# require pytest-faker

# External
import pytest

@pytest.fixture()
def name(faker):
    """Return a name"""
    return faker.name
tests/
├── __init__.py
├── conftest.py
├── fixtures
│   ├── __init__.py
│   ├── fix1.py
│   └── ...
├── helpers
│   ├── __init__.py
│   ├── help1.py
│   ├── ...
└── units
    ├── __init__.py
    ├── mod1_test.py