How to use the coverage.env function in coverage

To help you get started, we’ve selected a few coverage examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nedbat / coveragepy / tests / test_files.py View on Github external
def setUp(self):
        if not env.WINDOWS:
            self.skipTest("Only need to run Windows tests on Windows.")
        super(WindowsFileTest, self).setUp()
github nedbat / coveragepy / tests / test_process.py View on Github external
def test_subprocess_with_pth_files(self):           # pragma: no metacov
        if env.METACOV:
            self.skipTest("Can't test sub-process pth file suppport during metacoverage")

        # An existing data file should not be read when a subprocess gets
        # measured automatically.  Create the data file here with bogus data in
        # it.
        data = coverage.CoverageData(".mycovdata")
        data.add_lines({os.path.abspath('sub.py'): dict.fromkeys(range(100))})
        data.write()

        self.make_file("coverage.ini", """\
            [run]
            data_file = .mycovdata
            """)
        self.set_environ("COVERAGE_PROCESS_START", "coverage.ini")
        import main             # pylint: disable=unused-import
github nedbat / coveragepy / tests / test_parser.py View on Github external
def parse_source(self, text):
        """Parse `text` as source, and return the `PythonParser` used."""
        if env.PY2:
            text = text.decode("ascii")
        text = textwrap.dedent(text)
        parser = PythonParser(text=text, exclude="nocover")
        parser.parse_source()
        return parser
github nedbat / coveragepy / tests / test_plugins.py View on Github external
def setUp(self):
        if not env.C_TRACER:
            self.skipTest("Plugins are only supported with the C tracer.")
        super(FileTracerTest, self).setUp()
github nedbat / coveragepy / tests / test_arcs.py View on Github external
self.check_coverage("""\
            a, i = 1, 0
            while 1:
                if i >= 3:
                    a = 4
                    break
                i += 1
            assert a == 4 and i == 3
            """,
            arcz=arcz,
            )
        # With "while True", 2.x thinks it's computation,
        # 3.x thinks it's constant.
        if env.PYBEHAVIOR.nix_while_true:
            arcz = ".1 13 34 45 36 63 57 7."
        elif env.PY3:
            arcz = ".1 12 23 34 45 36 63 57 7."
        else:
            arcz = ".1 12 23 34 45 36 62 57 7."
        self.check_coverage("""\
            a, i = 1, 0
            while True:
                if i >= 3:
                    a = 4
                    break
                i += 1
            assert a == 4 and i == 3
            """,
            arcz=arcz,
        )
github nedbat / coveragepy / coverage / cmdline.py View on Github external
def unshell_list(s):
    """Turn a command-line argument into a list."""
    if not s:
        return None
    if env.WINDOWS:
        # When running coverage.py as coverage.exe, some of the behavior
        # of the shell is emulated: wildcards are expanded into a list of
        # file names.  So you have to single-quote patterns on the command
        # line, but (not) helpfully, the single quotes are included in the
        # argument, so we have to strip them off here.
        s = s.strip("'")
    return s.split(',')
github nedbat / coveragepy / coverage / files.py View on Github external
normtail = os.path.normcase(tail)
            for f in files:
                if os.path.normcase(f) == normtail:
                    tail = f
                    break
            actpath = os.path.join(head, tail)
        _ACTUAL_PATH_CACHE[path] = actpath
        return actpath

else:
    def actual_path(filename):
        """The actual path for non-Windows platforms."""
        return filename


if env.PY2:
    @contract(returns='unicode')
    def unicode_filename(filename):
        """Return a Unicode version of `filename`."""
        if isinstance(filename, str):
            encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
            filename = filename.decode(encoding, "replace")
        return filename
else:
    @contract(filename='unicode', returns='unicode')
    def unicode_filename(filename):
        """Return a Unicode version of `filename`."""
        return filename


@contract(returns='unicode')
def abs_file(path):
github nedbat / coveragepy / coverage / python.py View on Github external
def read_python_source(filename):
    """Read the Python source text from `filename`.

    Returns bytes.

    """
    with open(filename, "rb") as f:
        source = f.read()

    if env.IRONPYTHON:
        # IronPython reads Unicode strings even for "rb" files.
        source = bytes(source)

    return source.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
github nedbat / coveragepy / coverage / phystokens.py View on Github external
@contract(source='bytes')
def _source_encoding_py3(source):
    """Determine the encoding for `source`, according to PEP 263.

    `source` is a byte string: the text of the program.

    Returns a string, the name of the encoding.

    """
    readline = iternext(source.splitlines(True))
    return tokenize.detect_encoding(readline)[0]


if env.PY3:
    source_encoding = _source_encoding_py3
else:
    source_encoding = _source_encoding_py2


@contract(source='unicode')
def compile_unicode(source, filename, mode):
    """Just like the `compile` builtin, but works on any Unicode string.

    Python 2's compile() builtin has a stupid restriction: if the source string
    is Unicode, then it may not have a encoding declaration in it.  Why not?
    Who knows!  It also decodes to utf8, and then tries to interpret those utf8
    bytes according to the encoding declaration.  Why? Who knows!

    This function neuters the coding declaration, and compiles it.
github nedbat / coveragepy / coverage / misc.py View on Github external
return ISOLATED_MODULES[mod]

os = isolate_module(os)


def dummy_decorator_with_args(*args_unused, **kwargs_unused):
    """Dummy no-op implementation of a decorator with arguments."""
    def _decorator(func):
        return func
    return _decorator


# Environment COVERAGE_NO_CONTRACTS=1 can turn off contracts while debugging
# tests to remove noise from stack traces.
# $set_env.py: COVERAGE_NO_CONTRACTS - Disable PyContracts to simplify stack traces.
USE_CONTRACTS = env.TESTING and not bool(int(os.environ.get("COVERAGE_NO_CONTRACTS", 0)))

# Use PyContracts for assertion testing on parameters and returns, but only if
# we are running our own test suite.
if USE_CONTRACTS:
    from contracts import contract              # pylint: disable=unused-import
    from contracts import new_contract as raw_new_contract

    def new_contract(*args, **kwargs):
        """A proxy for contracts.new_contract that doesn't mind happening twice."""
        try:
            return raw_new_contract(*args, **kwargs)
        except ValueError:
            # During meta-coverage, this module is imported twice, and
            # PyContracts doesn't like redefining contracts. It's OK.
            pass