### Adding Assertions to Slash Tests (Python) Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This example illustrates how to incorporate simple 'assert' statements within Slash tests to verify conditions. Slash enhances these assertions with assertion rewriting, providing more detailed failure information upon test execution. ```python # test_addition.py def test_addition(): assert 2 + 2 == 4 ``` -------------------------------- ### Adding Cleanups to Slash Tests with `slash.add_cleanup` (Python) Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This example illustrates how to register cleanup functions using `slash.add_cleanup`. These functions are guaranteed to be called whenever a test finishes, regardless of its success or failure, ensuring proper resource deallocation. Cleanups can also be configured to run only on successful test completion using `success_only=True`. ```python def test_product_power_on_sequence(): product = ... product.plug_to_outlet() slash.add_cleanup(product.plug_out_of_outlet) product.press_power() slash.add_cleanup(product.wait_until_off) slash.add_cleanup(product.press_power) slash.add_cleanup(product.pack_for_shipping, success_only=True) product.wait_until_on() ``` -------------------------------- ### Toggling Boolean Parameters in Slash Tests (Python) Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This example showcases the `@slash.parameters.toggle` decorator, which provides a convenient shortcut for parametrizing a test with boolean values. It automatically creates two test cases, one where the specified parameter is `True` and another where it is `False`. ```python @slash.parameters.toggle('with_power_operator') def test_power_of_two(with_power_operator): num = 2 if with_power_operator: result = num ** 2 else: result = num * num assert result == 4 ``` -------------------------------- ### Defining a Basic Test Function in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet demonstrates the minimal structure for a test function in Slash. Tests are loaded from Python files, and only functions prefixed with 'test_' are recognized as runnable tests, similar to 'unittest' and 'py.test'. ```python # test_addition.py import slash def test_addition(): pass ``` -------------------------------- ### Running Slash Tests from the Command Line (Bash) Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This command-line snippet shows how to execute a Slash test file. The 'slash run' command automatically finds, loads, and runs the specified tests, reporting the results within a single execution referred to as a 'session'. ```bash $ slash run test_addition.py ``` -------------------------------- ### Using the Global Slash Logger (Python) Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet demonstrates how to use the global logger provided by Slash for basic logging tasks within tests. Slash integrates with Logbook, offering a flexible and powerful logging solution for capturing test execution details. ```python import slash def test_1(): slash.logger.debug("Hello!") ``` -------------------------------- ### Storing Additional Test Details with slash.set_test_detail in Python Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet illustrates how to use `slash.set_test_detail` to associate key-value pairs with a test. These details are printed in the test summary if the test fails, aiding in investigation. Each test maintains its own unique storage. ```python def test_one(): slash.set_test_detail('log', '/var/log/foo.log') slash.set_error("Some condition is not met!") def test_two(): # Every test has its own unique storage, so it's possible to use the same key in multiple tests slash.set_test_detail('log', '/var/log/bar.log') ``` -------------------------------- ### Creating and Installing a Slash Log Collection Plugin (Python) Source: https://github.com/getslash/slash/blob/develop/doc/customizing_slash.rst This example shows how to encapsulate log collection logic within a Slash plugin, making the behavior optional and modular. The `LogCollectionPlugin` class inherits from `slash.plugins.PluginInterface`, defines a `get_name` method, and implements `session_end`, which automatically registers to the `slash.session_end` hook upon plugin activation. The snippet also demonstrates how to instantiate and install the plugin using `plugins.manager.install`. ```Python ... class LogCollectionPlugin(slash.plugins.PluginInterface): def get_name(self): return 'logcollector' def session_end(self): shutil.copytree( slash.session.logging.session_log_path, os.path.join('/remote/path', slash.session.id)) collector_plugin = LogCollectionPlugin() plugins.manager.install(collector_plugin) ``` -------------------------------- ### Basic Slash Plugin .slashrc File Example (Python) Source: https://github.com/getslash/slash/blob/develop/doc/customizing_slash.rst This snippet provides a minimal example of a .slashrc file, which is used to configure Slash. In this context, it serves as a placeholder for where the full plugin code would reside, demonstrating the basic structure of such a file. ```python import os ``` -------------------------------- ### Repeating Tests with @slash.repeat Decorator in Python Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet shows how to use the `@slash.repeat` decorator to execute a test function multiple times. This is useful for probabilistic tests or to ensure stability over several runs. ```python @slash.repeat(5) def test_probabilistic(): assert still_works() ``` -------------------------------- ### Parametrizing Slash Tests with `slash.parametrize` (Python) Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet demonstrates how to parametrize a test function using the `@slash.parametrize` decorator. It allows the test to be executed multiple times, iterating through a list of values for a specified parameter, creating separate test cases for each value. ```python @slash.parametrize('x', [1, 2, 3]) def test_something(x): # use x here ``` -------------------------------- ### Skipping Tests with slash.skip_test in Python Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet demonstrates how to programmatically skip a test by calling `slash.skip_test` within a test function. It's useful for conditional skipping based on runtime conditions, such as checking a device model. ```python def test_microwave_has_supercool_feature(): if microwave.model() == "Microtech Shitbox": slash.skip_test("Microwave model too old") ``` -------------------------------- ### Defining a Customization Function in Slash Source: https://github.com/getslash/slash/blob/develop/doc/advanced_usage.rst This snippet defines a Python function `cool_customization_logic` which serves as a placeholder for custom Slash configuration, such as installing plugins or changing settings. This function is intended to be registered as a Setuptools entry point for global customization, allowing Slash to automatically discover and execute it on startup. ```Python def cool_customization_logic(): ... # install plugins here, change configuration, etc... ``` -------------------------------- ### Defining Test Requirements with @slash.requires (Function) in Python Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet shows how to use the `@slash.requires` decorator with a function that returns a boolean value. If the function returns `False`, the test is skipped before execution, indicating an unmet precondition. ```python def is_some_condition_met(): return True @slash.requires(is_some_condition_met) def test_something(): ... ``` -------------------------------- ### Skipping Tests with @slash.skipped Decorator in Python Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet illustrates how to use the `@slash.skipped` decorator to mark a test function as skipped. It can be used with or without a reason string, providing a declarative way to skip tests. ```python @slash.skipped("reason") def test_1(): # ... @slash.skipped # no reason def test_2(): # ... ``` -------------------------------- ### Implementing Slash Product Testing Plugin (Python) Source: https://github.com/getslash/slash/blob/develop/doc/customizing_slash.rst The `ProductTestingPlugin` extends Slash's functionality to support product-specific testing. It defines a default API timeout, allows users to specify a target IP address via command-line arguments, and initializes a global `Target` object with the configured address and timeout at the start of the session. ```Python @slash.plugins.active class ProductTestingPlugin(slash.plugins.PluginInterface): def get_name(self): return 'your product' def get_default_config(self): return {'api_timeout_seconds': 50} def configure_argument_parser(self, parser): parser.add_argument('-t', '--target', help='ip address of the target to test') def configure_from_parsed_args(self, args): self.target_address = args.target def session_start(self): slash.g.target = Target( self.target_address, timeout=slash.config.root.plugin_config.your_product.api_timeout_seconds) ``` -------------------------------- ### Creating Autouse Session-Scoped Fixtures in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This example defines an `autouse` fixture that is automatically applied to tests without explicit declaration, scoped to the entire session. It creates a temporary directory at the start of the session and ensures its removal using a cleanup function registered with `this.add_cleanup` when the session concludes. ```Python @slash.fixture(autouse=True, scope='session') def temp_dir(): """Create a temporary directory""" directory = '/some/directory' os.makedirs(directory) @this.add_cleanup def cleanup(): shutil.rmtree(directory) ``` -------------------------------- ### Parametrizing a Test Function with slash.parametrize (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Demonstrates how to use the `@slash.parametrize` decorator to create multiple test cases from a single test function by iterating over a list of values for a specified parameter. This example generates three test cases for the 'x' parameter. ```python @slash.parametrize('x', [1, 2, 3]) def test_something(x): pass ``` -------------------------------- ### Running Slash Tests Programmatically Source: https://github.com/getslash/slash/blob/develop/doc/advanced_usage.rst This Python snippet illustrates how to programmatically load and execute Slash tests within a controlled environment. It initializes a `slash.Session`, uses `slash.loader.Loader().get_runnables` to discover tests from specified paths, and then executes them using `slash.run_tests` within the session's started context. ```Python import slash from slash.loader import Loader if __name__ == "__main__": with slash.Session() as session: tests = Loader().get_runnables(["/my_path", ...]) with session.get_started_context(): slash.run_tests(tests) ``` -------------------------------- ### Defining Test Requirements with @slash.requires (Function and Message) in Python Source: https://github.com/getslash/slash/blob/develop/doc/tour.rst This snippet demonstrates how to use the `@slash.requires` decorator with a function and an explicit `message` parameter. If the requirement function returns `False`, the specified message will be displayed in the test summary, providing more context for the unmet condition. ```python @slash.requires(is_some_condition_met, message='My condition is not met!') def test_something(): ... ``` -------------------------------- ### Defining Hook-Level Plugin Dependencies in Slash Source: https://github.com/getslash/slash/blob/develop/doc/plugins.rst This example illustrates how to establish dependencies between specific plugin hook methods using `@slash.plugins.provides` and `@slash.plugins.needs` decorators. The `TestIdentificationLoggingPlugin`'s `test_start` hook is ensured to run only after `TestIdentificationPlugin`'s `test_start` hook, which provides the 'awesome_test_id' identifier. This ensures proper execution order for interdependent plugin functionalities. ```Python class TestIdentificationPlugin(PluginInterface): @slash.plugins.provides('awesome_test_id') def test_start(self): slash.context.test.awesome_test_id = awesome_id_allocation_service() class TestIdentificationLoggingPlugin(PluginInterface): @slash.plugins.needs('awesome_test_id') def test_start(self): slash.logger.debug('Test has started with the awesome id of {!r}', slash.context.test.awesome_id) ``` -------------------------------- ### Parametrizing Test Class Methods with slash.parametrize (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Illustrates applying `@slash.parametrize` to `before`, `test`, and `after` methods within a test class. This creates a Cartesian product of all parameter values, significantly multiplying the number of runnable test cases. In this example, 27 tests are generated. ```python class SomeTest(Test): @slash.parametrize('x', [1, 2, 3]) def before(self, x): # ... @slash.parametrize('y', [4, 5, 6]) def test(self, y): # ... @slash.parametrize('z', [7, 8, 9]) def after(self, z): # ... ``` -------------------------------- ### Programmatically Creating a Slash Session (Python) Source: https://github.com/getslash/slash/blob/develop/doc/internals.rst This example demonstrates how to programmatically create and manage a slash.Session instance using a 'with' statement. While typically handled automatically by Slash, this method allows for manual session control, useful in interpreter environments or for custom test runners. ```python from slash import Session ... with slash.Session() as s: ... # <--- in this context, s is the active session ``` -------------------------------- ### Defining Session-Scoped Fixtures in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This example illustrates how to create a fixture with a 'session' scope, meaning it is activated once at the beginning of the test session and lives until the session ends. It includes a cleanup function registered with `this.add_cleanup` that executes when the session concludes. ```Python @slash.fixture(scope='session') def some_session_fixture(this): @this.add_cleanup def cleanup(): print('Hurray! the session has ended') ``` -------------------------------- ### Creating Parametrized Generator Fixtures with slash.generator_fixture (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This example illustrates the use of `@slash.generator_fixture` as a concise way to define a fixture that yields multiple values, effectively acting as a single parametrization. The `model_types` fixture iterates through `all_model_configs` and yields the `type` of supported models. ```python @slash.generator_fixture def model_types(): for model_config in all_model_configs: if model_config.supported: yield model_config.type ``` -------------------------------- ### Overriding Slash Configuration via Command-Line Source: https://github.com/getslash/slash/blob/develop/doc/configuration.rst This snippet demonstrates how to override Slash configuration values directly from the command line using the -o flag with slash run. It shows an example of setting hooks.swallow_exceptions to yes. Configuration values are automatically converted to their respective types. ```Shell $ slash run -o hooks.swallow_exceptions=yes ... ``` -------------------------------- ### Testing for Near Equality with slash.assert_almost_equal Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This example demonstrates `slash.assert_almost_equal`, a utility function for checking if two floating-point numbers are approximately equal within a specified maximum delta. This is crucial for comparing floating-point results due to precision issues. ```Python slash.assert_almost_equal(1.001, 1, max_delta=0.1) ``` -------------------------------- ### Reusing Pre-defined Tag Decorators (Python) Source: https://github.com/getslash/slash/blob/develop/doc/tags.rst This example shows how to create a reusable tag decorator by assigning `slash.tag('dangerous')` to a variable. This pre-defined decorator can then be applied to multiple test functions, simplifying tag management and promoting consistency. ```python dangerous = slash.tag('dangerous') ... @dangerous def test_something(): ... ``` -------------------------------- ### Configuring Slack Notifications in Slash (Shell) Source: https://github.com/getslash/slash/blob/develop/doc/builtin_plugins.rst This command activates Slack notifications in Slash, setting the webhook URL and the target channel or user. It requires prior Slack webhook integration setup and is used to send session end alerts to a Slack channel or user. ```Shell slash run --with-notifications -o plugin_config.notifications.slack.url='your-webhook-ingetration-url' -o plugin_config.notifications.slack.channel='@myslackuser' ``` -------------------------------- ### Handling Missing Expected Exceptions with slash.assert_raises Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This example illustrates that `slash.assert_raises` will raise an `ExpectedExceptionNotCaught` exception if the anticipated exception is not raised within the `with` block, indicating a test failure. ```Python >>> with slash.assert_raises(Exception) as caught: # doctest: +IGNORE_EXCEPTION_DETAIL ... pass Traceback (most recent call last): ... ExpectedExceptionNotCaught: ... ``` -------------------------------- ### Nesting Slash's Exception Handling Context (Python) Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This example illustrates how `slash.exception_handling.handling_exceptions` contexts can be safely nested. Once an exception is handled by an inner context, it is marked, preventing outer contexts from re-handling the same exception, ensuring efficient and predictable error flow. ```python from slash.exception_handling import handling_exceptions def some_function(): with handling_exceptions(): do_something_that_might_fail() with handling_exceptions(): some_function() ``` -------------------------------- ### Customizing Interactive Shell Namespace with Slash Plugins (Python) Source: https://github.com/getslash/slash/blob/develop/doc/cookbook.rst This example shows how to extend the default namespace of Slash interactive sessions using the `before_interactive_shell` hook within a plugin. It adds a new variable, `lab_name`, to the interactive shell's namespace, making it accessible during interactive test runs (e.g., `slash run -i`). This allows for pre-populating the interactive environment with useful objects or data. ```python class MyPlugin(PluginInterface): ... def before_interactive_shell(self, namespace): namespace['lab_name'] = 'MicrowaveLab' ``` -------------------------------- ### Complex Test Filtering with Slash Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Applies a complex filter expression to include and exclude tests based on multiple conditions. This example runs tests containing 'components' but not 'failing_' in their names, using logical operators. ```Bash $ slash run -k 'not failing_ and components' /path/to/tests ``` -------------------------------- ### Configuring Extra Session Log Paths via Slash Plugin (Python) Source: https://github.com/getslash/slash/blob/develop/doc/cookbook.rst This plugin example demonstrates how to add an extra log path at the session level in Slash. The plugin defines a configurable `extra_log_path` and, during `session_start`, checks if this path is set. If so, it uses `slash.context.session.results.global_result.add_extra_log_path()` to include the specified log file with the overall session results, useful for logs generated outside individual tests. ```python class MyPlugin(slash.plugins.PluginInterface): def get_name(self): return "my plugin" def get_default_config(self): retrun {'extra_log_path': ''} def session_start(self): log_path = slash.config.root.plugin_config.my_plugin.extra_log_path if log_path: slash.context.session.results.global_result.add_extra_log_path(log_path) ``` -------------------------------- ### Excluding Tests by Substring with Slash Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Excludes tests whose names contain the specified substring. This example prevents tests with 'failing_' in their name from being executed. ```Bash $ slash run -k 'not failing_' /path/to/tests ``` -------------------------------- ### Aliasing Fixtures with `slash.use` in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This example illustrates how to alias a descriptively named fixture to a shorter, more convenient name within a test function's signature using `slash.use`. This practice improves test readability by allowing concise variable names while retaining the clarity of the original fixture definition. ```Python @slash.fixture def microwave_with_up_to_date_firmware(microwave): microwave.update_firmware() return microwave def test_turning_off(m: slash.use('microwave_with_up_to_date_firmware')): m.turn_off() assert m.is_off() m.turn_on() ``` -------------------------------- ### Excluding Multiple Parameter Combinations in Slash Python Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst This example illustrates how to exclude test cases based on specific combinations of multiple parameters using `@slash.exclude`. It defines a `test_car` function and a `car` fixture, where instances with `car.size` 10 and `car.color` 'red', or `car.size` 20 and `car.color` 'blue' will be skipped. ```python import slash SUPPORTED_SIZES = [10, 15, 20, 25] @slash.exclude(('car.size', 'car.color'), [(10, 'red'), (20, 'blue')]) def test_car(car): ... @slash.parametrize('size', SUPPORTED_SIZES) @slash.parametrize('color', ['red', 'green', 'blue']) @slash.fixture def car(size, color): # <-- red cars of size 10 and blue cars of size 20 will be skipped ... ``` -------------------------------- ### Complex Expression Assertion in Python Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This example illustrates an assertion involving complex function calls. Slash's assertion rewriting provides an elaborate output upon failure, detailing the intermediate values of expressions to help diagnose issues. ```Python ... assert f(g(x)) == g(f(x + 1)) ... ``` -------------------------------- ### Marking an Added Error as Fatal in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This code shows how to mark an error as fatal when adding it explicitly via `slash.add_error()`. While this method marks the error as fatal, it does not immediately stop the session, requiring the developer to ensure no further actions tamper with the setup or session state. ```python slash.add_error("some error condition detected!").mark_fatal() ``` -------------------------------- ### Adding Extra Log Files to a Test Result in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/cookbook.rst This snippet illustrates how a test function can add an additional log file to its result in Slash. It retrieves the current test's log directory, constructs a path for an external tool's log, and uses `slash.context.result.add_extra_log_path()` to associate it with the test result. The example then runs an external validation tool, redirecting its output to this new log file. ```python import slash import subprocess def test_running_validation_tool(): log_dir = slash.context.result.get_log_dir() log_file = os.path.join(log_dir, "tool.log") slash.context.result.add_extra_log_path(log_file) with open(os.path.join(log_dir, "tool.log"), "w") as logfile: res = subprocess.run(f'/bin/validation_tool -l {log_dir}', shell=True, stdout=logfile) res.check_returncode() ``` -------------------------------- ### Opting Out of Fixture Deduction with @slash.nofixtures (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This example demonstrates how to use the `@slash.nofixtures` decorator on a method to prevent Slash from interpreting its parameters as fixture names. This is particularly useful in inheritance scenarios where a base class method's parameters are not intended to be fixtures, avoiding load failures. ```Python class BaseTest(slash.Test): @slash.nofixtures def before(self, param): self._construct_case_with(param) ``` -------------------------------- ### Using `use_fixtures` Decorator in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet demonstrates the `@slash.use_fixtures` decorator, which allows a test function to declare its dependency on one or more fixtures without needing to accept them as arguments. This is particularly useful when the test doesn't require the fixture's return value but still needs its setup and teardown to occur. ```Python @slash.fixture() def used_fixture1(): """do something""" pass @slash.fixture() def used_fixture2(): """do another thing""" pass @slash.use_fixtures(["used_fixture1, used_fixture2"]) def test_something(): pass ``` -------------------------------- ### Registering Slash Customization via Setuptools Entry Point Source: https://github.com/getslash/slash/blob/develop/doc/advanced_usage.rst This `setup.py` snippet demonstrates how to register the `cool_customization_logic` function as a `slash.site.customize` entry point using Setuptools. This configuration ensures that Slash automatically calls the specified function upon startup, enabling global and persistent customization of the framework's behavior. ```Python # setup.py ... setup(... # ... entry_points = { "slash.site.customize": [ "cool_customization_logic = my_package:cool_customization_logic" ] }, # ... ) ``` -------------------------------- ### Running Slash Test Suite and Verifying Results in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet demonstrates how to execute a test suite using `suite.run()` and then inspect the results. It shows how to check the number of results and verify if all tests passed using `summary.ok()`. ```python summary = suite.run() len(summary.session.results) summary.ok() ``` -------------------------------- ### Running Tests with Slash CLI Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Executes tests located at the specified path using the `slash run` command-line utility. This is the basic usage for initiating a test session. ```Bash $ slash run /path/to/tests ``` -------------------------------- ### Activating XUnit Plugin and Specifying Output (Shell) Source: https://github.com/getslash/slash/blob/develop/doc/builtin_plugins.rst This command activates the Slash XUnit plugin, which generates an XML file conforming to the XUnit format. The output filename is specified as 'xunit.xml', making the results compatible with third-party CI tools. ```Shell slash run --with-xunit --xunit-filename xunit.xml ``` -------------------------------- ### Initializing Slash Test Suite in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet demonstrates how to import the `Suite` class from `tests.utils.suite_writer` and instantiate it. The `Suite` object is used to create and manage virtual test suites for Slash. ```python from tests.utils.suite_writer import Suite suite = Suite() ``` -------------------------------- ### Registering Hooks with slash.hooks (Python) Source: https://github.com/getslash/slash/blob/develop/doc/hooks.rst This snippet demonstrates the standard way to register a callback function to a Slash hook using the `slash.hooks` module. The `handler` function is decorated with `@slash.hooks.session_start.register`, ensuring it executes at the beginning of a test session and prints session information. ```Python import slash @slash.hooks.session_start.register def handler(): print("Session has started: ", slash.context.session) ``` -------------------------------- ### Listing Available Slash Fixtures from Command Line (Shell) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This command-line snippet shows how to use the `slash list` command with the `--only-fixtures` flag to display all available fixtures within a specified testing directory. It provides a way to inspect the fixtures defined in a project without running tests. ```shell slash list --only-fixtures path/to/tests ``` -------------------------------- ### Adding Test Start/End Callbacks to Scoped Fixtures in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This code demonstrates how to integrate `this.test_start` and `this.test_end` callbacks within a widely-scoped fixture (e.g., module scope). These callbacks allow the fixture to execute specific logic at the beginning and end of each individual test that depends on it, useful for managing resources like background processes. ```Python @slash.fixture(scope='module') def background_process(this): process = SomeComplexBackgroundProcess() @this.test_start def on_test_start(): process.make_sure_still_running() @this.test_end def on_test_end(): process.make_sure_no_errors() process.start() this.add_cleanup(process.stop) ``` -------------------------------- ### Managing Fixture Dependencies and Parameters in Slash in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet illustrates a more complex scenario where fixtures depend on each other and are parametrized. It shows how to add fixtures to `slashconf` and test files, establish dependencies, and add parameters to fixtures, verifying the number of results matches parameter values. ```python suite.clear() f1 = suite.slashconf.add_fixture() test = suite.add_test() f2 = test.file.add_fixture() _ = f2.depend_on_fixture(f1) _ = test.depend_on_fixture(f2) p = f1.add_parameter() summary = suite.run() summary.ok() len(summary.session.results) == len(p.values) ``` -------------------------------- ### Defining a Basic Fixture (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This code illustrates the basic definition of a fixture using the `@slash.fixture` decorator. The function `microwave` is responsible for initializing and returning an instance of `Microwave`, which will then be provided to any test or other fixture that requests it. ```Python import slash ... @slash.fixture def microwave(): # initialization of the actual microwave instance return Microwave(...) ``` -------------------------------- ### Labeling Parameters with slash.param Shortcut (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Presents an alternative syntactic shortcut for labeling parameters using the `//` operator with `slash.param`. This form is functionally equivalent to the direct `slash.param()` usage but allows placing the value before the label. ```python @slash.parametrize('param', [ Object1() // slash.param('first'), Object2() // slash.param('second'), ]) def test_something(param): ... ``` -------------------------------- ### Loading Tests from Suite Files with Slash Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Loads tests from one or more specified suite files. Each file can contain paths to tests, with support for comments and whitespace. This allows for organizing test execution through external lists. ```Bash $ slash run -f file1.txt -f file2.txt ``` -------------------------------- ### Running Interactive Session with Slash Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Invokes an interactive IPython shell initialized with the project's environment and a valid Slash session. This is useful for experimenting with the framework and debugging. ```Bash $ slash run -i ``` -------------------------------- ### Activating Coverage Plugin with HTML Report (Shell) Source: https://github.com/getslash/slash/blob/develop/doc/builtin_plugins.rst This command activates the Slash coverage plugin, specifying 'mypackage' for coverage tracking and generating an HTML report. It's used to monitor runtime code coverage and output results in a human-readable format. ```Shell slash run --with-coverage --cov mypackage --cov-report html ``` -------------------------------- ### Running CPU-Bound Slash Tests in Parallel per CPU Core Source: https://github.com/getslash/slash/blob/develop/doc/parallel.rst This command shows how to run Slash tests in parallel, allocating one worker process per CPU core. The $(nproc) command dynamically determines the number of available CPU cores, making it suitable for CPU-bound test suites. ```Bash $ slash run /path/to/tests --parallel $(nproc) ``` -------------------------------- ### Configuring Default Plugin Settings in Slash Source: https://github.com/getslash/slash/blob/develop/doc/plugins.rst This snippet demonstrates how to provide default configuration for a Slash plugin by overriding the `get_default_config` method. The returned dictionary defines configuration parameters, such as `log_destination`, which are then accessible via the `current_config` property. This allows plugins to offer customizable settings. ```Python class LogCollectionPlugin(PluginInterface): def get_default_config(self): return { 'log_destination': '/some/default/path' } ``` -------------------------------- ### Defining Plugin-Level Dependencies in Slash Source: https://github.com/getslash/slash/blob/develop/doc/plugins.rst This snippet demonstrates how to apply dependencies at the entire plugin level using `@slash.plugins.provides` and `@slash.plugins.needs` decorators on the class definition. This ensures that all hooks within `TestIdentificationLoggingPlugin` will depend on the 'awesome_test_id' provided by `TestIdentificationPlugin`, simplifying dependency management for multiple hooks. ```Python @slash.plugins.provides('awesome_test_id') class TestIdentificationPlugin(PluginInterface): def test_start(self): slash.context.test.awesome_test_id = awesome_id_allocation_service() @slash.plugins.needs('awesome_test_id') class TestIdentificationLoggingPlugin(PluginInterface): def test_start(self): slash.logger.debug('Test has started with the awesome id of {!r}', slash.context.test.awesome_id) ``` -------------------------------- ### Defining a Fixture with Dependencies (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This code illustrates how a fixture can depend on other fixtures by accepting them as arguments, similar to how tests depend on fixtures. The `heating_plate` fixture requires the `microwave` fixture, and Slash automatically resolves and provides the `microwave` instance before `heating_plate` is initialized. ```Python @slash.fixture def heating_plate(microwave): return get_appropriate_heating_plate_for(microwave) ``` -------------------------------- ### Registering Hooks with Gossip Directly (Python) Source: https://github.com/getslash/slash/blob/develop/doc/hooks.rst This snippet illustrates the underlying mechanism of Slash hook registration by directly using the `gossip` library. The `handler` function is registered to the `slash.session_start` gossip group, achieving the same effect as using `slash.hooks` and demonstrating Slash's dependency on `gossip`. ```Python import gossip @gossip.register("slash.session_start") def handler(): print("Session has started: ", slash.context.session) ``` -------------------------------- ### Configuring Default Test Source for Slash Run Source: https://github.com/getslash/slash/blob/develop/doc/advanced_usage.rst This snippet demonstrates how to specify a default test source path for the `slash run` command using the `slash.config.root.run.default_sources` option. This configuration is typically placed in a `.slashrc` file, providing a convenient and consistent default test environment for users without requiring them to specify paths manually. ```Python # ... slash.config.root.run.default_sources = ["/my/default/path/to/tests"] ``` -------------------------------- ### Adding Custom Details to Notifications (Python) Source: https://github.com/getslash/slash/blob/develop/doc/builtin_plugins.rst This Python snippet demonstrates how to use the `prepare_notification` hook to inject additional information into notification messages. The added details become part of the email content, allowing for custom data inclusion. ```Python @slash.hooks.prepare_notification.register def prepare_notification(message): message.details_dict['additional_information'] = 'some information included' ``` -------------------------------- ### Iterating Multiple Parameters with slash.parameters.iterate (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Demonstrates an alternative way to specify multiple parametrizations using `@slash.parameters.iterate`. This decorator allows defining multiple parameters and their respective value lists, generating a Cartesian product of all combinations. ```python @slash.parameters.iterate(x=[1, 2, 3], y=[4, 5, 6]) def test_something(x, y): ... ``` -------------------------------- ### Emitting Highlight Logs in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/logging.rst This snippet shows how to mark a log record as a 'highlight' in Slash. By passing `{'highlight': True}` in the `extra` dictionary of a log emission, the log will be directed to the configured highlight log file, useful for tracking infrequent but important operations. ```Python slash.logger.info("hey", extra={"highlight": True}) ``` -------------------------------- ### Running Slash Suite and Counting Errors in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet shows how to re-run the suite after configuring a test to raise an exception. It then demonstrates how to retrieve the number of errors from the session results, confirming the test failure. ```python summary = suite.run() summary.session.results.get_num_errors() summary.ok() ``` -------------------------------- ### Parametrizing a Fixture (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet shows how to parametrize a fixture using the `@slash.parametrize` decorator, allowing the fixture to be instantiated with different values. In this case, the `microwave` fixture will be created for both `SimpleMicrowave` and `AdvancedMicrowave` classes, effectively generating multiple test variants with minimal effort. ```Python @slash.fixture @slash.parametrize('microwave_class', [SimpleMicrowave, AdvancedMicrowave]): def microwave(microwave_class, this): returned = microwave_class() this.add_cleanup(returned.turn_off) return returned ``` -------------------------------- ### Labeling Parameters with slash.param (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Demonstrates how to use `slash.param` to assign descriptive labels to parameter values. This improves test readability by generating test names that reflect the specific parametrization flavor (e.g., `param=first`, `param=second`). ```python @slash.parametrize('param', [ slash.param('first', Object1()), slash.param('second', Object2()), ]) def test_something(param): ... ``` -------------------------------- ### Understanding slash.generator_fixture Equivalence to Parametrized Fixtures (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet demonstrates the equivalence between using `@slash.generator_fixture` with `yield from` and a standard `@slash.fixture` combined with `@slash.parametrize`. It shows how a generator fixture yielding from an iterable `x` achieves the same result as a parametrized fixture that returns each parameter value. ```python @slash.generator_fixture def fixture(): yield from x ``` ```python @slash.fixture @slash.parametrize('param', x) def fixture(param): return param ``` -------------------------------- ### Configuring Command-Line Arguments for Slash Plugin (Python) Source: https://github.com/getslash/slash/blob/develop/doc/plugins.rst This snippet shows the beginning of a `configure_argument_parser` method within a Slash plugin. This method is used to add command-line arguments specific to the plugin, allowing users to pass options to the plugin when running Slash from the command line. The `parser` parameter is an `argparse.ArgumentParser` instance. ```Python class ResultsReportingPlugin(PluginInterface): def configure_argument_parser(self, parser): ``` -------------------------------- ### Running Slash with NMA Notifications (CLI) Source: https://github.com/getslash/slash/blob/develop/doc/features.rst This snippet demonstrates how to execute a Slash test run while enabling the notifications plugin and configuring it to use the Notify My Android (NMA) service. It requires the --with-notifications flag and the plugins.notifications.nma_api_key option with a valid API key to send notifications at the end of the run. ```Shell slash run my_test.py --with-notifications -o plugins.notifications.nma_api_key=XXXXXXXXXXXXXXX ``` -------------------------------- ### Defining a Test Function with a Fixture (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet demonstrates how a test function declares its dependency on a fixture by including the fixture's name as an argument. Slash automatically resolves and provides the `microwave` fixture instance to the `test_microwave_turns_on` function, allowing the test to interact with the pre-configured object. ```Python def test_microwave_turns_on(microwave): microwave.turn_on() assert microwave.get_state() == STATE_ON ``` -------------------------------- ### Adding Slashconf Fixture in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet demonstrates how to add a fixture directly to the `slashconf` file of the suite. Fixtures defined in `slashconf` are globally available within the test suite. ```python f = suite.slashconf.add_fixture() ``` -------------------------------- ### Extending Slash Configuration with Plugin Defaults (Python) Source: https://github.com/getslash/slash/blob/develop/doc/customizing_slash.rst This snippet shows how a Slash plugin can extend the framework's configuration system by providing default values. The get_default_config method defines a default api_timeout_seconds. This value can then be accessed via slash.config.root.plugin_config and overridden by users via command-line flags like -o product.api_timeout_seconds=100. ```python @slash.plugins.active class ProductTestingPlugin(slash.plugins.PluginInterface): ... def get_name(self): return 'your product' def get_default_config(self): return {'api_timeout_seconds': 50} ... def session_start(self): slash.g.target = Target( self.target_address, timeout=slash.config.root.plugin_config.your_product.api_timeout_seconds) ``` -------------------------------- ### Toggling Boolean Parameters with slash.parameters.toggle (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Provides a shortcut for creating two test cases based on a boolean flag. The `@slash.parameters.toggle` decorator automatically generates tests where the specified parameter is `True` and `False`. ```python @slash.parameters.toggle('with_safety_switch') def test_operation(with_safety_switch): ... ``` -------------------------------- ### Running Slash Tests in Parallel with Fixed Workers Source: https://github.com/getslash/slash/blob/develop/doc/parallel.rst This command demonstrates how to execute Slash tests in parallel mode by specifying a fixed number of worker processes. The --parallel argument is used to define the desired concurrency level for test execution. ```Bash $ slash run /path/to/tests --parallel 4 ``` -------------------------------- ### Adding Command-Line Arguments to a Slash Plugin (Python) Source: https://github.com/getslash/slash/blob/develop/doc/customizing_slash.rst This plugin demonstrates how to add custom command-line arguments to a Slash test run. It uses configure_argument_parser to define an argument (-t/--target) and configure_from_parsed_args to process its value. The session_start hook then uses this value to initialize a global target object, making it accessible to tests. ```python @slash.plugins.active class ProductTestingPlugin(slash.plugins.PluginInterface): def get_name(self): return 'your product' def configure_argument_parser(self, parser): parser.add_argument('-t', '--target', help='ip address of the target to test') def configure_from_parsed_args(self, args): self.target_address = args.target def session_start(self): slash.g.target = Target(self.target_address) ``` -------------------------------- ### Applying Slash's Exception Handling Context (Python) Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This code demonstrates the use of `slash.handle_exceptions_context()` to ensure that Slash's exception handling logic is invoked closer to where an exception originates. By wrapping the call to `func2()` within this context, cleanup operations are deferred until after Slash has had a chance to process the exception. ```python def func1(): with some_cleanup_context(), slash.handle_exceptions_context(): func2() ``` -------------------------------- ### Parametrizing Inherited Test Class Methods with slash.parametrize (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Shows how `slash.parametrize` works across class inheritance. Base classes can parametrize their `before` or `after` methods, and derived classes can further parametrize their own, with `super()` calls handled automatically. This expands the total number of test variations. ```python class BaseTest(Test): @slash.parametrize('base_parameter', [1, 2, 3]) def before(self, base_parameter): # .... class DerivedTest(BaseTest): @slash.parametrize('derived_parameter', [4, 5, 6]) def before(self, derived_parameter): super(DerivedTest, self).before() # note that base parameters aren't specified here # ..... ``` -------------------------------- ### Illustrating Default Exception Propagation in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This snippet demonstrates a typical function call chain where an exception might occur. It highlights that without explicit handling, cleanup contexts (like `some_cleanup_context`) are exited before Slash's debugger is entered, potentially leading to unexpected behavior during debugging. ```python def test_function(): func1() def func1(): with some_cleanup_context(): func2() def func2(): do_something_that_can_fail() ``` -------------------------------- ### Adding Multiple Tests to Slash Suite in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet shows how to add multiple test objects to a `Suite` instance using a loop. Each call to `add_test()` creates a new test object, which can be further manipulated before running the suite. ```python for i in range(10): test = suite.add_test() ``` -------------------------------- ### Defining Yielding Fixtures in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet demonstrates how to define a fixture as a generator in the Slash testing framework. The value yielded by the generator becomes the fixture's value, and any code after the `yield` statement is executed as cleanup, similar to `this.add_cleanup`. It shows a `microwave` fixture that initializes a `Microwave` object and turns it off during cleanup. ```python @slash.fixture def microwave(model_name): m = Microwave(model_name) yield m m.turn_off() ``` -------------------------------- ### Resuming Failed Sessions with Slash Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Resumes a previously failed test session, rerunning only the unsuccessful tests. It accepts all flags compatible with `slash run` and requires a session ID to identify the session to resume. ```Bash $ slash resume -vv ``` -------------------------------- ### Configuring Slash Test to Raise Exception in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet illustrates how to configure a test object to raise an exception when it is run. This is useful for simulating error conditions and testing error handling within the suite. ```python test.when_run.raise_exception() ``` -------------------------------- ### Asserting Expected Exceptions with slash.assert_raises Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This snippet demonstrates using `slash.assert_raises` to verify that a specific exception (`SomeException`) is raised within a code block. It also shows how to capture the raised exception and inspect its attributes, such as `caught.exception.param`. ```Python with slash.assert_raises(SomeException) as caught: some_func() assert caught.exception.param == 'some_value' ``` -------------------------------- ### Overriding Configuration with Slash Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Overrides a specific configuration value during test execution. This allows dynamic adjustment of settings without modifying configuration files, useful for testing different scenarios. ```Bash $ slash run -o path.to.config.value=20 ... ``` -------------------------------- ### Running Parallel Slash Tests with Tmux for Output Control Source: https://github.com/getslash/slash/blob/develop/doc/parallel.rst This command enables parallel test execution in Slash while integrating with tmux for enhanced output management. The --tmux flag allows each worker to open a new tmux window or pane (with --tmux-panes), providing separate console outputs for monitoring. ```Bash $ slash run /path/to/tests --parallel 4 --tmux [--tmux-panes] ``` -------------------------------- ### Specifying Fixture Requirements in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet demonstrates how to apply requirements to a fixture using the `@slash.requires` decorator. If the specified condition is not met, any tests dependent on this fixture will be skipped, ensuring tests only run when their prerequisites are satisfied. ```Python @slash.fixture @slash.requires(condition, 'Requires a specific flag') def some_fixture(): ... ``` -------------------------------- ### Adding Parameters to Slash Test in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet demonstrates how to clear the suite, add a new test, and then add a parameter to that test. It shows that by default, parameters will have multiple values, and the suite will still pass. ```python suite.clear() test = suite.add_test() p = test.add_parameter() len(p.values) suite.run().ok() ``` -------------------------------- ### Adding File-Level Fixture to Slash Test in Python Source: https://github.com/getslash/slash/blob/develop/doc/unit_testing.rst This snippet shows how to add a fixture at the file level for a test. It demonstrates clearing the suite, adding a test, creating a fixture associated with the test's file, and making the test depend on it, ensuring the suite runs successfully. ```python suite.clear() test = suite.add_test() f = test.file.add_fixture() _ = test.depend_on_fixture(f) suite.run().ok() ``` -------------------------------- ### Implementing Slash Log Collection Plugin (Python) Source: https://github.com/getslash/slash/blob/develop/doc/customizing_slash.rst This plugin, `LogCollectionPlugin`, is activated in Slash to handle log collection at the end of a test session. It copies the entire session log directory to a specified remote path, using the session ID for the destination folder name. ```Python @slash.plugins.active class LogCollectionPlugin(slash.plugins.PluginInterface): def get_name(self): return 'logcollector' def session_end(self): shutil.copytree( slash.session.logging.session_log_path, os.path.join('/remote/path', slash.session.id)) ``` -------------------------------- ### Basic Test Assertion in Python Source: https://github.com/getslash/slash/blob/develop/doc/errors.rst This snippet demonstrates a fundamental assertion in a Python test function. It uses the `assert` statement to verify a simple arithmetic condition, showcasing how Slash's assertion rewriting provides detailed feedback upon failure. ```Python # test_addition.py def test_addition(self): assert 2 + 2 == 4 ``` -------------------------------- ### Rerunning Entire Sessions with Slash Source: https://github.com/getslash/slash/blob/develop/doc/slash_run.rst Reruns all tests from a specified previous session, useful for reproducing a run or re-executing a specific worker's tests. It accepts all flags compatible with `slash run` and requires a session ID. ```Bash $ slash rerun -vv ``` -------------------------------- ### Controlling Test Execution Order with Slash Hooks (Python) Source: https://github.com/getslash/slash/blob/develop/doc/cookbook.rst This snippet demonstrates how to use the `tests_loaded` hook in Slash to control the execution order of tests. It registers a function that reverses the order of tests by setting a dedicated sort key in their metadata, ensuring tests run in a custom sequence. This code is typically placed in a `slashconf.py` file. ```python @slash.hooks.tests_loaded.register def tests_loaded(tests): for index, test in enumerate(reversed(tests)): test.__slash__.set_sort_key(index) ``` -------------------------------- ### Setting Test Facts in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/details.rst This snippet illustrates how to set a test 'fact' using `slash.context.result.facts.set`. Facts are similar to details but are intended for more structured values, often used for coverage matrices. Here, it records whether the car is a van, triggering the `fact_set` hook. ```python def test_steering_wheel(car): slash.context.result.facts.set('is_van', car.is_van()) ``` -------------------------------- ### Adding Cleanup to a Fixture (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet shows how to register a cleanup callback for a fixture using the `this` argument and its `add_cleanup` method. The `returned.turn_off` method will be called automatically when the fixture's lifetime ends, typically at the end of each test that requested it, ensuring proper resource release. ```Python @slash.fixture def microwave(this): returned = Microwave() this.add_cleanup(returned.turn_off) return returned ``` -------------------------------- ### Specifying Dependent Parameters with slash.parametrize (Python) Source: https://github.com/getslash/slash/blob/develop/doc/parameters.rst Shows how to group dependent parameters using a tuple in `@slash.parametrize`. This ensures that parameters receive related values from a list of tuples, preventing the generation of invalid or unrelated combinations (e.g., a 'yellow apple'). ```python @slash.parametrize(('fruit', 'color'), [('apple', 'red'), ('apple', 'green'), ('banana', 'yellow')]) def test_fruits(fruit, color): ... # <-- this never gets a yellow apple ``` -------------------------------- ### Configuring Slash Log Root Directory (Python) Source: https://github.com/getslash/slash/blob/develop/doc/customizing_slash.rst This snippet configures the root directory for Slash logs. It sets the `log.root` path in the Slash configuration to an expanded user directory, ensuring logs are stored in a user-specific location. ```Python slash.config.root.log.root = os.path.expanduser('~/slash_logs') ``` -------------------------------- ### Defining Module-Scoped Fixtures in Slash (Python) Source: https://github.com/getslash/slash/blob/develop/doc/fixtures.rst This snippet shows how to define a fixture with a 'module' scope, which means it is active from its first use until the last test in its module finishes execution. A cleanup function is registered using `this.add_cleanup` to run at the end of the module's tests. ```Python @slash.fixture(scope='module') def some_module_fixture(this): @this.add_cleanup def cleanup(): print('Hurray! We are finished with this module') ```