diff options
33 files changed, 171 insertions, 186 deletions
diff --git a/tests/conftest.py b/tests/conftest.py index 201a6e0e..a2577086 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -111,4 +111,4 @@ def pytest_runtest_call(item): """Convert StopEverything into skipped tests.""" outcome = yield if outcome.excinfo and issubclass(outcome.excinfo[0], StopEverything): - pytest.skip("Skipping {} for StopEverything: {}".format(item.nodeid, outcome.excinfo[1])) + pytest.skip(f"Skipping {item.nodeid} for StopEverything: {outcome.excinfo[1]}") diff --git a/tests/coveragetest.py b/tests/coveragetest.py index 1163e349..287b585d 100644 --- a/tests/coveragetest.py +++ b/tests/coveragetest.py @@ -61,7 +61,7 @@ class CoverageTest( keep_temp_dir = bool(int(os.getenv("COVERAGE_KEEP_TMP", "0"))) def setup_test(self): - super(CoverageTest, self).setup_test() + super().setup_test() # Attributes for getting info about what happened. self.last_command_status = None @@ -166,7 +166,7 @@ class CoverageTest( if isinstance(lines[0], int): # lines is just a list of numbers, it must match the statements # found in the code. - assert statements == lines, "{!r} != {!r}".format(statements, lines) + assert statements == lines, f"{statements!r} != {lines!r}" else: # lines is a list of possible line number lists, one of them # must match. @@ -174,18 +174,18 @@ class CoverageTest( if statements == line_list: break else: - assert False, "None of the lines choices matched %r" % (statements,) + assert False, f"None of the lines choices matched {statements!r}" missing_formatted = analysis.missing_formatted() if isinstance(missing, str): - msg = "{!r} != {!r}".format(missing_formatted, missing) + msg = f"{missing_formatted!r} != {missing!r}" assert missing_formatted == missing, msg else: for missing_list in missing: if missing_formatted == missing_list: break else: - assert False, "None of the missing choices matched %r" % (missing_formatted,) + assert False, f"None of the missing choices matched {missing_formatted!r}" if arcs is not None: # print("Possible arcs:") @@ -206,7 +206,7 @@ class CoverageTest( frep = io.StringIO() cov.report(mod, file=frep, show_missing=True) rep = " ".join(frep.getvalue().split("\n")[2].split()[1:]) - assert report == rep, "{!r} != {!r}".format(report, rep) + assert report == rep, f"{report!r} != {rep!r}" return cov @@ -232,7 +232,7 @@ class CoverageTest( """A fake implementation of Coverage._warn, to capture warnings.""" # NOTE: we don't implement `once`. if slug: - msg = "%s (%s)" % (msg, slug) + msg = f"{msg} ({slug})" saved_warnings.append(msg) original_warn = cov._warn @@ -249,17 +249,17 @@ class CoverageTest( if re.search(warning_regex, saved): break else: - msg = "Didn't find warning %r in %r" % (warning_regex, saved_warnings) + msg = f"Didn't find warning {warning_regex!r} in {saved_warnings!r}" assert False, msg for warning_regex in not_warnings: for saved in saved_warnings: if re.search(warning_regex, saved): - msg = "Found warning %r in %r" % (warning_regex, saved_warnings) + msg = f"Found warning {warning_regex!r} in {saved_warnings!r}" assert False, msg else: # No warnings expected. Raise if any warnings happened. if saved_warnings: - assert False, "Unexpected warnings: %r" % (saved_warnings,) + assert False, f"Unexpected warnings: {saved_warnings!r}" finally: cov._warn = original_warn @@ -305,7 +305,7 @@ class CoverageTest( """ ret_actual = command_line(args) - assert ret_actual == ret, "{!r} != {!r}".format(ret_actual, ret) + assert ret_actual == ret, f"{ret_actual!r} != {ret!r}" # Some distros rename the coverage command, and need a way to indicate # their new command name to the tests. This is here for them to override, @@ -440,11 +440,11 @@ class CoverageTest( for filename in coverage_data.measured_files()} -class UsingModulesMixin(object): +class UsingModulesMixin: """A mixin for importing modules from tests/modules and tests/moremodules.""" def setup_test(self): - super(UsingModulesMixin, self).setup_test() + super().setup_test() # Parent class saves and restores sys.path, we can just modify it. sys.path.append(nice_file(TESTS_DIR, "modules")) diff --git a/tests/goldtest.py b/tests/goldtest.py index 16301417..7ea42754 100644 --- a/tests/goldtest.py +++ b/tests/goldtest.py @@ -44,7 +44,7 @@ def versioned_directory(d): subdir = os.path.join(d, version) if os.path.exists(subdir): return subdir - raise Exception("Directory missing: {}".format(d)) # pragma: only failure + raise Exception(f"Directory missing: {d}") # pragma: only failure def compare( @@ -95,17 +95,17 @@ def compare( expected = scrub(expected, scrubs) actual = scrub(actual, scrubs) if expected != actual: # pragma: only failure - text_diff.append('%s != %s' % (expected_file, actual_file)) + text_diff.append(f'{expected_file} != {actual_file}') expected = expected.splitlines() actual = actual.splitlines() - print(":::: diff {!r} and {!r}".format(expected_file, actual_file)) + print(f":::: diff {expected_file!r} and {actual_file!r}") print("\n".join(difflib.Differ().compare(expected, actual))) - print(":::: end diff {!r} and {!r}".format(expected_file, actual_file)) + print(f":::: end diff {expected_file!r} and {actual_file!r}") assert not text_diff, "Files differ: %s" % '\n'.join(text_diff) - assert not expected_only, "Files in %s only: %s" % (expected_dir, expected_only) + assert not expected_only, f"Files in {expected_dir} only: {expected_only}" if not actual_extra: - assert not actual_only, "Files in %s only: %s" % (actual_dir, actual_only) + assert not actual_only, f"Files in {actual_dir} only: {actual_only}" def canonicalize_xml(xtext): @@ -124,10 +124,10 @@ def contains(filename, *strlist): missing in `filename`. """ - with open(filename, "r") as fobj: + with open(filename) as fobj: text = fobj.read() for s in strlist: - assert s in text, "Missing content in %s: %r" % (filename, s) + assert s in text, f"Missing content in {filename}: {s!r}" def contains_any(filename, *strlist): @@ -137,7 +137,7 @@ def contains_any(filename, *strlist): `filename`. """ - with open(filename, "r") as fobj: + with open(filename) as fobj: text = fobj.read() for s in strlist: if s in text: @@ -155,10 +155,10 @@ def doesnt_contain(filename, *strlist): `filename`. """ - with open(filename, "r") as fobj: + with open(filename) as fobj: text = fobj.read() for s in strlist: - assert s not in text, "Forbidden content in %s: %r" % (filename, s) + assert s not in text, f"Forbidden content in {filename}: {s!r}" # Helpers diff --git a/tests/helpers.py b/tests/helpers.py index 93583b8b..21459cd4 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -12,7 +12,7 @@ import re import subprocess import textwrap -import mock +from unittest import mock from coverage.misc import output_encoding @@ -90,7 +90,7 @@ def nice_file(*fparts): return os.path.normcase(os.path.abspath(os.path.realpath(fname))) -class CheckUniqueFilenames(object): +class CheckUniqueFilenames: """Asserts the uniqueness of file names passed to a function.""" def __init__(self, wrapped): self.filenames = set() @@ -115,7 +115,7 @@ class CheckUniqueFilenames(object): def wrapper(self, filename, *args, **kwargs): """The replacement method. Check that we don't have dupes.""" assert filename not in self.filenames, ( - "File name %r passed to %r twice" % (filename, self.wrapped) + f"File name {filename!r} passed to {self.wrapped!r} twice" ) self.filenames.add(filename) ret = self.wrapped(filename, *args, **kwargs) @@ -154,10 +154,8 @@ def remove_files(*patterns): # Map chars to numbers for arcz_to_arcs _arcz_map = {'.': -1} -_arcz_map.update(dict((c, ord(c) - ord('0')) for c in '123456789')) -_arcz_map.update(dict( - (c, 10 + ord(c) - ord('A')) for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' -)) +_arcz_map.update({c: ord(c) - ord('0') for c in '123456789'}) +_arcz_map.update({c: 10 + ord(c) - ord('A') for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}) def arcz_to_arcs(arcz): """Convert a compact textual representation of arcs to a list of pairs. diff --git a/tests/mixins.py b/tests/mixins.py index 44b16f6c..dd9b4e3e 100644 --- a/tests/mixins.py +++ b/tests/mixins.py @@ -18,7 +18,7 @@ import pytest from tests.helpers import change_dir, make_file, remove_files -class PytestBase(object): +class PytestBase: """A base class to connect to pytest in a test class hierarchy.""" @pytest.fixture(autouse=True) @@ -49,7 +49,7 @@ class PytestBase(object): self._monkeypatch.delenv(name, raising=False) -class TempDirMixin(object): +class TempDirMixin: """Provides temp dir and data file helpers for tests.""" # Our own setting: most of these tests run in their own temp directory. diff --git a/tests/modules/pkg1/__init__.py b/tests/modules/pkg1/__init__.py index 3390a854..dbef951c 100644 --- a/tests/modules/pkg1/__init__.py +++ b/tests/modules/pkg1/__init__.py @@ -1,2 +1,2 @@ # A simple package for testing with. -print("pkg1.__init__: %s" % (__name__,)) +print(f"pkg1.__init__: {__name__}") diff --git a/tests/osinfo.py b/tests/osinfo.py index f9562deb..ec34c709 100644 --- a/tests/osinfo.py +++ b/tests/osinfo.py @@ -50,7 +50,7 @@ elif env.LINUX: # Get pseudo file /proc/<pid>/status with open('/proc/%d/status' % os.getpid()) as t: v = t.read() - except IOError: # pragma: cant happen + except OSError: # pragma: cant happen return 0 # non-Linux? # Get VmKey line e.g. 'VmRSS: 9999 kB\n ...' i = v.index(key) diff --git a/tests/test_annotate.py b/tests/test_annotate.py index 051a31ee..de6edcd0 100644 --- a/tests/test_annotate.py +++ b/tests/test_annotate.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt diff --git a/tests/test_api.py b/tests/test_api.py index 57154d64..05554ae4 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -629,7 +629,7 @@ class ApiTest(CoverageTest): # Labeled data is collected data = cov.get_data() - assert [u'', u'multiply_six', u'multiply_zero'] == sorted(data.measured_contexts()) + assert ['', 'multiply_six', 'multiply_zero'] == sorted(data.measured_contexts()) filenames = self.get_measured_filenames(data) suite_filename = filenames['testsuite.py'] @@ -667,7 +667,7 @@ class ApiTest(CoverageTest): # Labeled data is collected data = cov.get_data() - expected = [u'mysuite', u'mysuite|multiply_six', u'mysuite|multiply_zero'] + expected = ['mysuite', 'mysuite|multiply_six', 'mysuite|multiply_zero'] assert expected == sorted(data.measured_contexts()) filenames = self.get_measured_filenames(data) diff --git a/tests/test_cmdline.py b/tests/test_cmdline.py index adbbc619..ed5090f5 100644 --- a/tests/test_cmdline.py +++ b/tests/test_cmdline.py @@ -8,7 +8,7 @@ import pprint import sys import textwrap -import mock +from unittest import mock import pytest import coverage @@ -58,7 +58,7 @@ class BaseCmdLineTest(CoverageTest): concurrency=None, check_preimported=True, context=None, ) - DEFAULT_KWARGS = dict((name, kw) for name, _, kw in _defaults.mock_calls) + DEFAULT_KWARGS = {name: kw for name, _, kw in _defaults.mock_calls} def model_object(self): """Return a Mock suitable for use in CoverageScript.""" @@ -113,7 +113,7 @@ class BaseCmdLineTest(CoverageTest): def cmd_executes(self, args, code, ret=OK, options=None): """Assert that the `args` end up executing the sequence in `code`.""" called, status = self.mock_command_line(args, options=options) - assert status == ret, "Wrong status: got %r, wanted %r" % (status, ret) + assert status == ret, f"Wrong status: got {status!r}, wanted {ret!r}" # Remove all indentation, and execute with mock globals code = textwrap.dedent(code) @@ -157,7 +157,7 @@ class BaseCmdLineTest(CoverageTest): """ mk, status = self.mock_command_line(args) - assert status == ret, "Wrong status: got %s, wanted %s" % (status, ret) + assert status == ret, f"Wrong status: got {status}, wanted {ret}" if help_msg: assert mk.mock_calls[-1] == ('show_help', (help_msg,), {}) else: @@ -846,7 +846,7 @@ class CmdLineStdoutTest(BaseCmdLineTest): self.command_line("help") lines = self.stdout().splitlines() assert len(lines) > 10 - assert lines[-1] == "Full documentation is at {}".format(__url__) + assert lines[-1] == f"Full documentation is at {__url__}" def test_cmd_help(self): self.command_line("help run") @@ -855,14 +855,14 @@ class CmdLineStdoutTest(BaseCmdLineTest): assert "<pyfile>" in lines[0] assert "--timid" in out assert len(lines) > 20 - assert lines[-1] == "Full documentation is at {}".format(__url__) + assert lines[-1] == f"Full documentation is at {__url__}" def test_unknown_topic(self): # Should probably be an ERR return, but meh. self.command_line("help foobar") lines = self.stdout().splitlines() assert lines[0] == "Don't know topic 'foobar'" - assert lines[-1] == "Full documentation is at {}".format(__url__) + assert lines[-1] == f"Full documentation is at {__url__}" def test_error(self): self.command_line("fooey kablooey", ret=ERR) @@ -879,7 +879,7 @@ class CmdMainTest(CoverageTest): run_in_temp_dir = False - class CoverageScriptStub(object): + class CoverageScriptStub: """A stub for coverage.cmdline.CoverageScript, used by CmdMainTest.""" def command_line(self, argv): @@ -896,11 +896,11 @@ class CmdMainTest(CoverageTest): elif argv[0] == 'exit': sys.exit(23) else: - raise AssertionError("Bad CoverageScriptStub: %r" % (argv,)) + raise AssertionError(f"Bad CoverageScriptStub: {argv!r}") return 0 def setup_test(self): - super(CmdMainTest, self).setup_test() + super().setup_test() old_CoverageScript = coverage.cmdline.CoverageScript coverage.cmdline.CoverageScript = self.CoverageScriptStub self.addCleanup(setattr, coverage.cmdline, 'CoverageScript', old_CoverageScript) @@ -929,7 +929,7 @@ class CmdMainTest(CoverageTest): assert ret == 23 -class CoverageReportingFake(object): +class CoverageReportingFake: """A fake Coverage.coverage test double.""" # pylint: disable=missing-function-docstring def __init__(self, report_result, html_result, xml_result, json_report): diff --git a/tests/test_concurrency.py b/tests/test_concurrency.py index 9cc1f3b6..a5aed4f1 100644 --- a/tests/test_concurrency.py +++ b/tests/test_concurrency.py @@ -240,7 +240,7 @@ class ConcurrencyTest(CoverageTest): # If the test fails, it's helpful to see this info: fname = abs_file("try_it.py") linenos = data.lines(fname) - print("{}: {}".format(len(linenos), linenos)) + print(f"{len(linenos)}: {linenos}") print_simple_annotation(code, linenos) lines = line_count(code) @@ -408,7 +408,7 @@ class MultiprocessingTest(CoverageTest): upto = 30 code = (SQUARE_OR_CUBE_WORK + MULTI_CODE).format(NPROCS=nprocs, UPTO=upto) total = sum(x*x if x%2 else x*x*x for x in range(upto)) - expected_out = "{nprocs} pids, total = {total}".format(nprocs=nprocs, total=total) + expected_out = f"{nprocs} pids, total = {total}" self.try_multiprocessing_code(code, expected_out, threading, nprocs) def test_multiprocessing_append(self): @@ -416,7 +416,7 @@ class MultiprocessingTest(CoverageTest): upto = 30 code = (SQUARE_OR_CUBE_WORK + MULTI_CODE).format(NPROCS=nprocs, UPTO=upto) total = sum(x*x if x%2 else x*x*x for x in range(upto)) - expected_out = "{nprocs} pids, total = {total}".format(nprocs=nprocs, total=total) + expected_out = f"{nprocs} pids, total = {total}" self.try_multiprocessing_code(code, expected_out, threading, nprocs, args="--append") def test_multiprocessing_and_gevent(self): @@ -426,7 +426,7 @@ class MultiprocessingTest(CoverageTest): SUM_RANGE_WORK + EVENTLET + SUM_RANGE_Q + MULTI_CODE ).format(NPROCS=nprocs, UPTO=upto) total = sum(sum(range((x + 1) * 100)) for x in range(upto)) - expected_out = "{nprocs} pids, total = {total}".format(nprocs=nprocs, total=total) + expected_out = f"{nprocs} pids, total = {total}" self.try_multiprocessing_code( code, expected_out, eventlet, nprocs, concurrency="multiprocessing,eventlet" ) @@ -450,7 +450,7 @@ class MultiprocessingTest(CoverageTest): if start_method and start_method not in multiprocessing.get_all_start_methods(): continue - out = self.run_command("coverage run --rcfile=multi.rc multi.py %s" % (start_method,)) + out = self.run_command(f"coverage run --rcfile=multi.rc multi.py {start_method}") assert out.rstrip() == expected_out out = self.run_command("coverage combine") @@ -465,7 +465,7 @@ class MultiprocessingTest(CoverageTest): upto = 30 code = (SQUARE_OR_CUBE_WORK + MULTI_CODE).format(NPROCS=nprocs, UPTO=upto) total = sum(x*x if x%2 else x*x*x for x in range(upto)) - expected_out = "{nprocs} pids, total = {total}".format(nprocs=nprocs, total=total) + expected_out = f"{nprocs} pids, total = {total}" self.try_multiprocessing_code_with_branching(code, expected_out) def test_multiprocessing_bootstrap_error_handling(self): @@ -541,7 +541,7 @@ def test_thread_safe_save_data(tmpdir): # Create some Python modules and put them in the path modules_dir = tmpdir.mkdir('test_modules') - module_names = ["m{:03d}".format(i) for i in range(1000)] + module_names = [f"m{i:03d}" for i in range(1000)] for module_name in module_names: modules_dir.join(module_name + ".py").write("def f(): pass\n") diff --git a/tests/test_config.py b/tests/test_config.py index 3330290f..83d756a5 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -6,7 +5,7 @@ from collections import OrderedDict -import mock +from unittest import mock import pytest import coverage @@ -83,13 +82,13 @@ class ConfigTest(CoverageTest): cov = coverage.Coverage(config_file="pyproject.toml") assert cov.config.timid assert not cov.config.branch - assert cov.config.concurrency == [u"a", u"b"] - assert cov.config.data_file == u".hello_kitty.data" - assert cov.config.plugins == [u"plugins.a_plugin"] + assert cov.config.concurrency == ["a", "b"] + assert cov.config.data_file == ".hello_kitty.data" + assert cov.config.plugins == ["plugins.a_plugin"] assert cov.config.precision == 3 - assert cov.config.html_title == u"tabblo & «ταБЬℓσ»" + assert cov.config.html_title == "tabblo & «ταБЬℓσ»" assert round(abs(cov.config.fail_under-90.5), 7) == 0 - assert cov.config.get_plugin_options("plugins.a_plugin") == {u"hello": u"world"} + assert cov.config.get_plugin_options("plugins.a_plugin") == {"hello": "world"} # Test that our class doesn't reject integers when loading floats self.make_file("pyproject.toml", """\ diff --git a/tests/test_context.py b/tests/test_context.py index 688d5cce..b20ecdef 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -205,7 +205,7 @@ def get_qualname(): # pylint: disable=missing-class-docstring, missing-function-docstring, unused-argument -class Parent(object): +class Parent: def meth(self): return get_qualname() @@ -216,7 +216,7 @@ class Parent(object): class Child(Parent): pass -class SomethingElse(object): +class SomethingElse: pass class MultiChild(SomethingElse, Child): @@ -273,5 +273,5 @@ class QualnameTest(CoverageTest): def test_bug_829(self): # A class with a name like a function shouldn't confuse qualname_from_frame. - class test_something(object): # pylint: disable=unused-variable + class test_something: # pylint: disable=unused-variable assert get_qualname() is None diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 559c42a6..3ddc6e86 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt diff --git a/tests/test_data.py b/tests/test_data.py index 30e6df60..867891d4 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -10,7 +10,7 @@ import re import sqlite3 import threading -import mock +from unittest import mock import pytest from coverage.data import CoverageData, combine_parallel_data diff --git a/tests/test_execfile.py b/tests/test_execfile.py index ec8cd180..7c63ac15 100644 --- a/tests/test_execfile.py +++ b/tests/test_execfile.py @@ -86,7 +86,7 @@ class RunFileTest(CoverageTest): def test_no_such_file(self): path = python_reported_file('xyzzy.py') - msg = re.escape("No file to run: '{}'".format(path)) + msg = re.escape(f"No file to run: '{path}'") with pytest.raises(NoSource, match=msg): run_python_file(["xyzzy.py"]) @@ -160,7 +160,7 @@ class RunPycFileTest(CoverageTest): def test_no_such_pyc_file(self): path = python_reported_file('xyzzy.pyc') - msg = re.escape("No file to run: '{}'".format(path)) + msg = re.escape(f"No file to run: '{path}'") with pytest.raises(NoCode, match=msg): run_python_file(["xyzzy.pyc"]) @@ -173,7 +173,7 @@ class RunPycFileTest(CoverageTest): path = python_reported_file('binary') msg = ( - re.escape("Couldn't run '{}' as Python code: ".format(path)) + + re.escape(f"Couldn't run '{path}' as Python code: ") + r"(TypeError|ValueError): " r"(" r"compile\(\) expected string without null bytes" # for py2 diff --git a/tests/test_filereporter.py b/tests/test_filereporter.py index 1e8513f8..e2c71fa2 100644 --- a/tests/test_filereporter.py +++ b/tests/test_filereporter.py @@ -103,5 +103,5 @@ class FileReporterTest(UsingModulesMixin, CoverageTest): z1 = PythonFileReporter(zip1) z1z1 = PythonFileReporter(zip1.zip1) - assert z1.source() == u"" - assert u"# My zip file!" in z1z1.source().splitlines() + assert z1.source() == "" + assert "# My zip file!" in z1z1.source().splitlines() diff --git a/tests/test_files.py b/tests/test_files.py index ed6fef26..cfe37460 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -30,7 +29,7 @@ class FilesTest(CoverageTest): def test_simple(self): self.make_file("hello.py") files.set_relative_directory() - assert files.relative_filename(u"hello.py") == u"hello.py" + assert files.relative_filename("hello.py") == "hello.py" a = self.abs_path("hello.py") assert a != "hello.py" assert files.relative_filename(a) == "hello.py" @@ -70,18 +69,18 @@ class FilesTest(CoverageTest): @pytest.mark.parametrize("original, flat", [ - (u"a/b/c.py", u"a_b_c_py"), - (u"c:\\foo\\bar.html", u"_foo_bar_html"), - (u"Montréal/☺/conf.py", u"Montréal_☺_conf_py"), + ("a/b/c.py", "a_b_c_py"), + (r"c:\foo\bar.html", "_foo_bar_html"), + ("Montréal/☺/conf.py", "Montréal_☺_conf_py"), ( # original: - u"c:\\lorem\\ipsum\\quia\\dolor\\sit\\amet\\consectetur\\adipisci\\velit\\sed\\quia\\non" - u"\\numquam\\eius\\modi\\tempora\\incidunt\\ut\\labore\\et\\dolore\\magnam\\aliquam" - u"\\quaerat\\voluptatem\\ut\\enim\\ad\\minima\\veniam\\quis\\nostrum\\exercitationem" - u"\\ullam\\corporis\\suscipit\\laboriosam\\Montréal\\☺\\my_program.py", + r"c:\lorem\ipsum\quia\dolor\sit\amet\consectetur\adipisci\velit\sed\quia\non" + r"\numquam\eius\modi\tempora\incidunt\ut\labore\et\dolore\magnam\aliquam" + r"\quaerat\voluptatem\ut\enim\ad\minima\veniam\quis\nostrum\exercitationem" + r"\ullam\corporis\suscipit\laboriosam\Montréal\☺\my_program.py", # flat: - u"re_et_dolore_magnam_aliquam_quaerat_voluptatem_ut_enim_ad_minima_veniam_quis_" - u"nostrum_exercitationem_ullam_corporis_suscipit_laboriosam_Montréal_☺_my_program_py_" - u"97eaca41b860faaa1a21349b1f3009bb061cf0a8" + "re_et_dolore_magnam_aliquam_quaerat_voluptatem_ut_enim_ad_minima_veniam_quis_" + "nostrum_exercitationem_ullam_corporis_suscipit_laboriosam_Montréal_☺_my_program_py_" + "97eaca41b860faaa1a21349b1f3009bb061cf0a8" ), ]) def test_flat_rootname(original, flat): @@ -141,13 +140,13 @@ class MatcherTest(CoverageTest): """Tests of file matchers.""" def setup_test(self): - super(MatcherTest, self).setup_test() + super().setup_test() files.set_relative_directory() def assertMatches(self, matcher, filepath, matches): """The `matcher` should agree with `matches` about `filepath`.""" canonical = files.canonical_filename(filepath) - msg = "File %s should have matched as %s" % (filepath, matches) + msg = f"File {filepath} should have matched as {matches}" assert matches == matcher.match(canonical), msg def test_tree_matcher(self): diff --git a/tests/test_html.py b/tests/test_html.py index c561a5d2..3b3250e4 100644 --- a/tests/test_html.py +++ b/tests/test_html.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -12,7 +11,7 @@ import os.path import re import sys -import mock +from unittest import mock import pytest import coverage @@ -93,11 +92,11 @@ class HtmlTestHelpers(CoverageTest): self.assert_recent_datetime( timestamp, seconds=120, - msg="Timestamp is wrong: {}".format(timestamp), + msg=f"Timestamp is wrong: {timestamp}", ) -class FileWriteTracker(object): +class FileWriteTracker: """A fake object to track how `open` is used to write files.""" def __init__(self, written): self.written = written @@ -113,7 +112,7 @@ class HtmlDeltaTest(HtmlTestHelpers, CoverageTest): """Tests of the HTML delta speed-ups.""" def setup_test(self): - super(HtmlDeltaTest, self).setup_test() + super().setup_test() # At least one of our tests monkey-patches the version of coverage.py, # so grab it here to restore it later. @@ -135,7 +134,7 @@ class HtmlDeltaTest(HtmlTestHelpers, CoverageTest): self.files_written = set() mock_open = FileWriteTracker(self.files_written).open with mock.patch("coverage.html.open", mock_open): - return super(HtmlDeltaTest, self).run_coverage(covargs=covargs, htmlargs=htmlargs) + return super().run_coverage(covargs=covargs, htmlargs=htmlargs) def assert_htmlcov_files_exist(self): """Assert that all the expected htmlcov files exist.""" @@ -555,7 +554,7 @@ class HtmlStaticFileTest(CoverageTest): """Tests of the static file copying for the HTML report.""" def setup_test(self): - super(HtmlStaticFileTest, self).setup_test() + super().setup_test() original_path = list(coverage.html.STATIC_PATH) self.addCleanup(setattr, coverage.html, 'STATIC_PATH', original_path) @@ -1039,7 +1038,7 @@ assert len(math) == 18 doesnt_contain("out/tabbed_py.html", "\t") def test_unicode(self): - surrogate = u"\U000e0100" + surrogate = "\U000e0100" self.make_file("unicode.py", """\ # -*- coding: utf-8 -*- diff --git a/tests/test_json.py b/tests/test_json.py index 47955742..b750a666 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt diff --git a/tests/test_misc.py b/tests/test_misc.py index dad542ac..760d8efe 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -36,9 +36,9 @@ class HasherTest(CoverageTest): def test_unicode_hashing(self): h1 = Hasher() - h1.update(u"Hello, world! \N{SNOWMAN}") + h1.update("Hello, world! \N{SNOWMAN}") h2 = Hasher() - h2.update(u"Goodbye!") + h2.update("Goodbye!") assert h1.hexdigest() != h2.hexdigest() def test_dict_hashing(self): @@ -90,14 +90,14 @@ class ContractTest(CoverageTest): assert need_bytes(b"Hey") == b"Hey" assert need_bytes() is None with pytest.raises(Exception): - need_bytes(u"Oops") + need_bytes("Oops") def test_unicode(self): @contract(text='unicode|None') def need_unicode(text=None): return text - assert need_unicode(u"Hey") == u"Hey" + assert need_unicode("Hey") == "Hey" assert need_unicode() is None with pytest.raises(Exception): need_unicode(b"Oops") diff --git a/tests/test_mixins.py b/tests/test_mixins.py index aab1242a..1483b1a2 100644 --- a/tests/test_mixins.py +++ b/tests/test_mixins.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -65,7 +64,7 @@ class SysPathModulessMixinTest(TempDirMixin, SysPathModulesMixin): @pytest.mark.parametrize("val", [17, 42]) def test_module_independence(self, val): - self.make_file("xyzzy.py", "A = {}".format(val)) + self.make_file("xyzzy.py", f"A = {val}") import xyzzy # pylint: disable=import-error assert xyzzy.A == val diff --git a/tests/test_numbits.py b/tests/test_numbits.py index 98399086..3f69b4de 100644 --- a/tests/test_numbits.py +++ b/tests/test_numbits.py @@ -99,7 +99,7 @@ class NumbitsSqliteFunctionTest(CoverageTest): run_in_temp_dir = False def setup_test(self): - super(NumbitsSqliteFunctionTest, self).setup_test() + super().setup_test() conn = sqlite3.connect(":memory:") register_sqlite_functions(conn) self.cursor = conn.cursor() diff --git a/tests/test_oddball.py b/tests/test_oddball.py index 2e438396..d6a14f9f 100644 --- a/tests/test_oddball.py +++ b/tests/test_oddball.py @@ -271,7 +271,7 @@ class PyexpatTest(CoverageTest): # Make sure pyexpat isn't recorded as a source file. # https://github.com/nedbat/coveragepy/issues/419 files = cov.get_data().measured_files() - msg = "Pyexpat.c is in the measured files!: %r:" % (files,) + msg = f"Pyexpat.c is in the measured files!: {files!r}:" assert not any(f.endswith("pyexpat.c") for f in files), msg @@ -573,8 +573,7 @@ class MockingProtectionTest(CoverageTest): # StopIteration error. self.make_file("bug416.py", """\ import os.path - - import mock + from unittest import mock @mock.patch('os.path.exists') def test_path_exists(mock_exists): diff --git a/tests/test_parser.py b/tests/test_parser.py index 64839572..4a12c59c 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -236,7 +236,7 @@ class ParserMissingArcDescriptionTest(CoverageTest): def test_missing_arc_description(self): # This code is never run, so the actual values don't matter. - parser = self.parse_text(u"""\ + parser = self.parse_text("""\ if x: print(2) print(3) @@ -271,7 +271,7 @@ class ParserMissingArcDescriptionTest(CoverageTest): assert expected == parser.missing_arc_description(11, 13) def test_missing_arc_descriptions_for_small_callables(self): - parser = self.parse_text(u"""\ + parser = self.parse_text("""\ callables = [ lambda: 2, (x for x in range(3)), @@ -290,7 +290,7 @@ class ParserMissingArcDescriptionTest(CoverageTest): assert expected == parser.missing_arc_description(5, -5) def test_missing_arc_descriptions_for_exceptions(self): - parser = self.parse_text(u"""\ + parser = self.parse_text("""\ try: pass except ZeroDivideError: @@ -310,7 +310,7 @@ class ParserMissingArcDescriptionTest(CoverageTest): assert expected == parser.missing_arc_description(5, 6) def test_missing_arc_descriptions_for_finally(self): - parser = self.parse_text(u"""\ + parser = self.parse_text("""\ def function(): for i in range(2): try: @@ -384,7 +384,7 @@ class ParserMissingArcDescriptionTest(CoverageTest): assert expected == parser.missing_arc_description(18, -1) def test_missing_arc_descriptions_bug460(self): - parser = self.parse_text(u"""\ + parser = self.parse_text("""\ x = 1 d = { 3: lambda: [], diff --git a/tests/test_phystokens.py b/tests/test_phystokens.py index 76b545e1..06cdd385 100644 --- a/tests/test_phystokens.py +++ b/tests/test_phystokens.py @@ -18,7 +18,7 @@ from tests.coveragetest import CoverageTest, TESTS_DIR # A simple program and its token stream. -SIMPLE = u"""\ +SIMPLE = """\ # yay! def foo(): say('two = %d' % 2) @@ -33,7 +33,7 @@ SIMPLE_TOKENS = [ ] # Mixed-whitespace program, and its token stream. -MIXED_WS = u"""\ +MIXED_WS = """\ def hello(): a="Hello world!" \tb="indented" @@ -46,7 +46,7 @@ MIXED_WS_TOKENS = [ ] # https://github.com/nedbat/coveragepy/issues/822 -BUG_822 = u"""\ +BUG_822 = """\ print( "Message 1" ) array = [ 1,2,3,4, # 4 numbers \\ 5,6,7 ] # 3 numbers @@ -192,12 +192,12 @@ class NeuterEncodingDeclarationTest(CoverageTest): assert source_encoding(neutered) == DEF_ENCODING, "Wrong encoding in %r" % neutered def test_two_encoding_declarations(self): - input_src = textwrap.dedent(u"""\ + input_src = textwrap.dedent("""\ # -*- coding: ascii -*- # -*- coding: utf-8 -*- # -*- coding: utf-16 -*- """) - expected_src = textwrap.dedent(u"""\ + expected_src = textwrap.dedent("""\ # (deleted declaration) -*- # (deleted declaration) -*- # -*- coding: utf-16 -*- @@ -206,12 +206,12 @@ class NeuterEncodingDeclarationTest(CoverageTest): assert expected_src == output_src def test_one_encoding_declaration(self): - input_src = textwrap.dedent(u"""\ + input_src = textwrap.dedent("""\ # -*- coding: utf-16 -*- # Just a comment. # -*- coding: ascii -*- """) - expected_src = textwrap.dedent(u"""\ + expected_src = textwrap.dedent("""\ # (deleted declaration) -*- # Just a comment. # -*- coding: ascii -*- @@ -260,7 +260,7 @@ class CompileUnicodeTest(CoverageTest): def assert_compile_unicode(self, source): """Assert that `source` will compile properly with `compile_unicode`.""" - source += u"a = 42\n" + source += "a = 42\n" # This doesn't raise an exception: code = compile_unicode(source, "<string>", "exec") globs = {} @@ -268,11 +268,11 @@ class CompileUnicodeTest(CoverageTest): assert globs['a'] == 42 def test_cp1252(self): - uni = u"""# coding: cp1252\n# \u201C curly \u201D\n""" + uni = """# coding: cp1252\n# \u201C curly \u201D\n""" self.assert_compile_unicode(uni) def test_double_coding_declaration(self): # Build this string in a weird way so that actual vim's won't try to # interpret it... - uni = u"# -*- coding:utf-8 -*-\n# v" + "im: fileencoding=utf-8\n" + uni = "# -*- coding:utf-8 -*-\n# v" + "im: fileencoding=utf-8\n" self.assert_compile_unicode(uni) diff --git a/tests/test_plugins.py b/tests/test_plugins.py index fec92749..21aeab14 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -22,7 +22,7 @@ from tests.coveragetest import CoverageTest from tests.helpers import CheckUniqueFilenames -class FakeConfig(object): +class FakeConfig: """A fake config for use in tests.""" def __init__(self, plugin, options): @@ -644,7 +644,7 @@ class BadFileTracerTest(FileTracerTest): # Disabling plug-in '...' due to previous exception # or: # Disabling plug-in '...' due to an exception: - msg = "Disabling plug-in '%s.%s' due to " % (module_name, plugin_name) + msg = f"Disabling plug-in '{module_name}.{plugin_name}' due to " warnings = stderr.count(msg) assert warnings == 1 diff --git a/tests/test_process.py b/tests/test_process.py index a73c650f..b57a4aa4 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -162,9 +161,9 @@ class ProcessTest(CoverageTest): assert status == 1 for n in "12": - self.assert_exists(".coverage.bad{}".format(n)) + self.assert_exists(f".coverage.bad{n}") warning_regex = ( - r"Coverage.py warning: Couldn't use data file '.*\.coverage.bad{0}': " + r"Coverage.py warning: Couldn't use data file '.*\.coverage.bad{}': " r"file (is encrypted or )?is not a database" .format(n) ) @@ -490,7 +489,7 @@ class ProcessTest(CoverageTest): # But also make sure that the output is what we expect. path = python_reported_file('throw.py') - msg = 'File "{}", line 5,? in f2'.format(re.escape(path)) + msg = f'File "{re.escape(path)}", line 5,? in f2' assert re.search(msg, out) assert 'raise Exception("hey!")' in out assert status == 1 @@ -563,8 +562,8 @@ class ProcessTest(CoverageTest): # The two data files should have different random numbers at the end of # the file name. data_files = glob.glob(".coverage.*") - nums = set(name.rpartition(".")[-1] for name in data_files) - assert len(nums) == 2, "Same random: %s" % (data_files,) + nums = {name.rpartition(".")[-1] for name in data_files} + assert len(nums) == 2, f"Same random: {data_files}" # Combine the parallel coverage data files into .coverage . self.run_command("coverage combine") @@ -604,7 +603,7 @@ class ProcessTest(CoverageTest): # will fail. out = self.run_command("coverage run i_dont_exist.py") path = python_reported_file('i_dont_exist.py') - assert "No file to run: '{}'".format(path) in out + assert f"No file to run: '{path}'" in out assert "warning" not in out assert "Exception" not in out @@ -727,7 +726,7 @@ class ProcessTest(CoverageTest): msg = ( "Coverage.py warning: " - "Already imported a file that will be measured: {0} " + "Already imported a file that will be measured: {} " "(already-imported)").format(goodbye_path) assert msg in out @@ -990,7 +989,7 @@ class EnvironmentTest(CoverageTest): self.make_file("run_me.py", f.read()) expected = self.run_command("python run_me.py") cov_main = os.path.join(TESTS_DIR, "covmain.zip") - actual = self.run_command("python {} run run_me.py".format(cov_main)) + actual = self.run_command(f"python {cov_main} run run_me.py") self.assert_tryexecfile_output(expected, actual) def test_coverage_custom_script(self): @@ -1217,7 +1216,7 @@ class FailUnderTest(CoverageTest): """Tests of the --fail-under switch.""" def setup_test(self): - super(FailUnderTest, self).setup_test() + super().setup_test() self.make_file("forty_two_plus.py", """\ # I have 42.857% (3/7) coverage! a = 1 @@ -1276,14 +1275,14 @@ class UnicodeFilePathsTest(CoverageTest): def test_accented_dot_py(self): # Make a file with a non-ascii character in the filename. - self.make_file(u"h\xe2t.py", "print('accented')") - out = self.run_command(u"coverage run --source=. h\xe2t.py") + self.make_file("h\xe2t.py", "print('accented')") + out = self.run_command("coverage run --source=. h\xe2t.py") assert out == "accented\n" # The HTML report uses ascii-encoded HTML entities. out = self.run_command("coverage html") assert out == "" - self.assert_exists(u"htmlcov/h\xe2t_py.html") + self.assert_exists("htmlcov/h\xe2t_py.html") with open("htmlcov/index.html") as indexf: index = indexf.read() assert '<a href="hât_py.html">hât.py</a>' in index @@ -1293,15 +1292,15 @@ class UnicodeFilePathsTest(CoverageTest): assert out == "" with open("coverage.xml", "rb") as xmlf: xml = xmlf.read() - assert u' filename="h\xe2t.py"'.encode('utf8') in xml - assert u' name="h\xe2t.py"'.encode('utf8') in xml + assert ' filename="h\xe2t.py"'.encode() in xml + assert ' name="h\xe2t.py"'.encode() in xml report_expected = ( - u"Name Stmts Miss Cover\n" - u"----------------------------\n" - u"h\xe2t.py 1 0 100%\n" - u"----------------------------\n" - u"TOTAL 1 0 100%\n" + "Name Stmts Miss Cover\n" + "----------------------------\n" + "h\xe2t.py 1 0 100%\n" + "----------------------------\n" + "TOTAL 1 0 100%\n" ) out = self.run_command("coverage report") @@ -1309,14 +1308,14 @@ class UnicodeFilePathsTest(CoverageTest): def test_accented_directory(self): # Make a file with a non-ascii character in the directory name. - self.make_file(u"\xe2/accented.py", "print('accented')") - out = self.run_command(u"coverage run --source=. \xe2/accented.py") + self.make_file("\xe2/accented.py", "print('accented')") + out = self.run_command("coverage run --source=. \xe2/accented.py") assert out == "accented\n" # The HTML report uses ascii-encoded HTML entities. out = self.run_command("coverage html") assert out == "" - self.assert_exists(u"htmlcov/\xe2_accented_py.html") + self.assert_exists("htmlcov/\xe2_accented_py.html") with open("htmlcov/index.html") as indexf: index = indexf.read() assert '<a href="â_accented_py.html">â%saccented.py</a>' % os.sep in index @@ -1330,21 +1329,21 @@ class UnicodeFilePathsTest(CoverageTest): assert b' name="accented.py"' in xml dom = ElementTree.parse("coverage.xml") - elts = dom.findall(u".//package[@name='â']") + elts = dom.findall(".//package[@name='â']") assert len(elts) == 1 assert elts[0].attrib == { - "branch-rate": u"0", - "complexity": u"0", - "line-rate": u"1", - "name": u"â", + "branch-rate": "0", + "complexity": "0", + "line-rate": "1", + "name": "â", } report_expected = ( - u"Name Stmts Miss Cover\n" - u"-----------------------------------\n" - u"\xe2%saccented.py 1 0 100%%\n" - u"-----------------------------------\n" - u"TOTAL 1 0 100%%\n" + "Name Stmts Miss Cover\n" + "-----------------------------------\n" + "\xe2%saccented.py 1 0 100%%\n" + "-----------------------------------\n" + "TOTAL 1 0 100%%\n" ) % os.sep out = self.run_command("coverage report") @@ -1400,11 +1399,11 @@ def possible_pth_dirs(): def find_writable_pth_directory(): """Find a place to write a .pth file.""" for pth_dir in possible_pth_dirs(): # pragma: part covered - try_it = os.path.join(pth_dir, "touch_{}.it".format(WORKER)) + try_it = os.path.join(pth_dir, f"touch_{WORKER}.it") with open(try_it, "w") as f: try: f.write("foo") - except (IOError, OSError): # pragma: cant happen + except OSError: # pragma: cant happen continue os.remove(try_it) @@ -1427,19 +1426,19 @@ def persistent_remove(path): time.sleep(.05) else: return - raise Exception("Sorry, couldn't remove {!r}".format(path)) # pragma: cant happen + raise Exception(f"Sorry, couldn't remove {path!r}") # pragma: cant happen -class ProcessCoverageMixin(object): +class ProcessCoverageMixin: """Set up a .pth file to coverage-measure all sub-processes.""" def setup_test(self): - super(ProcessCoverageMixin, self).setup_test() + super().setup_test() # Create the .pth file. assert PTH_DIR pth_contents = "import coverage; coverage.process_startup()\n" - pth_path = os.path.join(PTH_DIR, "subcover_{}.pth".format(WORKER)) + pth_path = os.path.join(PTH_DIR, f"subcover_{WORKER}.pth") with open(pth_path, "w") as pth: pth.write(pth_contents) @@ -1451,7 +1450,7 @@ class ProcessStartupTest(ProcessCoverageMixin, CoverageTest): """Test that we can measure coverage in sub-processes.""" def setup_test(self): - super(ProcessStartupTest, self).setup_test() + super().setup_test() # Main will run sub.py self.make_file("main.py", """\ @@ -1688,7 +1687,7 @@ def venv_world_fixture(tmp_path_factory): # Install coverage. coverage_src = nice_file(TESTS_DIR, "..") - run_in_venv("python -m pip install --no-index {}".format(coverage_src)) + run_in_venv(f"python -m pip install --no-index {coverage_src}") return venv_world diff --git a/tests/test_setup.py b/tests/test_setup.py index b2ccd67c..0d64319c 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -16,7 +16,7 @@ class SetupPyTest(CoverageTest): run_in_temp_dir = False def setup_test(self): - super(SetupPyTest, self).setup_test() + super().setup_test() # Force the most restrictive interpretation. self.set_environ('LC_ALL', 'C') diff --git a/tests/test_summary.py b/tests/test_summary.py index b00ee96b..a326fc85 100644 --- a/tests/test_summary.py +++ b/tests/test_summary.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -105,8 +104,8 @@ class SummaryTest(UsingModulesMixin, CoverageTest): # Try reporting while omitting some modules self.make_mycode() self.run_command("coverage run mycode.py") - omit = '{}/*,*/site-packages/*'.format(TESTS_DIR) - report = self.report_from_command("coverage report --omit '{}'".format(omit)) + omit = f'{TESTS_DIR}/*,*/site-packages/*' + report = self.report_from_command(f"coverage report --omit '{omit}'") # Name Stmts Miss Cover # ------------------------------- @@ -569,10 +568,10 @@ class SummaryTest(UsingModulesMixin, CoverageTest): # We run a .py file with a non-ascii name, and when reporting, we can't # parse it as Python. We should get an error message in the report. - self.make_file(u"accented\xe2.py", "print('accented')") - self.run_command(u"coverage run accented\xe2.py") - self.make_file(u"accented\xe2.py", "This isn't python at all!") - report = self.report_from_command(u"coverage report accented\xe2.py") + self.make_file("accented\xe2.py", "print('accented')") + self.run_command("coverage run accented\xe2.py") + self.make_file("accented\xe2.py", "This isn't python at all!") + report = self.report_from_command("coverage report accented\xe2.py") # Couldn't parse '...' as Python source: 'invalid syntax' at line 1 # Name Stmts Miss Cover @@ -584,7 +583,7 @@ class SummaryTest(UsingModulesMixin, CoverageTest): errmsg = re.sub(r"parse '.*(accented.*?\.py)", r"parse '\1", errmsg) # The actual error message varies version to version errmsg = re.sub(r": '.*' at", ": 'error' at", errmsg) - expected = u"Couldn't parse 'accented\xe2.py' as Python source: 'error' at line 1" + expected = "Couldn't parse 'accented\xe2.py' as Python source: 'error' at line 1" assert expected == errmsg def test_dotpy_not_python_ignored(self): @@ -903,7 +902,7 @@ class SummaryReporterConfigurationTest(CoverageTest): """Assert that the `words` appear in order in `text`.""" indexes = list(map(text.find, words)) assert -1 not in indexes - msg = "The words %r don't appear in order in %r" % (words, text) + msg = f"The words {words!r} don't appear in order in {text!r}" assert indexes == sorted(indexes), msg def test_sort_report_by_stmts(self): diff --git a/tests/test_templite.py b/tests/test_templite.py index 770e97f9..e4d83647 100644 --- a/tests/test_templite.py +++ b/tests/test_templite.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -14,7 +13,7 @@ from tests.coveragetest import CoverageTest # pylint: disable=possibly-unused-variable -class AnyOldObject(object): +class AnyOldObject: """Simple testing object. Use keyword arguments in the constructor to set attributes on the object. @@ -289,9 +288,9 @@ class TempliteTest(CoverageTest): def test_non_ascii(self): self.try_render( - u"{{where}} ollǝɥ", - { 'where': u'ǝɹǝɥʇ' }, - u"ǝɹǝɥʇ ollǝɥ" + "{{where}} ollǝɥ", + { 'where': 'ǝɹǝɥʇ' }, + "ǝɹǝɥʇ ollǝɥ" ) def test_exception_during_evaluation(self): diff --git a/tests/test_testing.py b/tests/test_testing.py index 558c846e..3a563efe 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -209,7 +208,7 @@ class CheckUniqueFilenamesTest(CoverageTest): run_in_temp_dir = False - class Stub(object): + class Stub: """A stand-in for the class we're checking.""" def __init__(self, x): self.x = x diff --git a/tests/test_xml.py b/tests/test_xml.py index 334abb4c..9c6cfb58 100644 --- a/tests/test_xml.py +++ b/tests/test_xml.py @@ -1,4 +1,3 @@ -# coding: utf-8 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt @@ -54,13 +53,13 @@ class XmlTestHelpers(CoverageTest): return os.path.join(curdir, p) for i in range(width): - next_dir = here("d{}".format(i)) + next_dir = here(f"d{i}") self.make_tree(width, depth-1, next_dir) if curdir != ".": self.make_file(here("__init__.py"), "") for i in range(width): - filename = here("f{}.py".format(i)) - self.make_file(filename, "# {}\n".format(filename)) + filename = here(f"f{i}.py") + self.make_file(filename, f"# {filename}\n") def assert_source(self, xmldom, src): """Assert that the XML has a <source> element with `src`.""" |