<commit_before># Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt

"""Base test case class for coverage.py testing."""

import contextlib
import datetime
import difflib
import glob
import io
import os
import os.path
import random
import re
import shlex
import sys

import pytest

import coverage
from coverage import env
from coverage.cmdline import CoverageScript
from coverage.misc import import_local_file

from tests.helpers import arcs_to_arcz_repr, arcz_to_arcs, assert_count_equal
from tests.helpers import nice_file, run_command
from tests.mixins import PytestBase, StdStreamCapturingMixin, RestoreModulesMixin, TempDirMixin


# Status returns for the command line.
OK, ERR = 0, 1

# The coverage/tests directory, for all sorts of finding test helping things.
TESTS_DIR = os.path.dirname(__file__)

# Install arguments to pass to pip when reinstalling ourselves.
# Defaults to the top of the source tree, but can be overridden if we need
# some help on certain platforms.
COVERAGE_INSTALL_ARGS = os.getenv("COVERAGE_INSTALL_ARGS", nice_file(TESTS_DIR, ".."))


class CoverageTest(
    StdStreamCapturingMixin,
    RestoreModulesMixin,
    TempDirMixin,
    PytestBase,
):
    """A base class for coverage.py test cases."""

    # Standard unittest setting: show me diffs even if they are very long.
    maxDiff = None

    # Tell newer unittest implementations to print long helpful messages.
    longMessage = True

    # Let stderr go to stderr, pytest will capture it for us.
    show_stderr = True

    def setUp(self):
        super().setUp()

        # Attributes for getting info about what happened.
        self.last_command_status = None
        self.last_command_output = None
        self.last_module_name = None

    def start_import_stop(self, cov, modname, modfile=None):
        """Start coverage, import a file, then stop coverage.

        `cov` is started and stopped, with an `import_local_file` of
        `modname` in the middle. `modfile` is the file to import as `modname`
        if it isn't in the current directory.

        The imported module is returned.

        """
        cov.start()
        try:                                    # pragma: nested
            # Import the Python file, executing it.
            mod = import_local_file(modname, modfile)
        finally:                                # pragma: nested
            # Stop coverage.py.
            cov.stop()
        return mod

    def get_report(self, cov, squeeze=True, **kwargs):
        """Get the report from `cov`, and canonicalize it."""
        repout = io.StringIO()
        kwargs.setdefault("show_missing", False)
        cov.report(file=repout, **kwargs)
        report = repout.getvalue().replace('\\', '/')
        if squeeze:
            report = re.sub(r" +", " ", report)
        return report

    def get_module_name(self):
        """Return a random module name to use for this test run."""
        self.last_module_name = 'coverage_test_' + str(random.random())[2:]
        return self.last_module_name

    def _check_arcs(self, a1, a2, arc_type):
        """Check that the arc lists `a1` and `a2` are equal.

        If they are equal, return empty string. If they are unequal, return
        a string explaining what is different.
        """
        # Make them into multi-line strings so we can see what's going wrong.
        s1 = arcs_to_arcz_repr(a1)
        s2 = arcs_to_arcz_repr(a2)
        if s1 != s2:
            lines1 = s1.splitlines(True)
            lines2 = s2.splitlines(True)
            diff = "".join(difflib.ndiff(lines1, lines2))
            return "\n" + arc_type + " arcs differ: minus is expected, plus is actual\n" + diff
        else:
            return ""

    def check_coverage(<commit_msg>test: a utility print for when reporting tests fail<commit_after># Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt

"""Base test case class for coverage.py testing."""

import contextlib
import datetime
import difflib
import glob
import io
import os
import os.path
import random
import re
import shlex
import sys

import pytest

import coverage
from coverage import env
from coverage.cmdline import CoverageScript
from coverage.misc import import_local_file

from tests.helpers import arcs_to_arcz_repr, arcz_to_arcs, assert_count_equal
from tests.helpers import nice_file, run_command
from tests.mixins import PytestBase, StdStreamCapturingMixin, RestoreModulesMixin, TempDirMixin


# Status returns for the command line.
OK, ERR = 0, 1

# The coverage/tests directory, for all sorts of finding test helping things.
TESTS_DIR = os.path.dirname(__file__)

# Install arguments to pass to pip when reinstalling ourselves.
# Defaults to the top of the source tree, but can be overridden if we need
# some help on certain platforms.
COVERAGE_INSTALL_ARGS = os.getenv("COVERAGE_INSTALL_ARGS", nice_file(TESTS_DIR, ".."))


class CoverageTest(
    StdStreamCapturingMixin,
    RestoreModulesMixin,
    TempDirMixin,
    PytestBase,
):
    """A base class for coverage.py test cases."""

    # Standard unittest setting: show me diffs even if they are very long.
    maxDiff = None

    # Tell newer unittest implementations to print long helpful messages.
    longMessage = True

    # Let stderr go to stderr, pytest will capture it for us.
    show_stderr = True

    def setUp(self):
        super().setUp()

        # Attributes for getting info about what happened.
        self.last_command_status = None
        self.last_command_output = None
        self.last_module_name = None

    def start_import_stop(self, cov, modname, modfile=None):
        """Start coverage, import a file, then stop coverage.

        `cov` is started and stopped, with an `import_local_file` of
        `modname` in the middle. `modfile` is the file to import as `modname`
        if it isn't in the current directory.

        The imported module is returned.

        """
        cov.start()
        try:                                    # pragma: nested
            # Import the Python file, executing it.
            mod = import_local_file(modname, modfile)
        finally:                                # pragma: nested
            # Stop coverage.py.
            cov.stop()
        return mod

    def get_report(self, cov, squeeze=True, **kwargs):
        """Get the report from `cov`, and canonicalize it."""
        repout = io.StringIO()
        kwargs.setdefault("show_missing", False)
        cov.report(file=repout, **kwargs)
        report = repout.getvalue().replace('\\', '/')
        print(report)   # When tests fail, it's helpful to see the output
        if squeeze:
            report = re.sub(r" +", " ", report)
        return report

    def get_module_name(self):
        """Return a random module name to use for this test run."""
        self.last_module_name = 'coverage_test_' + str(random.random())[2:]
        return self.last_module_name

    def _check_arcs(self, a1, a2, arc_type):
        """Check that the arc lists `a1` and `a2` are equal.

        If they are equal, return empty string. If they are unequal, return
        a string explaining what is different.
        """
        # Make them into multi-line strings so we can see what's going wrong.
        s1 = arcs_to_arcz_repr(a1)
        s2 = arcs_to_arcz_repr(a2)
        if s1 != s2:
            lines1 = s1.splitlines(True)
            lines2 = s2.splitlines(True)
            diff = "".join(difflib.ndiff(lines1, lines2))
            return "\n" + arc_type + " arcs differ: minus is expected, plus is actual\n" + diff
        else:
            return ""

    def check_coverage(
{'fraction_non_alphanumeric': 0.08484538717096857, 'fraction_numerical': 0.005366726296958855, 'mean_word_length': 2.6370817843866172, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7281934', 'n_tokens_mistral': 2304, 'n_tokens_neox': 2241, 'n_words': 783}