Fixtures Reference

This page provides a reference for the available fixtures in Nanaimo. While the Nanaimo (library) guide is comprehensive it is useful only if you are writing your own fixtures. This page provides a more concise reference when writing tests using only Nanaimo’s built-in fixtures and pytest plugins.

Builtin Pytest Fixtures

A set of pytest fixtures that come with nanaimo.

Pytest logo nanaimo_arguments

nanaimo.pytest.plugin.nanaimo_arguments(request: Any) → nanaimo.Namespace[source]

Exposes the commandline arguments and defaults provided to a test.

def test_example(nanaimo_arguments: nanaimo.Namespace) -> None:
    an_argument = nanaimo_arguments.some_arg
Parameters:pytest_request (_pytest.fixtures.FixtureRequest) – The request object passed into the pytest fixture factory.
Returns:A namespace with the pytest commandline args added per the documented rules.
Return type:nanaimo.Namespace

Pytest logo nanaimo_log

nanaimo.pytest.plugin.nanaimo_log(request: Any) → logging.Logger[source]

Provides the unit tests with a logger configured for use with the Nanaimo framework.

Note

For now this is just a Python logger. Future revisions may add capabilities like the ability to log to a display or otherwise provide feedback to humans about the status of a test.

def test_example(nanaimo_log: logging.Logger) -> None:
    nanaimo_log.info('Hiya')

It’s recommended that all Nanaimo tests configure logging in a tox.ini, pytest.ini, or pyproject.toml (when this is supported). For example, the following section in tox.ini would enable cli logging for nanaimo tests:

[pytest]
log_cli = true
log_cli_level = DEBUG
log_format = %(asctime)s %(levelname)s %(name)s: %(message)s
log_date_format = %Y-%m-%d %H:%M:%S
Parameters:pytest_request (_pytest.fixtures.FixtureRequest) – The request object passed into the pytest fixture factory.
Returns:A logger for use by Nanaimo tests.
Return type:logging.Logger

Pytest logo nanaimo_fixture_manager

nanaimo.pytest.plugin.nanaimo_fixture_manager(request: Any) → nanaimo.fixtures.FixtureManager[source]

Provides a default FixtureManager to a test.

def test_example(nanaimo_fixture_manager: nanaimo.Namespace) -> None:
    common_loop = nanaimo_fixture_manager.loop
Parameters:pytest_request (_pytest.fixtures.FixtureRequest) – The request object passed into the pytest fixture factory.
Returns:A new fixture manager.
Return type:nanaimo.fixtures.FixtureManager

Builtin Nanaimo Fixtures

A set of predefined nanaimo.fixtures.Fixture types that come with nanaimo.

Pytest logo nanaimo_gather (gather)

class nanaimo.builtin.nanaimo_gather.Fixture(manager: nanaimo.fixtures.FixtureManager, args: Optional[nanaimo.Namespace] = None, **kwargs)[source]

Bases: nanaimo.fixtures.Fixture

This fixture takes a list of other fixtures and runs them concurrently returning a nanaimo.Artifacts.combine() ed set of nanaimo.Artifacts.

You can use this fixture directly in your unit tests:

async def example1() -> Artifacts:

    bar_one = nanaimo_bar.Fixture(manager)
    bar_two = nanaimo_bar.Fixture(manager)
    gather_fixture = nanaimo_gather.Fixture(manager)

    return await gather_fixture.gather(
        gather_coroutine=[
            bar_one.gather(bar_number=1),
            bar_two.gather(bar_number=2)
        ]
    )

You can also use the –gather-coroutines argument to specify fixtures by name:

nait nanaimo_gather --gather-coroutine nanaimo_bar --gather-coroutine nanaimo_bar
classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

on_gather(args: nanaimo.Namespace) → nanaimo.Artifacts[source]

Multi-plex fixture

Pytest logo nanaimo_serial_watch (lw)

class nanaimo.builtin.nanaimo_serial_watch.Fixture(manager: nanaimo.fixtures.FixtureManager, args: nanaimo.Namespace, **kwargs)[source]

Bases: nanaimo.fixtures.Fixture

Gathers a log over a serial connection until a given pattern is matched.

classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

on_gather(args: nanaimo.Namespace) → nanaimo.Artifacts[source]

Watch the logs until the pattern matches.

Returned Artifacts
key type Notes
match re.MatchObject The match if result_code is 0
matched_line str The full line matched if result_code is 0

Fixtures based on nanaimo.fixture.SubprocessFixture

class nanaimo.fixtures.SubprocessFixture(manager: nanaimo.fixtures.FixtureManager, args: Optional[nanaimo.Namespace] = None, **kwargs)[source]

Bases: nanaimo.fixtures.Fixture

Fixture base type that accepts a string argument cmd and executes it as a subprocess. Because some subprocess commands might result in huge amounts of data being sent to stdout and/or stderr this class does not capture this data by default. Instead, tests are encouraged to either filter the subprocess pipes or use the --logfile argument to write the output to a file in persistent storage.

Filtering is accomplished using the stdout_filter or stderr_filter property of this class. For example:

class MySubprocessFixture(nanaimo.fixtures.SubprocessFixture):
    '''
    Subprocess test fixture that simply calls "nait --version"
    '''

    @classmethod
    def on_visit_test_arguments(cls, arguments: nanaimo.Arguments) -> None:
        pass

    def on_construct_command(self, arguments: nanaimo.Namespace, inout_artifacts: nanaimo.Artifacts) -> str:
        return 'nait --version'


async def example(manager):

    subject = MySubprocessFixture(manager)

    # The accumulator does capture all stdout. Only use this if you know
    # the subprocess will produce a managable and bounded amount of output.
    filter = nanaimo.fixtures.SubprocessFixture.SubprocessMessageAccumulator()
    subject.stdout_filter = filter

    artifacts = await subject.gather()

    # In our example the subprocess produces only and exactly the Nanaimo
    # version number
    assert filter.getvalue() == nanaimo.version.__version__
Parameters:
  • stdout_filter – A logging.Filter used when gathering the subprocess.
  • stderr_filter – A logging.Filter used when gathering the subprocess.
class SubprocessMessageAccumulator(minimum_level: int = 20)[source]

Bases: logging.Filter, _io.StringIO

Helper class for working with SubprocessFixture.stdout_filter() or SubprocessFixture.stderr_filter(). This implementation will simply write all log messages (i.e. logging.LogRecord.getMessage()) to its internal buffer. Use getvalue() to get a reference to the buffer.

You can also subclass this method and override its logging.Filter.filter() method to customize your filter criteria.

Parameters:minimum_level – The minimum loglevel to accumulate messages for.
filter(record: logging.LogRecord) → bool[source]

Determine if the specified record is to be logged.

Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.

class SubprocessMessageMatcher(pattern: Any, minimum_level: int = 20)[source]

Bases: logging.Filter

Helper class for working with SubprocessFixture.stdout_filter() or SubprocessFixture.stderr_filter(). This implementation will watch every log message and store any that match the provided pattern.

This matcher does not buffer all logged messages.

Parameters:
  • pattern – A regular expression to match messages on.
  • minimum_level – The minimum loglevel to accumulate messages for.
match_count

The number of messages that matched the provided pattern.

filter(record: logging.LogRecord) → bool[source]

Determine if the specified record is to be logged.

Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.

classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

on_gather(args: nanaimo.Namespace) → nanaimo.Artifacts[source]
Artifacts
key type Notes
cmd str The command used to execute the subprocess.
logfile Optional[pathlib.Path] A file containing stdout, stderr, and test logs
stdout_filter

A filter used when logging the stdout stream with the subprocess.

stderr_filter

A filter used when logging the stderr stream with the subprocess.

on_construct_command(arguments: nanaimo.Namespace, inout_artifacts: nanaimo.Artifacts) → str[source]

Called by the subprocess fixture to ask the specialization to form a command given a set of arguments.

Parameters:
Returns:

The command to run in a subprocess shell.

Pytest logo nanaimo_cmd (cmd)

class nanaimo.builtin.nanaimo_cmd.Fixture(manager: nanaimo.fixtures.FixtureManager, args: Optional[nanaimo.Namespace] = None, **kwargs)[source]

Bases: nanaimo.fixtures.SubprocessFixture

Fixture that accepts a string argument cmd and executes it as a subprocess.

async def list_directory() -> Artifacts:

    cmd = nanaimo_cmd.Fixture(manager)

    return await cmd.gather(
        cmd_shell = ('dir' if os.name == 'nt' else 'ls -la')
    )
classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

on_construct_command(arguments: nanaimo.Namespace, inout_artifacts: nanaimo.Artifacts) → str[source]

Called by the subprocess fixture to ask the specialization to form a command given a set of arguments.

Parameters:
  • arguments (nanaimo.Arguments) – The arguments passed into Fixture.on_gather().
  • inout_artifacts (nanaimo.Artifacts) – A set of artifacts the superclass is assembling This is provided to the subclass to allow it to optionally contribute artifacts.
Returns:

The command to run in a subprocess shell.

Pytest logo nanaimo_scp (scp)

class nanaimo.builtin.nanaimo_scp.Fixture(manager: nanaimo.fixtures.FixtureManager, args: Optional[nanaimo.Namespace] = None, **kwargs)[source]

Bases: nanaimo.fixtures.SubprocessFixture

This fixture assumes that scp is available and functional on the system.

classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

on_construct_command(args: nanaimo.Namespace, inout_artifacts: nanaimo.Artifacts) → str[source]

Form the upload command.

Pytest logo nanaimo_ssh (ssh)

class nanaimo.builtin.nanaimo_ssh.Fixture(manager: nanaimo.fixtures.FixtureManager, args: Optional[nanaimo.Namespace] = None, **kwargs)[source]

Bases: nanaimo.fixtures.SubprocessFixture

This fixture assumes that ssh is available and functional on the system.

classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

on_construct_command(args: nanaimo.Namespace, inout_artifacts: nanaimo.Artifacts) → str[source]

Called by the subprocess fixture to ask the specialization to form a command given a set of arguments.

Parameters:
  • arguments (nanaimo.Arguments) – The arguments passed into Fixture.on_gather().
  • inout_artifacts (nanaimo.Artifacts) – A set of artifacts the superclass is assembling This is provided to the subclass to allow it to optionally contribute artifacts.
Returns:

The command to run in a subprocess shell.

Instrument Fixtures

Fixtures for popular measurement, control, and test gear.

Pytest logo nanaimo_instr_bk_precision (bk)

class nanaimo.instruments.bkprecision.Series1900BUart(manager: nanaimo.fixtures.FixtureManager, args: nanaimo.Namespace, **kwargs)[source]

Bases: nanaimo.fixtures.Fixture

Control of a 1900B series BK Precision power supply via UART.

classmethod mode_to_text(mode: int) → str[source]

Get a two-character textual representation for a given power supply mode.

UartFactoryType = typing.Callable[[typing.Union[str, pathlib.Path]], typing.Any]

The serial port factory type for this instrument.

classmethod default_serial_port(port: Union[str, pathlib.Path]) → Generator[nanaimo.connections.AbstractAsyncSerial, None, None][source]

Creates a serial connection to the given port using the default settings for a BK Precision Series 1900B power supply.

classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

is_volage_above_on_threshold(voltage: float) → bool[source]

Deprecated misspelling. See is_voltage_above_on_threshold() for correct method.

is_voltage_above_on_threshold(voltage: float) → bool[source]

Return if a given voltage is above the configured threshold for the high/on/rising voltage for this fixture.

Raises:ValueError – if no target voltage could be determined.
is_volage_below_off_threshold(voltage: float) → bool[source]

Deprecated misspelling. See is_voltage_below_off_threshold() for correct method.

is_voltage_below_off_threshold(voltage: float) → bool[source]

Return if a given voltage is below the configured threshold for the low/off/falling voltage for this fixture.

on_gather(args: nanaimo.Namespace) → nanaimo.Artifacts[source]

Send a command to the instrument and return the result. :param str command: Send one of the following commands:

Command Action Returns
‘1’ Turn on output voltage ‘OK’ or error text.
‘0’ Turn off output voltage ‘OK’ or error text
‘r’ Send a stream of <cr> characters (NA)
‘?’ Read the front panel display Display voltage, current, and status (ON or OFF)

Pytest logo nanaimo_instr_ykush (wk)

class nanaimo.instruments.ykush.Fixture(manager: nanaimo.fixtures.FixtureManager, args: Optional[nanaimo.Namespace] = None, **kwargs)[source]

Bases: nanaimo.fixtures.SubprocessFixture

Fixture for controlling Yepkit USB hubs with switchable power. For example the YKUSH3 is a 3-port USB-3 hub that allows individual control of the power rails for each port.

This is a subprocess fixture that requires the ykushcmd program is available in the subprocess environment (see Yepkit’s documentation for how to build this from source). All arguments can be overridden via the fixtures gather method. The supported commands are:

command example Description
yku-all-on await nanaimo_instr_ykush.gather(yku_all_on=True) Turn on power to all ports on the YKUSH.
yku-all-off await nanaimo_instr_ykush.gather(yku_all_off=True) Turn off power to all ports on the YKUSH.
yku-command await nanaimo_instr_ykush.gather(yku_command='-l') Pass-through any command to ykushcmd.
classmethod on_visit_test_arguments(arguments: nanaimo.Arguments) → None[source]

Called by the environment before instantiating any nanaimo.fixtures.Fixture instances to register arguments supported by each type. These arguments should be portable between both argparse and pytest. The fixture is registered for this callback by returning a reference to its type from a pytest_nanaimo_fixture_type hook in your fixture’s pytest plugin module.

on_construct_command(arguments: nanaimo.Namespace, inout_artifacts: nanaimo.Artifacts) → str[source]