### Combining Test File and Method Markers Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md This snippet demonstrates how to combine markers at different scopes (file and test method). The logging system prioritizes markers starting from the test method scope and moving upwards (class, file). The example shows a file-level marker `AI` and a method-level marker `MBT_AI`, with the method-level marker taking precedence in reporting. ```python from pytest_mfd_logging import marker pytestmark = marker.AI @marker.MBT_Waypoints class TestSomeModule: @marker.MBT_AI def test_connection(self): ... ``` -------------------------------- ### Display Test Metadata in Jinja2 Template Source: https://github.com/intel/pytest-mfd-logging/blob/main/pytest_mfd_logging/templates/html/test.html This snippet demonstrates how to render test start time, end time, and duration using Jinja2 templating. It utilizes `strftime` for date formatting and `timedelta` for duration formatting, assuming `time_format` is a predefined variable. ```jinja2 {% block test_content scoped %} {% if test.item.function.__doc__ %} {{ test.item.function.__doc__|cleandoc|rst|safe }} {% endif %} {% block test_metadata scoped %} {% for name, value in test.phases|map(attribute='report.user_properties')|chain|unique %} {% endfor %} {# TODO: Use keywords from TestReport to support dynamically added markers with xdist #} {% set markers = test.item.iter_markers()|rejectattr('name', '==', 'parametrize')|list|unique(attribute='name') %} {% if markers %} {% endif %} {% if test.item.fixturenames %} {% endif %} {% for phase in test.phases %} {% for extra in phase.report.extra|default([]) %} {% endfor %} {% endfor %} {% endblock %} Started {{ test.started|strftime(time_format) }} Ended {{ test.ended|strftime(time_format) }} Duration {{ test.phases|sum(attribute='report.duration')|timedelta }} {{ name }} {{ value|escape|urlize }} Markers {% for marker in markers %} {{ marker.name }} {% for value in marker.args %} {{ value|repr }} {% endfor %} {% for key, value in marker.kwargs.items() %} {{ key }}={{ value|repr }} {% endfor %} {% endfor %} Fixtures {% for fixturename in test.item.fixturenames if not fixturename.startswith('_') %} {{ fixturename }} {% endfor %} {{ extra.name }} {% if extra.format == 'image' %} ![{{ extra.name }}]({{ extra.content|asset(extra.extension) }}) {% elif extra.format == 'video' %} {% elif extra.format == 'html' %} {{ extra.content|safe }} {% elif extra.format == 'text' %} {{ extra.content|escape }} {% elif extra.format == 'json' %} {{ extra.content|tojson(indent=2) }} {% elif extra.format == 'url' %} {{ extra.content|urlize }} {% else %} ? {% endif %} {% for phase in test.phases if phase.call and phase.call.excinfo %} {{ phase.call.excinfo.exconly(tryshort=True) }} {% endfor %} {% for phase in test.phases %} #### {% if phase.status.category %} {% endif %} {{ phase.report.when|title }} {% if phase.report.longrepr %} {{ phase.report.longreprtext }} {% endif %} ##### {{ section }} {{ _get_parsed_logs_for_phase(phase)|escape|ansi|safe }} {% endfor %} {% endblock %} ``` -------------------------------- ### Display Test Markers and Fixtures in Jinja2 Source: https://github.com/intel/pytest-mfd-logging/blob/main/pytest_mfd_logging/templates/html/test.html This Jinja2 snippet illustrates how to iterate through test markers and fixtures. It processes markers with arguments and keyword arguments, and lists fixtures that do not start with an underscore. It assumes `test.item.iter_markers`, `test.item.fixturenames`, and marker attributes are available. ```jinja2 {# TODO: Use keywords from TestReport to support dynamically added markers with xdist #} {% set markers = test.item.iter_markers()|rejectattr('name', '==', 'parametrize')|list|unique(attribute='name') %} {% if markers %} {% endif %} {% if test.item.fixturenames %} {% endif %} {% for phase in test.phases %} {% for extra in phase.report.extra|default([]) %} {% endfor %} {% endfor %} Markers {% for marker in markers %} {{ marker.name }} {% for value in marker.args %} {{ value|repr }} {% endfor %} {% for key, value in marker.kwargs.items() %} {{ key }}={{ value|repr }} {% endfor %} {% endfor %} Fixtures {% for fixturename in test.item.fixturenames if not fixturename.startswith('_') %} {{ fixturename }} {% endfor %} ``` -------------------------------- ### Example of Parsed JSON Log Entry Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md Illustrates a single log entry within a parsed JSON report. This format includes detailed information about the log message, such as timestamp, module, level, file, line number, and function name. ```json { "name": "mfd_connect.base", "msg": "RPyCConnection established with: OSType.POSIX, OSName.LINUX, OSBitness.OS_64BIT, 10.11.12.13", "args": null, "levelname": "MODULE_DEBUG", "levelno": 13, "pathname": "C:\\Users\\someuser\\venv\\lib\\site-packages\\mfd_connect\\base.py", "filename": "base.py", "module": "base", "exc_info": null, "exc_text": null, "stack_info": null, "lineno": 215, "funcName": "log_connected_host_info", "created": 1672247127.0405319, "msecs": 40.53187370300293, "relativeCreated": 1161.8530750274658, "thread": 13316, "threadName": "MainThread", "processName": "MainProcess", "process": 3480, "asctime": "2022-12-28 18:05:27" } ``` -------------------------------- ### Marking Test Files with Module-Level Variable Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md This example illustrates how to mark an entire test file by assigning a marker to the `pytestmark` variable at the module level. This approach is suitable for applying a common marker to all tests within a file, such as `AI`. The marker will be reflected in log output and JSON report metadata. ```python from pytest_mfd_logging import marker pytestmark = marker.AI ``` -------------------------------- ### Render Parsed Test Logs in Jinja2 Source: https://github.com/intel/pytest-mfd-logging/blob/main/pytest_mfd_logging/templates/html/test.html This Jinja2 code block is responsible for rendering the parsed logs for each test phase. It includes the phase's 'when' status (e.g., setup, call, teardown) and the detailed log output, which is escaped, converted from ANSI escape codes, and rendered safely. It also displays `longreprtext` if available. ```jinja2 {% for phase in test.phases %} #### {% if phase.status.category %} {% endif %} {{ phase.report.when|title }} {% if phase.report.longrepr %} {{ phase.report.longreprtext }} {% endif %} ##### {{ section }} {{ _get_parsed_logs_for_phase(phase)|escape|ansi|safe }} {% endfor %} ``` -------------------------------- ### Run Documentation Generation Script Source: https://github.com/intel/pytest-mfd-logging/blob/main/sphinx-doc/README.md This snippet shows the command to execute the Python script responsible for generating the Sphinx documentation. Ensure you are in the activated virtual environment within the PyTest-MFD-Logging directory before running this command. ```shell $ python generate_docs.py ``` -------------------------------- ### PyTest Parameter ID Generation with pytest_make_parametrize_id Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md Demonstrates how to use the `pytest_make_parametrize_id` hook to automatically display parameter values for each test set generated by `pytest.mark.parametrize`. This improves test readability by showing the specific inputs used for each test case in the output. ```python import pytest @pytest.mark.parametrize( 'a, b', [ (1, {'Two Scoops of Django': '1.8'}), (True, 'Into the Brambles'), ('Jason likes cookies', [1, 2, 3]), ], ) @pytest.mark.parametrize( 'c', [ 'hello world', 123, ], ) def test_foobar(a, b, c): assert True ``` -------------------------------- ### Render Extra Test Information in Jinja2 Source: https://github.com/intel/pytest-mfd-logging/blob/main/pytest_mfd_logging/templates/html/test.html This Jinja2 code handles the display of various 'extra' information associated with a test phase, supporting formats like image, video, HTML, text, JSON, and URL. It uses conditional logic based on `extra.format` to render the content appropriately, including asset linking for images and safe rendering for HTML. ```jinja2 {{ extra.name }} {% if extra.format == 'image' %} ![{{ extra.name }}]({{ extra.content|asset(extra.extension) }}) {% elif extra.format == 'video' %} {% elif extra.format == 'html' %} {{ extra.content|safe }} {% elif extra.format == 'text' %} {{ extra.content|escape }} {% elif extra.format == 'json' %} {{ extra.content|tojson(indent=2) }} {% elif extra.format == 'url' %} {{ extra.content|urlize }} {% else %} ? {% endif %} ``` -------------------------------- ### Pytest INI Configuration for Logging Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md This configuration snippet defines pytest's logging behavior, including log format for both console and file output, and the logging level. It specifies how log messages and timestamps should be presented. This configuration is stored in a 'pytest.ini' file. ```ini [pytest] log_cli=True log_format=%(asctime)s %(name)22.22s:%(funcName)-18.18s %(levelname)-13.13s log_date_format=%Y-%m-%d %H:%M:%S log_cli_level=DEBUG log_file_format=%(asctime)s %(name)22.22s:%(funcName)-18.18s %(levelname)-13.13s log_file_date_format=%Y-%m-%d %H:%M:%S log_file_level=DEBUG ``` -------------------------------- ### Display Test Phase Exceptions in Jinja2 Source: https://github.com/intel/pytest-mfd-logging/blob/main/pytest_mfd_logging/templates/html/test.html This Jinja2 snippet iterates through test phases and displays any exceptions that occurred during the 'call' phase of the test. It uses `phase.call.excinfo.exconly(tryshort=True)` to extract and format the exception information concisely. ```jinja2 {% for phase in test.phases if phase.call and phase.call.excinfo %} {{ phase.call.excinfo.exconly(tryshort=True) }} {% endfor %} ``` -------------------------------- ### Enable and Configure JSON Logging in PyTest Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md Enables JSON logging in PyTest using the pytest-json-report plugin. Allows specifying output files for raw JSON reports and a directory for parsed JSON logs. The plugin gathers test durations and used plugins, providing detailed logs in JSON format. ```bash --json-report --json-report-file C:\logs.json --parsed-json-path C:\logs ``` -------------------------------- ### Marking Test Methods with Decorators Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md This code shows how to apply a marker to an individual test method using a decorator. This allows for more granular control over test categorization. The chosen marker, like `MBT_AI`, will be recorded in the test logs and the JSON report's metadata. ```python from pytest_mfd_logging import marker class TestSomeModule: @marker.MBT_AI def test_connections(self): ... ``` -------------------------------- ### Sign Git Commits Automatically Source: https://github.com/intel/pytest-mfd-logging/blob/main/CONTRIBUTING.md This snippet demonstrates how to configure Git to automatically sign your commits using the Developer Certificate of Origin. This simplifies the contribution process by appending the 'Signed-off-by' line to your commit messages. ```git git config --global user.name "Your Name" git config --global user.email "your.email@example.com" git commit -s -m "Your commit message" ``` -------------------------------- ### PyTest Output with Enhanced Parameter IDs Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md Shows the expected PyTest output when the `pytest_make_parametrize_id` hook is active. Each test case clearly displays the values of the parameters ('a', 'b', and 'c') used, making it easier to identify which specific combination led to a pass or fail. ```shell test_ids.py::test_foobar[|c = hello world|-|a = 1|-|b = {'Two Scoops of Django': '1.8'}|] PASSED test_ids.py::test_foobar[|c = hello world|-|a = True|-|b = Into the Brambles|] PASSED test_ids.py::test_foobar[|c = hello world|-|a = Jason likes cookies|-|b = [1, 2, 3]|] PASSED test_ids.py::test_foobar[|c = 123|-|a = 1|-|b = {'Two Scoops of Django': '1.8'}|] PASSED test_ids.py::test_foobar[|c = 123|-|a = True|-|b = Into the Brambles|] PASSED test_ids.py::test_foobar[|c = 123|-|a = Jason likes cookies|-|b = [1, 2, 3]|] PASSED ================================================== 6 passed in 0.03s ================================================== ``` -------------------------------- ### Marking Test Classes with Decorators Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md This snippet demonstrates how to mark a test class using a decorator from the `pytest_mfd_logging.marker` module. This is useful for categorizing tests based on their origin or type, such as `MBT_Waypoints` or `MBT_AI`. The marker will be visible in logs and JSON reports. ```python from pytest_mfd_logging import marker @marker.MBT_Waypoints class TestSomeModule: ... ``` -------------------------------- ### Python Function to Add Custom Logging Levels Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md This Python function, likely named '_add_all_logging_levels', is responsible for adding custom log levels, potentially from a library like 'mfd_common_libs', to the Python logger. This allows users to utilize these custom levels in configuration files or command-line arguments, enhancing the flexibility of the logging system. ```python def _add_all_logging_levels(): """Add mfd_common_libs log levels to logger.""" custom_levels = { "TRACE": 5, "DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40, "CRITICAL": 50, } for level_name, level_num in custom_levels.items(): if not logging.getLevelName(level_name): logging.addLevelName(level_num, level_name) logging.setLoggerClass(level_num, level_name) ``` -------------------------------- ### Python Function to Remove Stream Handler Source: https://github.com/intel/pytest-mfd-logging/blob/main/README.md This Python function, likely named '_remove_stream_handler', is designed to remove the stream handler from the root logger. This is a technique to prevent duplicate log messages when pytest's logging mechanism is enabled alongside Python's standard logging module. It ensures that only one handler is responsible for outputting logs to the console. ```python def _remove_stream_handler(): """Remove stream handler from root logger.""" root_logger = logging.getLogger() for handler in root_logger.handlers: if isinstance(handler, logging.StreamHandler): root_logger.removeHandler(handler) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.