### Install genbadge with all extra dependencies Source: https://smarie.github.io/python-genbadge Install genbadge with all extra dependencies to enable all command-line features, including tests, coverage, and flake8. ```bash > pip install genbadge[all] ``` -------------------------------- ### Display help for a specific genbadge command Source: https://smarie.github.io/python-genbadge Get help for a specific genbadge command, such as 'coverage', to understand its usage and options. ```bash Usage: genbadge [OPTIONS] COMMAND [ARGS]... Commandline utility to generate badges. To get help on each command use: genbadge --help Options: --help Show this message and exit. Commands: coverage Generate a badge for the coverage results (e.g. from a coverage.xml). flake8 Generate a badge for the flake8 results (e.g. from a flake8stats.txt file). tests Generate a badge for the test results (e.g. from a junit.xml). ``` -------------------------------- ### Install genbadge minimal dependencies Source: https://smarie.github.io/python-genbadge Install the minimal genbadge package, which includes core dependencies like click, pillow, and requests, allowing the use of the low-level API. ```bash > pip install genbadge ``` -------------------------------- ### Install genbadge with specific extra dependencies Source: https://smarie.github.io/python-genbadge Install genbadge with a subset of extra dependencies, such as tests and flake8, for specific command-line features. ```bash > pip install genbadge[tests,flake8] ``` -------------------------------- ### Example Coverage Badge SVG Output Source: https://smarie.github.io/python-genbadge/reports/junit/report.html This is an example of the SVG output generated for a coverage badge. It includes the coverage percentage and styling for display. ```xml coverage: 15.38% coverage 15.38% ``` -------------------------------- ### Import defusedxml or fallback Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.xunitparser_copy.source.html Attempts to import ElementTree from defusedxml. If the import fails, it defines a fallback class that raises an ImportError with a helpful message, guiding the user to install the necessary dependency. ```python try: # security patch: see https://docs.python.org/3/library/xml.etree.elementtree.html from defusedxml import ElementTree except ImportError as e: ee = e # save it class FakeDefusedXmlImport(object): # noqa def __getattribute__(self, item): raise ImportError("Could not import `defusedxml.ElementTree`, please install `defusedxml`. " "Note that all dependencies for the tests command can be installed with " "`pip install genbadge[tests]`. Caught: %r" % ee) ElementTree = FakeDefusedXmlImport() ``` -------------------------------- ### Get Coverage Stats from XML File Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_coverage_py.html Reads and parses a coverage.xml file to return a CoverageStats object. Accepts either a file path or a file-like object. ```python def get_coverage_stats(coverage_xml_file): # type: (...) -> CoverageStats """ Reads a coverage.xml file """ if isinstance(coverage_xml_file, str): # assume a file path with open(coverage_xml_file) as f: cov_stats = parse_cov(f) else: # assume a stream already cov_stats = parse_cov(coverage_xml_file) return cov_stats ``` -------------------------------- ### Markdown Integration of Coverage Badge Source: https://smarie.github.io/python-genbadge Example of how to embed the generated coverage badge in Markdown, linking it to the HTML report. The query parameter is a cache-busting technique. ```markdown [![Coverage Status](./reports/coverage/coverage-badge.svg?dummy=8484744)](./reports/coverage/index.html) ``` -------------------------------- ### Main CLI Entry Point Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.main.source.html The main entry point for the genbadge command-line utility. It sets up the command group and handles subcommand invocation, providing help if no subcommand is specified. ```python import click @click.group(invoke_without_command=True) @click.pass_context def genbadge(ctx): """ Commandline utility to generate badges. To get help on each command use: genbadge --help """ if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit(0) ``` -------------------------------- ### Display genbadge command-line help Source: https://smarie.github.io/python-genbadge Display the main help message for the genbadge command-line utility to see available commands and options. ```bash > genbadge ``` -------------------------------- ### Import Version and Handle Fallback Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d___init___py.html Imports the package version, attempting to load it from `_version.py` first. If that fails, it uses `setuptools_scm` to determine the version from source control. ```python try: # Distribution mode : import from _version.py generated by setuptools_scm during release from ._version import version as __version__ except ImportError: # Source mode : use setuptools_scm to get the current version from src using git from setuptools_scm import get_version as _gv from os import path as _path __version__ = _gv(_path.join(_path.dirname(__file__), _path.pardir)) ``` -------------------------------- ### Specify Input and Output Files for Badge Generation Source: https://smarie.github.io/python-genbadge Customize the input coverage report file using '-i' or '--input-file' and the output badge file using '-o' or '--output-file'. Use '-' for stdin/stdout. ```bash genbadge coverage -i - < coverage.xml genbadge coverage -o - > badge.svg ``` -------------------------------- ### Get Color Hexadecimal Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_badge.source.html Converts a color string to its hexadecimal representation. Assumes custom hexa strings are already valid. ```python def get_color(color_str): try: color_hexa = COLORS[color_str] except KeyError: # assume custom hexa string already color_hexa = color_str return color_hexa ``` -------------------------------- ### Generate a basic tests badge Source: https://smarie.github.io/python-genbadge Run the genbadge command to create a tests badge. It assumes default input and output file locations. ```bash genbadge tests ``` -------------------------------- ### Get Flake8 Statistics from File Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_flake8_py.html Reads and parses a flake8 statistics file (or stream) to create a Flake8Stats object. Handles both file paths and existing file-like objects. ```python def get_flake8_stats(flake8_stats_file): # type: (...) -> Flake8Stats """ Reads an index.html file obtained from flake8-html. """ if isinstance(flake8_stats_file, str): # assume a file path with open(flake8_stats_file) as f: flake8_stats_txt = f.read() else: # assume a stream already flake8_stats_txt = flake8_stats_file.read() return parse_flake8_stats(flake8_stats_txt) ``` -------------------------------- ### Generate Coverage Badge with Custom Input and Output Files Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge using a specified input coverage file and saves the badge to a custom output file path. Includes verbose output. ```bash genbadge coverage -l --input-file foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Get Flake8 Statistics from File Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_flake8.source.html Reads Flake8 statistics from a file path or a stream. Assumes the input is a file path if a string is provided, otherwise assumes it's a readable stream. ```python def get_flake8_stats(flake8_stats_file): # type: (...) -> Flake8Stats """ Reads an index.html file obtained from flake8-html. """ if isinstance(flake8_stats_file, str): # assume a file path with open(flake8_stats_file) as f: flake8_stats_txt = f.read() else: # assume a stream already flake8_stats_txt = flake8_stats_file.read() return parse_flake8_stats(flake8_stats_txt) ``` -------------------------------- ### Import Core Libraries Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_main_py.html Imports necessary libraries for command-line interface, and utility functions for generating badges. ```python import click from .utils_junit import get_test_stats, get_tests_badge from .utils_coverage import get_coverage_badge, get_coverage_stats from .utils_flake8 import get_flake8_stats, get_flake8_badge ``` -------------------------------- ### Get Test Statistics from JUnit XML Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_junit.source.html Parses a JUnit XML file or stream to extract test statistics. It returns a TestStats object containing counts of tests run, skipped, failed, and errors. ```python def get_test_stats(junit_xml_file='reports/junit/junit.xml' # type: Union[str, TextIOWrapper] ): # type: (...) -> TestStats """ read the junit test file and extract the success percentage :param junit_xml_file: the junit xml file path or file/text stream :return: the success percentage (an int) """ if isinstance(junit_xml_file, str): # assume a file path with open(junit_xml_file) as f: ts, tr = parse(f) else: # assume a stream already ts, tr = parse(junit_xml_file) runned = tr.testsRun skipped = len(tr.skipped) failed = len(tr.failures) errors = len(tr.errors) return TestStats(runned=runned, skipped=skipped, failed=failed, errors=errors) ``` -------------------------------- ### Process Coverage Input and Output Files Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.main.source.html Handles the input coverage XML file and determines the output file path for the badge. It supports standard file output and standard output. ```python # Process i/o files input_file, input_file_path = _process_infile(input_file, "reports/coverage/coverage.xml") output_file, output_file_path, is_stdout = _process_outfile(output_file, "coverage-badge.svg") ``` -------------------------------- ### Flake8 E251: Unexpected spaces around equals Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_coverage.report.html This snippet shows an example of the Flake8 E251 error, which flags unexpected spaces around the equals sign in a keyword argument or parameter assignment. Ensure there are no extra spaces. ```python _129_ left_txt= "coverage" # type: str ``` -------------------------------- ### Create Tests Badge with Default Settings Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a tests badge using default settings. The output path for the badge is automatically determined. ```bash genbadge tests -l SUCCESS - Tests badge created: '/tmp/pytest-of-runner/pytest-0/test_any_command_tests_default0/tests-badge.svg' ``` -------------------------------- ### Generate Coverage Reports Source: https://smarie.github.io/python-genbadge Use the 'coverage' tool to generate necessary reports for badge generation. 'coverage xml' is essential for creating the input file. ```bash > coverage report > coverage xml > coverage html ``` -------------------------------- ### Get Flake8 Badge Color Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_flake8_py.html Determines the appropriate badge color based on the number of critical, warning, and info issues found in the flake8 statistics. Returns 'red' for critical, 'orange' for warning, 'green' for info, and 'brightgreen' if no issues are found. ```python def get_color( flake8_stats # type: Flake8Stats ): """ Returns the badge color to use depending on the flake8 results """ if flake8_stats.nb_critical > 0: color = 'red' elif flake8_stats.nb_warning > 0: color = 'orange' elif flake8_stats.nb_info > 0: color = 'green' else: color = 'brightgreen' return color ``` -------------------------------- ### Generate Tests Badge with Short Args Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a badge for test results using short command-line arguments. The output is directed to stdout. ```bash genbadge tests -l -i foo/foo.xml -o - ``` -------------------------------- ### Define Version String and Tuple Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d__version_py.html Defines the package version as a string and a tuple. These are generated by setuptools_scm and should not be manually modified or tracked in version control. ```python __version__ = version = '0.1.dev1+g9c6537d92' __version_tuple__ = version_tuple = (0, 1, 'dev1', 'g9c6537d92') ``` -------------------------------- ### Define Help Text Constants Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_main_py.html Defines constants for help text used in command-line options, providing clear explanations for each parameter. ```python INFILE_HELP_TMP = "An alternate %s file to read. '-' is supported and means ." OUTFILE_BADGE_HELP = ("An alternate SVG badge file to write to. '-' is supported and means . Note that in this " "case no other message will be printed to . In particular the verbose flag will have no " "effect.") NAME_HELP = ("An alternate SVG badge text name to display on the left-hand side of the badge.") WITH_NAME_HELP = ("Indicates if a badge should be generated with or without the left-hand side of the badge.") SHIELDS_HELP = ("Indicates if badges should be generated using the shields.io HTTP API (default) or the local SVG file " "template included.") VERBOSE_HELP = ("Use this flag to print details to stdout during the badge generation process. Note that this flag has " "no effect when '-' is used as output, since the badge is written to . It also has no effect " "when the silent flag `-s` is used.") SILENT_HELP = ("When this flag is active nothing will be written to stdout. Note that this flag has no effect when '-' " "is used as the output file.") ``` -------------------------------- ### Generate Tests Badge to File (Short Args) Source: https://smarie.github.io/python-genbadge/reports/junit/report.html This command uses short argument flags (-i for input, -o for output) to generate a tests badge and save it to an SVG file. It assumes default verbose and silent settings. ```bash genbadge tests -l -i foo/foo.xml -o bar/bar-badge.svg ``` -------------------------------- ### Generate Tests Badge to Stdout Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a tests badge and outputs it to standard output. Requires an input XML file. ```bash genbadge tests -l --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_tests_custom_17/foo/foo.xml --output-file - ``` -------------------------------- ### Generate Flake8 Report and Badge Source: https://smarie.github.io/python-genbadge Run flake8 with specific options to generate statistics and an HTML report, then use genbadge to create a flake8 badge. The `--exit-zero` flag ensures the command always returns success. The `--statistics` flag with `--tee --output-file flake8stats.txt` is crucial for generating the input file for genbadge. ```bash > flake8 --exit-zero --format=html --htmldir ./reports/flake8 --statistics --tee --output-file flake8stats.txt 1 B014 Redundant exception types in `except (IOError, OSError):`. Write `except OSError:`, which catches exactly the same exceptions. 7 C801 Copyright notice not present. 1 E122 continuation line missing indentation or outdented 1 E303 too many blank lines (3) ... ``` ```bash > genbadge flake8 ``` ```bash Flake8 statistics parsed successfully from '(...)/reports/flake8/flake8stats.txt' - Total (20) = Critical (6) + Warning (9) + Info (5) SUCCESS - Flake8 badge created: '(...)/flake8-badge.svg' ``` -------------------------------- ### Main Execution Block Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_main_py.html The main entry point for the script execution. This block is typically run when the script is executed directly. ```python if __name__ == '__main__': genbadge() ``` -------------------------------- ### Generate tests badge with verbose output Source: https://smarie.github.io/python-genbadge Use the -v flag to display detailed statistics parsed from the input file and confirmation of badge creation. ```bash pytest --junitxml=reports/junit/junit.xml --html=reports/junit/report.html Test statistics parsed successfully from '(...)/reports/junit/junit.xml' - Nb tests: Total (6) = Success (2) + Skipped (1) + Failed (2) + Errors (1) - Success percentage: 40.00% (2 / 5) (Skipped tests are excluded) SUCCESS - Tests badge created: '(...)/tests-badge.svg' ``` -------------------------------- ### Badge Class Initialization Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_badge_py.html Initializes a Badge object with left text, right text, and color. Used for creating custom badges. ```python class Badge: """ A small utility class for badges """ def __init__(self, left_txt, # type: str right_txt, # type: str color, # type: str ): self.left_txt = left_txt self.right_txt = right_txt self.color = color ``` -------------------------------- ### Use Local Badge Template Source: https://smarie.github.io/python-genbadge Generate the badge using a local SVG template instead of shields.io by using the '-l/--local' flag. This option is less mature but functional. ```bash genbadge coverage -l ``` -------------------------------- ### Generate tests badge with custom input/output Source: https://smarie.github.io/python-genbadge Specify custom input JUnit XML file and output SVG file paths using -i and -o flags. ```bash genbadge tests -i - < junit.xml ``` ```bash genbadge tests -o - > badge.svg ``` -------------------------------- ### Define Public API Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d___init___py.html Defines the `__all__` list, specifying which names should be imported when `from genbadge import *` is used. This includes the package version and submodules. ```python __all__ = [ '__version__', # submodules 'main', 'utils_junit', 'utils_coverage', 'utils_flake8', 'utils_badge', 'xunitparser_copy', # symbols 'Badge' ] ``` -------------------------------- ### Generate Coverage Badge Source: https://smarie.github.io/python-genbadge Basic command to generate a coverage badge. The tool assumes default input and output paths. ```bash > genbadge coverage ``` -------------------------------- ### Generate Tests Badge to File Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a badge for test coverage and saves it to a specified SVG file. This is the standard way to create badge files for use in projects. ```bash genbadge tests -l --verbose --silent -i foo/foo.xml -o bar/bar-badge.svg ``` -------------------------------- ### Handle File Not Found Error for Tests Badge Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Demonstrates the error message when the input JUnit XML file for the tests badge is not found. Use the '-i' or '--input-file' option to specify the correct path. ```bash genbadge tests Error: Could not open file 'reports/junit/junit.xml': File not found genbadge tests -i unknown.file Usage: genbadge tests [OPTIONS] Try 'genbadge tests --help' for help. Error: Invalid value for '-i' / '--input-file': 'unknown.file': No such file or directory ``` -------------------------------- ### Create a Custom Badge with Badge Class Source: https://smarie.github.io/python-genbadge Instantiate the Badge class to create a custom badge. By default, this creates an abstract badge representation. Use the `write_to` method to generate an SVG file, optionally using shields.io or a local template. ```python from genbadge import Badge b = Badge(left_txt="foo", right_txt="bar", color="green") print(b) ``` ```python b.write_to("tmp_badge.svg", use_shields=False) ``` -------------------------------- ### Read Resource Bytes (Fallback) Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_badge.source.html Provides a fallback mechanism to read resource file bytes using pkg_resources for older Python versions when importlib.resources is not available or fully functional. ```python def _resource_string(package, resource_name): """Fallback for importlib.resources in older Python versions.""" if files and as_file: with as_file(files(package) / resource_name) as f: return f.read_bytes() else: # Fallback to pkg_resources for older Python versions from pkg_resources import resource_string return resource_string(package, resource_name) ``` -------------------------------- ### Genbadge Click Group Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_main_py.html Defines the main command group 'genbadge' using Click. It handles subcommand invocation and displays help if no subcommand is provided. ```python @click.group(invoke_without_command=True) @click.pass_context def genbadge(ctx): """ Commandline utility to generate badges. To get help on each command use: genbadge --help """ if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit(0) ``` -------------------------------- ### Generate Coverage Badge Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_coverage.source.html Creates a badge object from coverage statistics. It formats the coverage percentage and determines the badge color based on coverage levels. ```python def create_badge(cov_stats): """Return the badge from coverage results """ color = get_color(cov_stats) right_txt = "%.2f%%" % (cov_stats.total_coverage,) return Badge(left_txt="coverage", right_txt=right_txt, color=color) ``` -------------------------------- ### Generate Tests Badge with Input File Flag Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a badge for test coverage using a specific input file path and saves the output to a specified file. This demonstrates using explicit flags for input and output. ```bash genbadge tests -l --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_tests_custom_16/foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Generate Coverage Badge Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Use the 'genbadge coverage' command to generate a coverage badge. The SUCCESS argument indicates a successful coverage report, and the output path is specified. ```bash genbadge coverage -l SUCCESS - Coverage badge created: '/tmp/pytest-of-runner/pytest-0/test_any_command_coverage_defa0/coverage-badge.svg' ``` -------------------------------- ### Handle File Not Found Error for Coverage Badge Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Shows the error output when the input coverage XML file for the coverage badge is missing. Ensure the path provided with '-i' or '--input-file' is correct. ```bash genbadge coverage Error: Could not open file 'reports/coverage/coverage.xml': File not found genbadge coverage -i unknown.file Usage: genbadge coverage [OPTIONS] Try 'genbadge coverage --help' for help. Error: Invalid value for '-i' / '--input-file': 'unknown.file': No such file or directory ``` -------------------------------- ### Generate tests badge with custom name and local output Source: https://smarie.github.io/python-genbadge Customize the badge name using -n and choose local SVG template generation with -l. ```bash genbadge tests -n "" ``` ```bash genbadge tests -l ``` -------------------------------- ### genbadge Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.main.source.html The main genbadge command-line utility. It serves as a group for subcommands and provides general help. ```APIDOC ## genbadge ### Description Commandline utility to generate badges. To get help on each command use: genbadge --help ``` -------------------------------- ### Generate Coverage Badge with Explicit Input/Output Files Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge using explicit flags for input XML file and output SVG file. This command also confirms successful creation. ```bash genbadge coverage -l --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_coverage_cust16/foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Generate Coverage Badge Object Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_coverage_py.html Creates a Badge object using the coverage statistics. It formats the coverage percentage and applies the appropriate color. ```python def get_coverage_badge( cov_stats, # type: CoverageStats left_txt= "coverage" # type: str ): # type: (...) -> Badge """Return the badge from coverage results """ color = get_color(cov_stats) right_txt = "%.2f%%" % (cov_stats.total_coverage,) return Badge(left_txt=left_txt, right_txt=right_txt, color=color) ``` -------------------------------- ### Generate Test Badge to Stdout Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Use the 'genbadge tests' command with --input-file and --output-file - to print the SVG badge directly to standard output. This is useful for piping the output to other commands or processes. ```bash genbadge tests -l --verbose --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_tests_custom_21/foo/foo.xml --output-file - ``` -------------------------------- ### Generate Coverage Badge to File Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge and saves it to a specified SVG file. Use when you need to store the badge for later use or inclusion in documentation. ```bash genbadge coverage -l --verbose --input-file foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Generate Flake8 Badge with Custom Input/Output Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Creates a Flake8 badge using a specified XML input file and a custom output file path. Verbose logging is enabled. ```bash genbadge flake8 -l --input-file foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Generate Coverage Badge with Short Arguments Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge using abbreviated command-line flags for input and output files. This is useful for quicker typing and shorter commands. ```bash genbadge coverage -l -i foo/foo.xml -o bar/bar-badge.svg ``` -------------------------------- ### Generate Tests Badge to File Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a tests badge and saves it to a specified SVG file. Uses silent mode and requires an input XML file. ```bash genbadge tests -l --silent --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_tests_custom_18/foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Create Tests Badge Verbose Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a tests badge with the '--verbose' flag, showing detailed parsing information. The success percentage is calculated and displayed. ```bash genbadge tests -l --verbose Test statistics parsed successfully from '/tmp/pytest-of-runner/pytest-0/test_any_command_tests_default4/reports/junit/junit.xml' - Nb tests: Total (6) = Success (2) + Skipped (1) + Failed (2) + Errors (1) - Success percentage: 40.00% (2 / 5) (Skipped tests are excluded) SUCCESS - Tests badge created: '/tmp/pytest-of-runner/pytest-0/test_any_command_tests_default4/tests-badge.svg' ``` -------------------------------- ### Generate Flake8 Badge with Short Arguments Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a Flake8 badge using short command-line arguments for input and output files. This is a more concise way to specify options when generating badges. ```bash genbadge flake8 -l -i foo/foo.xml -o bar/bar-badge.svg ``` -------------------------------- ### Generate Test Badge to File Source: https://smarie.github.io/python-genbadge/reports/junit/report.html This command generates a test badge and saves it to a specified SVG file. The --output-file option directs the output to 'bar/bar-badge.svg'. ```bash genbadge tests -l --verbose --silent --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_tests_custom_22/foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Generate Tests Badge to Stdout Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a 'tests' badge and prints the SVG to standard output. Use this when you want to pipe the SVG to another process or display it directly. ```bash genbadge tests -l --input-file foo/foo.xml --output-file - ``` -------------------------------- ### Generate Coverage Badge Silently with Custom Input and Output Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge using a specified input coverage file and saves it to a custom output file path, with all logging suppressed. ```bash genbadge coverage -l --silent --input-file foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Generate Coverage Badge from XML Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.main.source.html Generates a badge for code coverage results from an XML file (e.g., coverage.xml, cobertura). Supports customization of input/output files and badge naming. Defaults to './reports/coverage/coverage.xml' and './coverage-badge.svg'. ```python @genbadge.command(name="coverage", short_help="Generate a badge for the coverage results (e.g. from a coverage.xml).") @click.option('-i', '--input-file', type=click.File('rt'), help=INFILE_HELP_TMP % "coverage results XML") @click.option('-o', '--output-file', type=click.File('wt'), help=OUTFILE_BADGE_HELP) @click.option('-n', '--name', type=str, default="coverage", help=NAME_HELP) @click.option('--withname/--noname', type=bool, default=True, help=WITH_NAME_HELP) @click.option('-w/-l', '--webshields/--local', type=bool, default=True, help=SHIELDS_HELP) @click.option('-v', '--verbose', type=bool, default=False, is_flag=True, help=VERBOSE_HELP) @click.option('-s', '--silent', type=bool, default=False, is_flag=True, help=SILENT_HELP) def gen_coverage_badge( input_file=None, output_file=None, name=None, withname=None, webshields=None, verbose=None, silent=None ): """ This command generates a badge for the coverage results, from an XML file in the 'coverage' format. Such a file can be for example generated using the python `coverage` tool, or java `cobertura`. By default the input file is the relative `./reports/coverage/coverage.xml` and the output file is `./coverage-badge.svg`. You can change these settings with the `-i/--input_file` and `-o/--output-file` options. """ pass ``` -------------------------------- ### Generate and Write Coverage Badge Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.main.source.html Generates the coverage badge using the retrieved statistics and configured name, then writes it to the specified output file or standard output. ```python # Generate the badge badge = get_coverage_badge(cov_stats, name) badge.write_to( output_file if is_stdout else output_file_path, ) ``` -------------------------------- ### Generate Coverage Badge with Verbose Output Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge using the default coverage report and displays verbose output. The badge is saved to the default output path. ```bash genbadge coverage -l --verbose ``` -------------------------------- ### Retrieve Coverage Statistics Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.main.source.html Fetches coverage statistics from a specified XML file. Raises a FileError if the input file is not found. ```python # First retrieve the coverage info from the coverage xml try: cov_stats = get_coverage_stats(coverage_xml_file=input_file) except FileNotFoundError: raise click.exceptions.FileError(input_file, hint="File not found") ``` -------------------------------- ### Generate Verbose Coverage Badge Output Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge with verbose output, providing detailed information about the coverage parsing and badge creation process. The output is saved to a file. ```bash genbadge coverage -l --verbose -i foo/foo.xml -o bar/bar-badge.svg ``` -------------------------------- ### Generate Tests Badge to Stdout (Silent) Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a tests badge in silent mode and outputs it to standard output. Requires an input XML file. ```bash genbadge tests -l --silent --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_tests_custom_19/foo/foo.xml --output-file - ``` -------------------------------- ### Generate Verbose Coverage Badge to File with Detailed Output Source: https://smarie.github.io/python-genbadge/reports/junit/report.html This command generates a coverage badge to a file with verbose logging. It also prints detailed coverage results and success messages to stdout. ```bash genbadge coverage -l --verbose --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_coverage_cust20/foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Generate Tests Badge with Verbose Output Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a badge for test results with verbose output enabled, providing detailed processing information. The output is directed to a file. ```bash genbadge tests -l --verbose -i foo/foo.xml -o bar/bar-badge.svg ``` -------------------------------- ### Generate Coverage Badge to Stdout Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a coverage badge and outputs it directly to standard output. Useful for piping to other commands or for immediate display. ```bash genbadge coverage -l -i foo/foo.xml -o - ``` -------------------------------- ### Generate Coverage Badge with Verbose Output Source: https://smarie.github.io/python-genbadge Use the '-v' flag to display detailed parsing and creation information for the coverage badge. This helps in debugging and understanding the process. ```bash Coverage results parsed successfully from '(...)/reports/coverage/coverage.xml' - Branch coverage: 5.56% (1/18) - Line coverage: 17.81% (13/73) - Total coverage: 15.38% ((1+13)/(18+73)) SUCCESS - Coverage badge created: '(...)/coverage-badge.svg' ``` -------------------------------- ### Load Badge Template Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_badge.source.html Reads the SVG badge template from package resources. Includes error handling for specific Python 2 environments. ```python def get_local_badge_template(): """Reads the SVG file template fgrom the package resources""" template_path = "badge-template.svg" try: template = _resource_string("genbadge", template_path).decode('utf8') except IOError: # error when running on python 2 inside the CliInvoker from click with a change of os.cwd. import genbadge reload(genbadge) # noqa template = _resource_string("genbadge", template_path).decode('utf8') return template ``` -------------------------------- ### Generate Tests Badge to File (Verbose, Silent) Source: https://smarie.github.io/python-genbadge/reports/junit/report.html This command generates a tests badge and saves it to a specified SVG file. The --verbose and --silent flags control the output detail. ```bash genbadge tests -l --verbose --silent --input-file foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Import Path Module Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_main_py.html Imports the Path module for handling file paths. Includes a fallback for older Python versions. ```python try: from pathlib import Path except ImportError: # pragma: no cover from pathlib2 import Path # python 2 ``` -------------------------------- ### Process Input File Path Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.main.source.html Handles the logic for determining the input file path. It defaults to a provided file if none is specified and resolves the absolute path for string inputs. ```python def _process_infile(input_file, default_in_file): """Common in file processor""" if input_file is None: input_file = default_in_file if isinstance(input_file, str): input_file_path = Path(input_file).absolute().as_posix() else: input_file_path = getattr(input_file, "name", "") return input_file, input_file_path ``` -------------------------------- ### Import necessary modules for genbadge Source: https://smarie.github.io/python-genbadge/reports/flake8/genbadge.utils_badge.source.html Imports standard libraries like os and sys, along with Pillow for image manipulation and pathlib for path operations. It includes fallback imports for compatibility with older Python versions. ```python import os import sys from PIL import ImageFont try: from pathlib import Path except ImportError: # pragma: no cover from pathlib2 import Path # python 2 try: from typing import Union except ImportError: # pragma: no cover pass # Migration from pkg_resources to importlib.resources try: # Python 3.9+ from importlib.resources import files, as_file except ImportError: # pragma: no cover try: # Python 3.7-3.8 (importlib_resources backport) from importlib_resources import files, as_file except ImportError: # pragma: no cover files = None as_file = None ``` -------------------------------- ### Generate Verbose Tests Badge Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a 'tests' badge with verbose output enabled, providing detailed information about the parsing and generation process. The output SVG is saved to a file. ```bash genbadge tests -l --verbose --input-file foo/foo.xml --output-file bar/bar-badge.svg ``` -------------------------------- ### Fallback for importlib.resources in older Python versions Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_badge_py.html Provides a fallback mechanism for reading package resources, compatible with older Python versions that may not support importlib.resources. ```python def _resource_string(package, resource_name): """Fallback for importlib.resources in older Python versions.""" if files and as_file: with as_file(files(package) / resource_name) as f: return f.read_bytes() else: # Fallback to pkg_resources for older Python versions from pkg_resources import resource_string return resource_string(package, resource_name) ``` -------------------------------- ### Generate SVG Badge Locally Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_badge_py.html Generates an SVG badge from a local template, filling in provided text and color. Use when shields.io is not desired. ```python def get_svg_badge( label_txt, # type: str msg_txt, # type: str color, # type: str label_color=None ): # type: (...) -> str """ Reads the SVG template from the package, fills the various information from args and returns the svg string """ all_text = "%s: %s" % (label_txt, msg_txt) if label_txt else ("%s" % msg_txt) # Same principle as in shields.io template = get_local_badge_template() horiz_padding = 5 vertical_margin = 0 has_logo = False # TODO when a logo is inserted total_logo_width = 0 has_label = len(label_txt) > 0 or label_color label_color = label_color or '#555' label_margin = total_logo_width + 1 def process_text(left_margin, content): """From renderText() https://github.com/badges/shields/blob/4415d07e8b5bf794e6675cea052cc644d0c81bb5/badge-maker/lib/badge-renderers.js#L113 """ text_length = preferred_width_of(content, font_size=11, font_name="Verdana") # todo content = escape_xml(content) shadow_margin = 150 + vertical_margin text_margin = 140 + vertical_margin out_text_length = 10 * text_length x = 10 * (left_margin + 0.5 * text_length + horiz_padding) return x, shadow_margin, text_margin, text_length, out_text_length label_x, label_shadow_margin, label_text_margin, label_width, label_text_length = \ process_text(label_margin, content=label_txt) left_width = (label_width + 2 * horiz_padding + total_logo_width) if has_label else 0 msg_margin = left_width - (1 if len(msg_txt) > 0 else 0) if not has_label: pass ``` -------------------------------- ### Generate Tests Badge to Stdout (Silent) Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a 'tests' badge and prints the SVG to standard output without any additional logging. This is useful for scripting where only the SVG output is needed. ```bash genbadge tests -l --silent --input-file foo/foo.xml --output-file - ``` -------------------------------- ### Generate Flake8 Badge (Success) Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a Flake8 badge indicating success and saves it to a default file path. This command is used when Flake8 checks pass. ```bash genbadge flake8 -l SUCCESS - Flake8 badge created: '/tmp/pytest-of-runner/pytest-0/test_any_command_flake8_defaul0/flake8-badge.svg' ``` -------------------------------- ### Determine Badge Color from Coverage Rate Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_coverage_py.html Returns a color string ('red', 'orange', 'green', 'brightgreen') based on the total coverage percentage. Used to visually represent coverage levels. ```python def get_color( cov_stats # type: CoverageStats ): """ Returns the badge color to use depending on the coverage rate """ if cov_stats.total_coverage < 50: color = 'red' elif cov_stats.total_coverage < 75: color = 'orange' elif cov_stats.total_coverage < 90: color = 'green' else: color = 'brightgreen' return color ``` -------------------------------- ### Generate Verbose Coverage Badge to Stdout Source: https://smarie.github.io/python-genbadge/reports/junit/report.html This command generates a coverage badge to standard output with verbose logging enabled. Verbose output provides more details about the process. ```bash genbadge coverage -l --silent --input-file /tmp/pytest-of-runner/pytest-0/test_any_command_coverage_cust19/foo/foo.xml --output-file - ``` -------------------------------- ### Generate Tests Badge to Stdout (Verbose, Silent) Source: https://smarie.github.io/python-genbadge/reports/junit/report.html Generates a tests badge and outputs the SVG to standard output, using verbose and silent modes. This is useful for piping the SVG to other commands. ```bash genbadge tests -l --verbose --silent --input-file foo/foo.xml --output-file - ``` -------------------------------- ### Generate SVG Badge using Shields.io Source: https://smarie.github.io/python-genbadge/reports/coverage/z_54579382f1cf822d_utils_badge_py.html Generates an SVG badge by fetching it from shields.io. Useful for standard badge formats. Requires the 'requests' library. ```python import requests # url encode test safe_left_txt = requests.utils.quote(self.left_txt, safe='') safe_right_txt = requests.utils.quote(self.right_txt, safe='') safe_color_txt = requests.utils.quote(self.color, safe='') url = 'https://img.shields.io/badge/%s-%s-%s.svg' % (safe_left_txt, safe_right_txt, safe_color_txt) response = requests.get(url, stream=True) return response.text ```