Fix encoding warnings

This commit is contained in:
nondescryptid 2023-06-20 04:55:39 -07:00 committed by Zac Hatfield-Dodds
parent faa1f9d2ad
commit a704605cf1
11 changed files with 218 additions and 112 deletions

View File

@ -267,7 +267,7 @@ class TestGeneralUsage:
def test_issue109_sibling_conftests_not_loaded(self, pytester: Pytester) -> None: def test_issue109_sibling_conftests_not_loaded(self, pytester: Pytester) -> None:
sub1 = pytester.mkdir("sub1") sub1 = pytester.mkdir("sub1")
sub2 = pytester.mkdir("sub2") sub2 = pytester.mkdir("sub2")
sub1.joinpath("conftest.py").write_text("assert 0") sub1.joinpath("conftest.py").write_text("assert 0", encoding="utf-8")
result = pytester.runpytest(sub2) result = pytester.runpytest(sub2)
assert result.ret == ExitCode.NO_TESTS_COLLECTED assert result.ret == ExitCode.NO_TESTS_COLLECTED
sub2.joinpath("__init__.py").touch() sub2.joinpath("__init__.py").touch()
@ -467,7 +467,7 @@ class TestGeneralUsage:
assert "invalid" in str(excinfo.value) assert "invalid" in str(excinfo.value)
p = pytester.path.joinpath("test_test_plugins_given_as_strings.py") p = pytester.path.joinpath("test_test_plugins_given_as_strings.py")
p.write_text("def test_foo(): pass") p.write_text("def test_foo(): pass", encoding="utf-8")
mod = types.ModuleType("myplugin") mod = types.ModuleType("myplugin")
monkeypatch.setitem(sys.modules, "myplugin", mod) monkeypatch.setitem(sys.modules, "myplugin", mod)
assert pytest.main(args=[str(pytester.path)], plugins=["myplugin"]) == 0 assert pytest.main(args=[str(pytester.path)], plugins=["myplugin"]) == 0
@ -587,7 +587,7 @@ class TestInvocationVariants:
def test_pyargs_importerror(self, pytester: Pytester, monkeypatch) -> None: def test_pyargs_importerror(self, pytester: Pytester, monkeypatch) -> None:
monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", False) monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", False)
path = pytester.mkpydir("tpkg") path = pytester.mkpydir("tpkg")
path.joinpath("test_hello.py").write_text("raise ImportError") path.joinpath("test_hello.py").write_text("raise ImportError", encoding="utf-8")
result = pytester.runpytest("--pyargs", "tpkg.test_hello", syspathinsert=True) result = pytester.runpytest("--pyargs", "tpkg.test_hello", syspathinsert=True)
assert result.ret != 0 assert result.ret != 0
@ -597,10 +597,10 @@ class TestInvocationVariants:
def test_pyargs_only_imported_once(self, pytester: Pytester) -> None: def test_pyargs_only_imported_once(self, pytester: Pytester) -> None:
pkg = pytester.mkpydir("foo") pkg = pytester.mkpydir("foo")
pkg.joinpath("test_foo.py").write_text( pkg.joinpath("test_foo.py").write_text(
"print('hello from test_foo')\ndef test(): pass" "print('hello from test_foo')\ndef test(): pass", encoding="utf-8"
) )
pkg.joinpath("conftest.py").write_text( pkg.joinpath("conftest.py").write_text(
"def pytest_configure(config): print('configuring')" "def pytest_configure(config): print('configuring')", encoding="utf-8"
) )
result = pytester.runpytest( result = pytester.runpytest(

View File

@ -287,7 +287,8 @@ class TestFillFixtures:
def spam(): def spam():
return 'spam' return 'spam'
""" """
) ),
encoding="utf-8",
) )
testfile = subdir.joinpath("test_spam.py") testfile = subdir.joinpath("test_spam.py")
testfile.write_text( testfile.write_text(
@ -296,7 +297,8 @@ class TestFillFixtures:
def test_spam(spam): def test_spam(spam):
assert spam == "spam" assert spam == "spam"
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"]) result.stdout.fnmatch_lines(["*1 passed*"])
@ -359,7 +361,8 @@ class TestFillFixtures:
def spam(request): def spam(request):
return request.param return request.param
""" """
) ),
encoding="utf-8",
) )
testfile = subdir.joinpath("test_spam.py") testfile = subdir.joinpath("test_spam.py")
testfile.write_text( testfile.write_text(
@ -371,7 +374,8 @@ class TestFillFixtures:
assert spam == params['spam'] assert spam == params['spam']
params['spam'] += 1 params['spam'] += 1
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines(["*3 passed*"]) result.stdout.fnmatch_lines(["*3 passed*"])
@ -403,7 +407,8 @@ class TestFillFixtures:
def spam(request): def spam(request):
return request.param return request.param
""" """
) ),
encoding="utf-8",
) )
testfile = subdir.joinpath("test_spam.py") testfile = subdir.joinpath("test_spam.py")
testfile.write_text( testfile.write_text(
@ -415,7 +420,8 @@ class TestFillFixtures:
assert spam == params['spam'] assert spam == params['spam']
params['spam'] += 1 params['spam'] += 1
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines(["*3 passed*"]) result.stdout.fnmatch_lines(["*3 passed*"])
@ -1037,10 +1043,11 @@ class TestRequestBasic:
def arg1(): def arg1():
pass pass
""" """
) ),
encoding="utf-8",
) )
p = b.joinpath("test_module.py") p = b.joinpath("test_module.py")
p.write_text("def test_func(arg1): pass") p.write_text("def test_func(arg1): pass", encoding="utf-8")
result = pytester.runpytest(p, "--fixtures") result = pytester.runpytest(p, "--fixtures")
assert result.ret == 0 assert result.ret == 0
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
@ -1617,7 +1624,8 @@ class TestFixtureManagerParseFactories:
def one(): def one():
return 1 return 1
""" """
) ),
encoding="utf-8",
) )
package.joinpath("test_x.py").write_text( package.joinpath("test_x.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -1625,7 +1633,8 @@ class TestFixtureManagerParseFactories:
def test_x(one): def test_x(one):
assert one == 1 assert one == 1
""" """
) ),
encoding="utf-8",
) )
sub = package.joinpath("sub") sub = package.joinpath("sub")
sub.mkdir() sub.mkdir()
@ -1638,7 +1647,8 @@ class TestFixtureManagerParseFactories:
def one(): def one():
return 2 return 2
""" """
) ),
encoding="utf-8",
) )
sub.joinpath("test_y.py").write_text( sub.joinpath("test_y.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -1646,7 +1656,8 @@ class TestFixtureManagerParseFactories:
def test_x(one): def test_x(one):
assert one == 2 assert one == 2
""" """
) ),
encoding="utf-8",
) )
reprec = pytester.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=2) reprec.assertoutcome(passed=2)
@ -1671,7 +1682,8 @@ class TestFixtureManagerParseFactories:
def teardown_module(): def teardown_module():
values[:] = [] values[:] = []
""" """
) ),
encoding="utf-8",
) )
package.joinpath("test_x.py").write_text( package.joinpath("test_x.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -1680,7 +1692,8 @@ class TestFixtureManagerParseFactories:
def test_x(): def test_x():
assert values == ["package"] assert values == ["package"]
""" """
) ),
encoding="utf-8",
) )
package = pytester.mkdir("package2") package = pytester.mkdir("package2")
package.joinpath("__init__.py").write_text( package.joinpath("__init__.py").write_text(
@ -1692,7 +1705,8 @@ class TestFixtureManagerParseFactories:
def teardown_module(): def teardown_module():
values[:] = [] values[:] = []
""" """
) ),
encoding="utf-8",
) )
package.joinpath("test_x.py").write_text( package.joinpath("test_x.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -1701,7 +1715,8 @@ class TestFixtureManagerParseFactories:
def test_x(): def test_x():
assert values == ["package2"] assert values == ["package2"]
""" """
) ),
encoding="utf-8",
) )
reprec = pytester.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=2) reprec.assertoutcome(passed=2)
@ -1714,7 +1729,7 @@ class TestFixtureManagerParseFactories:
) )
pytester.syspathinsert(pytester.path.name) pytester.syspathinsert(pytester.path.name)
package = pytester.mkdir("package") package = pytester.mkdir("package")
package.joinpath("__init__.py").write_text("") package.joinpath("__init__.py").write_text("", encoding="utf-8")
package.joinpath("conftest.py").write_text( package.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
@ -1731,7 +1746,8 @@ class TestFixtureManagerParseFactories:
yield values yield values
values.pop() values.pop()
""" """
) ),
encoding="utf-8",
) )
package.joinpath("test_x.py").write_text( package.joinpath("test_x.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -1742,7 +1758,8 @@ class TestFixtureManagerParseFactories:
def test_package(one): def test_package(one):
assert values == ["package-auto", "package"] assert values == ["package-auto", "package"]
""" """
) ),
encoding="utf-8",
) )
reprec = pytester.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=2) reprec.assertoutcome(passed=2)
@ -1892,8 +1909,12 @@ class TestAutouseDiscovery:
""" """
) )
conftest.rename(a.joinpath(conftest.name)) conftest.rename(a.joinpath(conftest.name))
a.joinpath("test_something.py").write_text("def test_func(): pass") a.joinpath("test_something.py").write_text(
b.joinpath("test_otherthing.py").write_text("def test_func(): pass") "def test_func(): pass", encoding="utf-8"
)
b.joinpath("test_otherthing.py").write_text(
"def test_func(): pass", encoding="utf-8"
)
result = pytester.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
""" """
@ -1939,7 +1960,8 @@ class TestAutouseManagement:
import sys import sys
sys._myapp = "hello" sys._myapp = "hello"
""" """
) ),
encoding="utf-8",
) )
sub = pkgdir.joinpath("tests") sub = pkgdir.joinpath("tests")
sub.mkdir() sub.mkdir()
@ -1952,7 +1974,8 @@ class TestAutouseManagement:
def test_app(): def test_app():
assert sys._myapp == "hello" assert sys._myapp == "hello"
""" """
) ),
encoding="utf-8",
) )
reprec = pytester.inline_run("-s") reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
@ -2882,7 +2905,7 @@ class TestFixtureMarker:
def browser(request): def browser(request):
def finalize(): def finalize():
sys.stdout.write_text('Finalized') sys.stdout.write_text('Finalized', encoding='utf-8')
request.addfinalizer(finalize) request.addfinalizer(finalize)
return {} return {}
""" """
@ -2900,7 +2923,8 @@ class TestFixtureMarker:
def test_browser(browser): def test_browser(browser):
assert browser['visited'] is True assert browser['visited'] is True
""" """
) ),
encoding="utf-8",
) )
reprec = pytester.runpytest("-s") reprec = pytester.runpytest("-s")
for test in ["test_browser"]: for test in ["test_browser"]:
@ -3855,7 +3879,8 @@ class TestParameterizedSubRequest:
def fix_with_param(request): def fix_with_param(request):
return request.param return request.param
""" """
) ),
encoding="utf-8",
) )
testfile = tests_dir.joinpath("test_foos.py") testfile = tests_dir.joinpath("test_foos.py")
@ -3867,7 +3892,8 @@ class TestParameterizedSubRequest:
def test_foo(request): def test_foo(request):
request.getfixturevalue('fix_with_param') request.getfixturevalue('fix_with_param')
""" """
) ),
encoding="utf-8",
) )
os.chdir(tests_dir) os.chdir(tests_dir)
@ -4196,7 +4222,7 @@ class TestScopeOrdering:
test_2.py test_2.py
""" """
root = pytester.mkdir("root") root = pytester.mkdir("root")
root.joinpath("__init__.py").write_text("values = []") root.joinpath("__init__.py").write_text("values = []", encoding="utf-8")
sub1 = root.joinpath("sub1") sub1 = root.joinpath("sub1")
sub1.mkdir() sub1.mkdir()
sub1.joinpath("__init__.py").touch() sub1.joinpath("__init__.py").touch()
@ -4211,7 +4237,8 @@ class TestScopeOrdering:
yield values yield values
assert values.pop() == "pre-sub1" assert values.pop() == "pre-sub1"
""" """
) ),
encoding="utf-8",
) )
sub1.joinpath("test_1.py").write_text( sub1.joinpath("test_1.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -4220,7 +4247,8 @@ class TestScopeOrdering:
def test_1(fix): def test_1(fix):
assert values == ["pre-sub1"] assert values == ["pre-sub1"]
""" """
) ),
encoding="utf-8",
) )
sub2 = root.joinpath("sub2") sub2 = root.joinpath("sub2")
sub2.mkdir() sub2.mkdir()
@ -4236,7 +4264,8 @@ class TestScopeOrdering:
yield values yield values
assert values.pop() == "pre-sub2" assert values.pop() == "pre-sub2"
""" """
) ),
encoding="utf-8",
) )
sub2.joinpath("test_2.py").write_text( sub2.joinpath("test_2.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -4245,7 +4274,8 @@ class TestScopeOrdering:
def test_2(fix): def test_2(fix):
assert values == ["pre-sub2"] assert values == ["pre-sub2"]
""" """
) ),
encoding="utf-8",
) )
reprec = pytester.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=2) reprec.assertoutcome(passed=2)

View File

@ -1443,7 +1443,8 @@ class TestMetafuncFunctional:
def pytest_generate_tests(metafunc): def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_1" assert metafunc.function.__name__ == "test_1"
""" """
) ),
encoding="utf-8",
) )
sub2.joinpath("conftest.py").write_text( sub2.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -1451,10 +1452,15 @@ class TestMetafuncFunctional:
def pytest_generate_tests(metafunc): def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_2" assert metafunc.function.__name__ == "test_2"
""" """
) ),
encoding="utf-8",
)
sub1.joinpath("test_in_sub1.py").write_text(
"def test_1(): pass", encoding="utf-8"
)
sub2.joinpath("test_in_sub2.py").write_text(
"def test_2(): pass", encoding="utf-8"
) )
sub1.joinpath("test_in_sub1.py").write_text("def test_1(): pass")
sub2.joinpath("test_in_sub2.py").write_text("def test_2(): pass")
result = pytester.runpytest("--keep-duplicates", "-v", "-s", sub1, sub2, sub1) result = pytester.runpytest("--keep-duplicates", "-v", "-s", sub1, sub2, sub1)
result.assert_outcomes(passed=3) result.assert_outcomes(passed=3)

View File

@ -160,7 +160,8 @@ class TestAssertionRewrite:
"def special_asserter():\n" "def special_asserter():\n"
" def special_assert(x, y):\n" " def special_assert(x, y):\n"
" assert x == y\n" " assert x == y\n"
" return special_assert\n" " return special_assert\n",
encoding="utf-8",
) )
pytester.makeconftest('pytest_plugins = ["plugin"]') pytester.makeconftest('pytest_plugins = ["plugin"]')
pytester.makepyfile("def test(special_asserter): special_asserter(1, 2)\n") pytester.makepyfile("def test(special_asserter): special_asserter(1, 2)\n")
@ -173,7 +174,9 @@ class TestAssertionRewrite:
pytester.makepyfile(test_y="x = 1") pytester.makepyfile(test_y="x = 1")
xdir = pytester.mkdir("x") xdir = pytester.mkdir("x")
pytester.mkpydir(str(xdir.joinpath("test_Y"))) pytester.mkpydir(str(xdir.joinpath("test_Y")))
xdir.joinpath("test_Y").joinpath("__init__.py").write_text("x = 2") xdir.joinpath("test_Y").joinpath("__init__.py").write_text(
"x = 2", encoding="utf-8"
)
pytester.makepyfile( pytester.makepyfile(
"import test_y\n" "import test_y\n"
"import test_Y\n" "import test_Y\n"
@ -726,7 +729,7 @@ class TestAssertionRewrite:
class TestRewriteOnImport: class TestRewriteOnImport:
def test_pycache_is_a_file(self, pytester: Pytester) -> None: def test_pycache_is_a_file(self, pytester: Pytester) -> None:
pytester.path.joinpath("__pycache__").write_text("Hello") pytester.path.joinpath("__pycache__").write_text("Hello", encoding="utf-8")
pytester.makepyfile( pytester.makepyfile(
""" """
def test_rewritten(): def test_rewritten():
@ -903,7 +906,8 @@ def test_rewritten():
pkg.joinpath("test_blah.py").write_text( pkg.joinpath("test_blah.py").write_text(
""" """
def test_rewritten(): def test_rewritten():
assert "@py_builtins" in globals()""" assert "@py_builtins" in globals()""",
encoding="utf-8",
) )
assert pytester.runpytest().ret == 0 assert pytester.runpytest().ret == 0
@ -1066,7 +1070,7 @@ class TestAssertionRewriteHookDetails:
source = tmp_path / "source.py" source = tmp_path / "source.py"
pyc = Path(str(source) + "c") pyc = Path(str(source) + "c")
source.write_text("def test(): pass") source.write_text("def test(): pass", encoding="utf-8")
py_compile.compile(str(source), str(pyc)) py_compile.compile(str(source), str(pyc))
contents = pyc.read_bytes() contents = pyc.read_bytes()
@ -1092,7 +1096,7 @@ class TestAssertionRewriteHookDetails:
fn = tmp_path / "source.py" fn = tmp_path / "source.py"
pyc = Path(str(fn) + "c") pyc = Path(str(fn) + "c")
fn.write_text("def test(): assert True") fn.write_text("def test(): assert True", encoding="utf-8")
source_stat, co = _rewrite_test(fn, config) source_stat, co = _rewrite_test(fn, config)
_write_pyc(state, co, source_stat, pyc) _write_pyc(state, co, source_stat, pyc)
@ -1187,9 +1191,10 @@ class TestAssertionRewriteHookDetails:
data = pkgutil.get_data('foo.test_foo', 'data.txt') data = pkgutil.get_data('foo.test_foo', 'data.txt')
assert data == b'Hey' assert data == b'Hey'
""" """
) ),
encoding="utf-8",
) )
path.joinpath("data.txt").write_text("Hey") path.joinpath("data.txt").write_text("Hey", encoding="utf-8")
result = pytester.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"]) result.stdout.fnmatch_lines(["*1 passed*"])

View File

@ -140,7 +140,7 @@ class TestCollectFS:
ensure_file(tmp_path / ".bzr" / "test_notfound.py") ensure_file(tmp_path / ".bzr" / "test_notfound.py")
ensure_file(tmp_path / "normal" / "test_found.py") ensure_file(tmp_path / "normal" / "test_found.py")
for x in tmp_path.rglob("test_*.py"): for x in tmp_path.rglob("test_*.py"):
x.write_text("def test_hello(): pass", "utf-8") x.write_text("def test_hello(): pass", encoding="utf-8")
result = pytester.runpytest("--collect-only") result = pytester.runpytest("--collect-only")
s = result.stdout.str() s = result.stdout.str()
@ -162,7 +162,7 @@ class TestCollectFS:
bindir = "Scripts" if sys.platform.startswith("win") else "bin" bindir = "Scripts" if sys.platform.startswith("win") else "bin"
ensure_file(pytester.path / "virtual" / bindir / fname) ensure_file(pytester.path / "virtual" / bindir / fname)
testfile = ensure_file(pytester.path / "virtual" / "test_invenv.py") testfile = ensure_file(pytester.path / "virtual" / "test_invenv.py")
testfile.write_text("def test_hello(): pass") testfile.write_text("def test_hello(): pass", encoding="utf-8")
# by default, ignore tests inside a virtualenv # by default, ignore tests inside a virtualenv
result = pytester.runpytest() result = pytester.runpytest()
@ -192,7 +192,7 @@ class TestCollectFS:
# norecursedirs takes priority # norecursedirs takes priority
ensure_file(pytester.path / ".virtual" / bindir / fname) ensure_file(pytester.path / ".virtual" / bindir / fname)
testfile = ensure_file(pytester.path / ".virtual" / "test_invenv.py") testfile = ensure_file(pytester.path / ".virtual" / "test_invenv.py")
testfile.write_text("def test_hello(): pass") testfile.write_text("def test_hello(): pass", encoding="utf-8")
result = pytester.runpytest("--collect-in-virtualenv") result = pytester.runpytest("--collect-in-virtualenv")
result.stdout.no_fnmatch_line("*test_invenv*") result.stdout.no_fnmatch_line("*test_invenv*")
# ...unless the virtualenv is explicitly given on the CLI # ...unless the virtualenv is explicitly given on the CLI
@ -231,10 +231,14 @@ class TestCollectFS:
) )
tmp_path = pytester.path tmp_path = pytester.path
ensure_file(tmp_path / "mydir" / "test_hello.py").write_text( ensure_file(tmp_path / "mydir" / "test_hello.py").write_text(
"def test_1(): pass" "def test_1(): pass", encoding="utf-8"
)
ensure_file(tmp_path / "xyz123" / "test_2.py").write_text(
"def test_2(): 0/0", encoding="utf-8"
)
ensure_file(tmp_path / "xy" / "test_ok.py").write_text(
"def test_3(): pass", encoding="utf-8"
) )
ensure_file(tmp_path / "xyz123" / "test_2.py").write_text("def test_2(): 0/0")
ensure_file(tmp_path / "xy" / "test_ok.py").write_text("def test_3(): pass")
rec = pytester.inline_run() rec = pytester.inline_run()
rec.assertoutcome(passed=1) rec.assertoutcome(passed=1)
rec = pytester.inline_run("xyz123/test_2.py") rec = pytester.inline_run("xyz123/test_2.py")
@ -248,12 +252,14 @@ class TestCollectFS:
""" """
) )
tmp_path = pytester.path tmp_path = pytester.path
ensure_file(tmp_path / "a" / "test_1.py").write_text("def test_a(): pass") ensure_file(tmp_path / "a" / "test_1.py").write_text(
"def test_a(): pass", encoding="utf-8"
)
ensure_file(tmp_path / "b" / "tests" / "test_2.py").write_text( ensure_file(tmp_path / "b" / "tests" / "test_2.py").write_text(
"def test_b(): pass" "def test_b(): pass", encoding="utf-8"
) )
ensure_file(tmp_path / "c" / "tests" / "test_3.py").write_text( ensure_file(tmp_path / "c" / "tests" / "test_3.py").write_text(
"def test_c(): pass" "def test_c(): pass", encoding="utf-8"
) )
# executing from rootdir only tests from `testpaths` directories # executing from rootdir only tests from `testpaths` directories
@ -349,8 +355,8 @@ class TestCustomConftests:
""" """
) )
sub = pytester.mkdir("xy123") sub = pytester.mkdir("xy123")
ensure_file(sub / "test_hello.py").write_text("syntax error") ensure_file(sub / "test_hello.py").write_text("syntax error", encoding="utf-8")
sub.joinpath("conftest.py").write_text("syntax error") sub.joinpath("conftest.py").write_text("syntax error", encoding="utf-8")
pytester.makepyfile("def test_hello(): pass") pytester.makepyfile("def test_hello(): pass")
pytester.makepyfile(test_one="syntax error") pytester.makepyfile(test_one="syntax error")
result = pytester.runpytest("--fulltrace") result = pytester.runpytest("--fulltrace")
@ -1060,13 +1066,18 @@ def test_fixture_scope_sibling_conftests(pytester: Pytester) -> None:
def fix(): def fix():
return 1 return 1
""" """
) ),
encoding="utf-8",
)
foo_path.joinpath("test_foo.py").write_text(
"def test_foo(fix): assert fix == 1", encoding="utf-8"
) )
foo_path.joinpath("test_foo.py").write_text("def test_foo(fix): assert fix == 1")
# Tests in `food/` should not see the conftest fixture from `foo/` # Tests in `food/` should not see the conftest fixture from `foo/`
food_path = pytester.mkpydir("food") food_path = pytester.mkpydir("food")
food_path.joinpath("test_food.py").write_text("def test_food(fix): assert fix == 1") food_path.joinpath("test_food.py").write_text(
"def test_food(fix): assert fix == 1", encoding="utf-8"
)
res = pytester.runpytest() res = pytester.runpytest()
assert res.ret == 1 assert res.ret == 1
@ -1197,7 +1208,8 @@ def test_collect_with_chdir_during_import(pytester: Pytester) -> None:
os.chdir(%r) os.chdir(%r)
""" """
% (str(subdir),) % (str(subdir),)
) ),
encoding="utf-8",
) )
pytester.makepyfile( pytester.makepyfile(
""" """
@ -1227,8 +1239,12 @@ def test_collect_pyargs_with_testpaths(
) -> None: ) -> None:
testmod = pytester.mkdir("testmod") testmod = pytester.mkdir("testmod")
# NOTE: __init__.py is not collected since it does not match python_files. # NOTE: __init__.py is not collected since it does not match python_files.
testmod.joinpath("__init__.py").write_text("def test_func(): pass") testmod.joinpath("__init__.py").write_text(
testmod.joinpath("test_file.py").write_text("def test_func(): pass") "def test_func(): pass", encoding="utf-8"
)
testmod.joinpath("test_file.py").write_text(
"def test_func(): pass", encoding="utf-8"
)
root = pytester.mkdir("root") root = pytester.mkdir("root")
root.joinpath("pytest.ini").write_text( root.joinpath("pytest.ini").write_text(
@ -1238,7 +1254,8 @@ def test_collect_pyargs_with_testpaths(
addopts = --pyargs addopts = --pyargs
testpaths = testmod testpaths = testmod
""" """
) ),
encoding="utf-8",
) )
monkeypatch.setenv("PYTHONPATH", str(pytester.path), prepend=os.pathsep) monkeypatch.setenv("PYTHONPATH", str(pytester.path), prepend=os.pathsep)
with monkeypatch.context() as mp: with monkeypatch.context() as mp:
@ -1323,6 +1340,7 @@ def test_collect_symlink_out_of_tree(pytester: Pytester) -> None:
assert request.node.nodeid == "test_real.py::test_nodeid" assert request.node.nodeid == "test_real.py::test_nodeid"
""" """
), ),
encoding="utf-8",
) )
out_of_tree = pytester.mkdir("out_of_tree") out_of_tree = pytester.mkdir("out_of_tree")

View File

@ -87,7 +87,8 @@ class TestParseIni:
[pytest] [pytest]
addopts = --verbose addopts = --verbose
""" """
) ),
encoding="utf-8",
) )
config = pytester.parseconfig(tmp_path) config = pytester.parseconfig(tmp_path)
assert config.option.color == "no" assert config.option.color == "no"
@ -127,7 +128,8 @@ class TestParseIni:
""".format( """.format(
section=section section=section
) )
) ),
encoding="utf-8",
) )
config = pytester.parseconfig() config = pytester.parseconfig()
assert config.getini("minversion") == "3.36" assert config.getini("minversion") == "3.36"
@ -150,7 +152,8 @@ class TestParseIni:
[pytest] [pytest]
minversion = 2.0 minversion = 2.0
""" """
) ),
encoding="utf-8",
) )
pytester.path.joinpath("pytest.ini").write_text( pytester.path.joinpath("pytest.ini").write_text(
textwrap.dedent( textwrap.dedent(
@ -158,13 +161,16 @@ class TestParseIni:
[pytest] [pytest]
minversion = 1.5 minversion = 1.5
""" """
) ),
encoding="utf-8",
) )
config = pytester.parseconfigure(sub) config = pytester.parseconfigure(sub)
assert config.getini("minversion") == "2.0" assert config.getini("minversion") == "2.0"
def test_ini_parse_error(self, pytester: Pytester) -> None: def test_ini_parse_error(self, pytester: Pytester) -> None:
pytester.path.joinpath("pytest.ini").write_text("addopts = -x") pytester.path.joinpath("pytest.ini").write_text(
"addopts = -x", encoding="utf-8"
)
result = pytester.runpytest() result = pytester.runpytest()
assert result.ret != 0 assert result.ret != 0
result.stderr.fnmatch_lines("ERROR: *pytest.ini:1: no section header defined") result.stderr.fnmatch_lines("ERROR: *pytest.ini:1: no section header defined")
@ -634,7 +640,7 @@ class TestConfigAPI:
def test_getconftest_pathlist(self, pytester: Pytester, tmp_path: Path) -> None: def test_getconftest_pathlist(self, pytester: Pytester, tmp_path: Path) -> None:
somepath = tmp_path.joinpath("x", "y", "z") somepath = tmp_path.joinpath("x", "y", "z")
p = tmp_path.joinpath("conftest.py") p = tmp_path.joinpath("conftest.py")
p.write_text(f"mylist = {['.', str(somepath)]}") p.write_text(f"mylist = {['.', str(somepath)]}", encoding="utf-8")
config = pytester.parseconfigure(p) config = pytester.parseconfigure(p)
assert ( assert (
config._getconftest_pathlist("notexist", path=tmp_path, rootpath=tmp_path) config._getconftest_pathlist("notexist", path=tmp_path, rootpath=tmp_path)
@ -910,7 +916,8 @@ class TestConfigFromdictargs:
[pytest] [pytest]
name = value name = value
""" """
) ),
encoding="utf-8",
) )
inifilename = "../../foo/bar.ini" inifilename = "../../foo/bar.ini"
@ -927,7 +934,8 @@ class TestConfigFromdictargs:
name = wrong-value name = wrong-value
should_not_be_set = true should_not_be_set = true
""" """
) ),
encoding="utf-8",
) )
with MonkeyPatch.context() as mp: with MonkeyPatch.context() as mp:
mp.chdir(cwd) mp.chdir(cwd)
@ -1387,7 +1395,7 @@ class TestRootdir:
) )
def test_with_ini(self, tmp_path: Path, name: str, contents: str) -> None: def test_with_ini(self, tmp_path: Path, name: str, contents: str) -> None:
inipath = tmp_path / name inipath = tmp_path / name
inipath.write_text(contents, "utf-8") inipath.write_text(contents, encoding="utf-8")
a = tmp_path / "a" a = tmp_path / "a"
a.mkdir() a.mkdir()
@ -1446,7 +1454,7 @@ class TestRootdir:
) -> None: ) -> None:
p = tmp_path / name p = tmp_path / name
p.touch() p.touch()
p.write_text(contents, "utf-8") p.write_text(contents, encoding="utf-8")
rootpath, inipath, ini_config = determine_setup(str(p), [str(tmp_path)]) rootpath, inipath, ini_config = determine_setup(str(p), [str(tmp_path)])
assert rootpath == tmp_path assert rootpath == tmp_path
assert inipath == p assert inipath == p
@ -1542,7 +1550,8 @@ class TestOverrideIniArgs:
custom = 1.0""".format( custom = 1.0""".format(
section=section section=section
) )
) ),
encoding="utf-8",
) )
pytester.makeconftest( pytester.makeconftest(
""" """

View File

@ -47,8 +47,12 @@ class TestConftestValueAccessGlobal:
) -> Generator[Path, None, None]: ) -> Generator[Path, None, None]:
tmp_path = tmp_path_factory.mktemp("basedir", numbered=True) tmp_path = tmp_path_factory.mktemp("basedir", numbered=True)
tmp_path.joinpath("adir/b").mkdir(parents=True) tmp_path.joinpath("adir/b").mkdir(parents=True)
tmp_path.joinpath("adir/conftest.py").write_text("a=1 ; Directory = 3") tmp_path.joinpath("adir/conftest.py").write_text(
tmp_path.joinpath("adir/b/conftest.py").write_text("b=2 ; a = 1.5") "a=1 ; Directory = 3", encoding="utf-8"
)
tmp_path.joinpath("adir/b/conftest.py").write_text(
"b=2 ; a = 1.5", encoding="utf-8"
)
if request.param == "inpackage": if request.param == "inpackage":
tmp_path.joinpath("adir/__init__.py").touch() tmp_path.joinpath("adir/__init__.py").touch()
tmp_path.joinpath("adir/b/__init__.py").touch() tmp_path.joinpath("adir/b/__init__.py").touch()
@ -123,8 +127,12 @@ class TestConftestValueAccessGlobal:
def test_conftest_in_nonpkg_with_init(tmp_path: Path, _sys_snapshot) -> None: def test_conftest_in_nonpkg_with_init(tmp_path: Path, _sys_snapshot) -> None:
tmp_path.joinpath("adir-1.0/b").mkdir(parents=True) tmp_path.joinpath("adir-1.0/b").mkdir(parents=True)
tmp_path.joinpath("adir-1.0/conftest.py").write_text("a=1 ; Directory = 3") tmp_path.joinpath("adir-1.0/conftest.py").write_text(
tmp_path.joinpath("adir-1.0/b/conftest.py").write_text("b=2 ; a = 1.5") "a=1 ; Directory = 3", encoding="utf-8"
)
tmp_path.joinpath("adir-1.0/b/conftest.py").write_text(
"b=2 ; a = 1.5", encoding="utf-8"
)
tmp_path.joinpath("adir-1.0/b/__init__.py").touch() tmp_path.joinpath("adir-1.0/b/__init__.py").touch()
tmp_path.joinpath("adir-1.0/__init__.py").touch() tmp_path.joinpath("adir-1.0/__init__.py").touch()
ConftestWithSetinitial(tmp_path.joinpath("adir-1.0", "b")) ConftestWithSetinitial(tmp_path.joinpath("adir-1.0", "b"))
@ -167,7 +175,7 @@ def test_conftest_global_import(pytester: Pytester) -> None:
sub = Path("sub") sub = Path("sub")
sub.mkdir() sub.mkdir()
subconf = sub / "conftest.py" subconf = sub / "conftest.py"
subconf.write_text("y=4") subconf.write_text("y=4", encoding="utf-8")
mod2 = conf._importconftest(subconf, importmode="prepend", rootpath=Path.cwd()) mod2 = conf._importconftest(subconf, importmode="prepend", rootpath=Path.cwd())
assert mod != mod2 assert mod != mod2
assert mod2.y == 4 assert mod2.y == 4
@ -246,7 +254,8 @@ def test_conftest_confcutdir(pytester: Pytester) -> None:
def pytest_addoption(parser): def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true") parser.addoption("--xyz", action="store_true")
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest("-h", "--confcutdir=%s" % x, x) result = pytester.runpytest("-h", "--confcutdir=%s" % x, x)
result.stdout.fnmatch_lines(["*--xyz*"]) result.stdout.fnmatch_lines(["*--xyz*"])
@ -274,9 +283,12 @@ def test_installed_conftest_is_picked_up(pytester: Pytester, tmp_path: Path) ->
@pytest.fixture @pytest.fixture
def fix(): return None def fix(): return None
""" """
) ),
encoding="utf-8",
)
tmp_path.joinpath("foo", "test_it.py").write_text(
"def test_it(fix): pass", encoding="utf-8"
) )
tmp_path.joinpath("foo", "test_it.py").write_text("def test_it(fix): pass")
result = pytester.runpytest("--pyargs", "foo") result = pytester.runpytest("--pyargs", "foo")
assert result.ret == 0 assert result.ret == 0
@ -401,7 +413,8 @@ def test_conftest_existing_junitxml(pytester: Pytester) -> None:
def pytest_addoption(parser): def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true") parser.addoption("--xyz", action="store_true")
""" """
) ),
encoding="utf-8",
) )
pytester.makefile(ext=".xml", junit="") # Writes junit.xml pytester.makefile(ext=".xml", junit="") # Writes junit.xml
result = pytester.runpytest("-h", "--junitxml", "junit.xml") result = pytester.runpytest("-h", "--junitxml", "junit.xml")
@ -412,7 +425,7 @@ def test_conftest_import_order(pytester: Pytester, monkeypatch: MonkeyPatch) ->
ct1 = pytester.makeconftest("") ct1 = pytester.makeconftest("")
sub = pytester.mkdir("sub") sub = pytester.mkdir("sub")
ct2 = sub / "conftest.py" ct2 = sub / "conftest.py"
ct2.write_text("") ct2.write_text("", encoding="utf-8")
def impct(p, importmode, root): def impct(p, importmode, root):
return p return p
@ -450,7 +463,8 @@ def test_fixture_dependency(pytester: Pytester) -> None:
def bar(foo): def bar(foo):
return 'bar' return 'bar'
""" """
) ),
encoding="utf-8",
) )
subsub = sub.joinpath("subsub") subsub = sub.joinpath("subsub")
subsub.mkdir() subsub.mkdir()
@ -467,7 +481,8 @@ def test_fixture_dependency(pytester: Pytester) -> None:
def test_event_fixture(bar): def test_event_fixture(bar):
assert bar == 'sub bar' assert bar == 'sub bar'
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest("sub") result = pytester.runpytest("sub")
result.stdout.fnmatch_lines(["*1 passed*"]) result.stdout.fnmatch_lines(["*1 passed*"])
@ -481,10 +496,11 @@ def test_conftest_found_with_double_dash(pytester: Pytester) -> None:
def pytest_addoption(parser): def pytest_addoption(parser):
parser.addoption("--hello-world", action="store_true") parser.addoption("--hello-world", action="store_true")
""" """
) ),
encoding="utf-8",
) )
p = sub.joinpath("test_hello.py") p = sub.joinpath("test_hello.py")
p.write_text("def test_hello(): pass") p.write_text("def test_hello(): pass", encoding="utf-8")
result = pytester.runpytest(str(p) + "::test_hello", "-h") result = pytester.runpytest(str(p) + "::test_hello", "-h")
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
""" """
@ -508,7 +524,8 @@ class TestConftestVisibility:
def fxtr(): def fxtr():
return "from-package" return "from-package"
""" """
) ),
encoding="utf-8",
) )
package.joinpath("test_pkgroot.py").write_text( package.joinpath("test_pkgroot.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -516,7 +533,8 @@ class TestConftestVisibility:
def test_pkgroot(fxtr): def test_pkgroot(fxtr):
assert fxtr == "from-package" assert fxtr == "from-package"
""" """
) ),
encoding="utf-8",
) )
swc = package.joinpath("swc") swc = package.joinpath("swc")
@ -530,7 +548,8 @@ class TestConftestVisibility:
def fxtr(): def fxtr():
return "from-swc" return "from-swc"
""" """
) ),
encoding="utf-8",
) )
swc.joinpath("test_with_conftest.py").write_text( swc.joinpath("test_with_conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -538,7 +557,8 @@ class TestConftestVisibility:
def test_with_conftest(fxtr): def test_with_conftest(fxtr):
assert fxtr == "from-swc" assert fxtr == "from-swc"
""" """
) ),
encoding="utf-8",
) )
snc = package.joinpath("snc") snc = package.joinpath("snc")
@ -551,7 +571,8 @@ class TestConftestVisibility:
assert fxtr == "from-package" # No local conftest.py, so should assert fxtr == "from-package" # No local conftest.py, so should
# use value from parent dir's # use value from parent dir's
""" """
) ),
encoding="utf-8",
) )
print("created directory structure:") print("created directory structure:")
for x in pytester.path.glob("**/"): for x in pytester.path.glob("**/"):
@ -625,7 +646,8 @@ def test_search_conftest_up_to_inifile(
@pytest.fixture @pytest.fixture
def fix1(): pass def fix1(): pass
""" """
) ),
encoding="utf-8",
) )
src.joinpath("test_foo.py").write_text( src.joinpath("test_foo.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -635,7 +657,8 @@ def test_search_conftest_up_to_inifile(
def test_2(out_of_reach): def test_2(out_of_reach):
pass pass
""" """
) ),
encoding="utf-8",
) )
root.joinpath("conftest.py").write_text( root.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -644,7 +667,8 @@ def test_search_conftest_up_to_inifile(
@pytest.fixture @pytest.fixture
def out_of_reach(): pass def out_of_reach(): pass
""" """
) ),
encoding="utf-8",
) )
args = [str(src)] args = [str(src)]
@ -727,7 +751,8 @@ def test_required_option_help(pytester: Pytester) -> None:
def pytest_addoption(parser): def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true", required=True) parser.addoption("--xyz", action="store_true", required=True)
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest("-h", x) result = pytester.runpytest("-h", x)
result.stdout.no_fnmatch_line("*argument --xyz is required*") result.stdout.no_fnmatch_line("*argument --xyz is required*")

View File

@ -357,7 +357,8 @@ class TestDoctests:
>>> 1/0 >>> 1/0
''' '''
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest("--doctest-modules") result = pytester.runpytest("--doctest-modules")
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
@ -448,7 +449,8 @@ class TestDoctests:
"""\ """\
import asdalsdkjaslkdjasd import asdalsdkjaslkdjasd
""" """
) ),
encoding="utf-8",
) )
pytester.maketxtfile( pytester.maketxtfile(
""" """
@ -492,7 +494,8 @@ class TestDoctests:
2 2
''' '''
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest(p, "--doctest-modules") result = pytester.runpytest(p, "--doctest-modules")
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
@ -1566,7 +1569,9 @@ def test_warning_on_unwrap_of_broken_object(
def test_is_setup_py_not_named_setup_py(tmp_path: Path) -> None: def test_is_setup_py_not_named_setup_py(tmp_path: Path) -> None:
not_setup_py = tmp_path.joinpath("not_setup.py") not_setup_py = tmp_path.joinpath("not_setup.py")
not_setup_py.write_text('from setuptools import setup; setup(name="foo")') not_setup_py.write_text(
'from setuptools import setup; setup(name="foo")', encoding="utf-8"
)
assert not _is_setup_py(not_setup_py) assert not _is_setup_py(not_setup_py)

View File

@ -324,7 +324,8 @@ def test_importerror(pytester: Pytester) -> None:
x = 1 x = 1
""" """
) ),
encoding="utf-8",
) )
pytester.path.joinpath("test_importerror.py").write_text( pytester.path.joinpath("test_importerror.py").write_text(
textwrap.dedent( textwrap.dedent(
@ -332,7 +333,8 @@ def test_importerror(pytester: Pytester) -> None:
def test_importerror(monkeypatch): def test_importerror(monkeypatch):
monkeypatch.setattr('package.a.x', 2) monkeypatch.setattr('package.a.x', 2)
""" """
) ),
encoding="utf-8",
) )
result = pytester.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
@ -434,11 +436,13 @@ def test_syspath_prepend_with_namespace_packages(
ns = d.joinpath("ns_pkg") ns = d.joinpath("ns_pkg")
ns.mkdir() ns.mkdir()
ns.joinpath("__init__.py").write_text( ns.joinpath("__init__.py").write_text(
"__import__('pkg_resources').declare_namespace(__name__)" "__import__('pkg_resources').declare_namespace(__name__)", encoding="utf-8"
) )
lib = ns.joinpath(dirname) lib = ns.joinpath(dirname)
lib.mkdir() lib.mkdir()
lib.joinpath("__init__.py").write_text("def check(): return %r" % dirname) lib.joinpath("__init__.py").write_text(
"def check(): return %r" % dirname, encoding="utf-8"
)
monkeypatch.syspath_prepend("hello") monkeypatch.syspath_prepend("hello")
import ns_pkg.hello import ns_pkg.hello

View File

@ -100,13 +100,13 @@ class TestImportPath:
def setuptestfs(self, path: Path) -> None: def setuptestfs(self, path: Path) -> None:
# print "setting up test fs for", repr(path) # print "setting up test fs for", repr(path)
samplefile = path / "samplefile" samplefile = path / "samplefile"
samplefile.write_text("samplefile\n") samplefile.write_text("samplefile\n", encoding="utf-8")
execfile = path / "execfile" execfile = path / "execfile"
execfile.write_text("x=42") execfile.write_text("x=42", encoding="utf-8")
execfilepy = path / "execfile.py" execfilepy = path / "execfile.py"
execfilepy.write_text("x=42") execfilepy.write_text("x=42", encoding="utf-8")
d = {1: 2, "hello": "world", "answer": 42} d = {1: 2, "hello": "world", "answer": 42}
path.joinpath("samplepickle").write_bytes(pickle.dumps(d, 1)) path.joinpath("samplepickle").write_bytes(pickle.dumps(d, 1))

View File

@ -38,6 +38,10 @@ passenv =
setenv = setenv =
_PYTEST_TOX_DEFAULT_POSARGS={env:_PYTEST_TOX_POSARGS_DOCTESTING:} {env:_PYTEST_TOX_POSARGS_LSOF:} {env:_PYTEST_TOX_POSARGS_XDIST:} _PYTEST_TOX_DEFAULT_POSARGS={env:_PYTEST_TOX_POSARGS_DOCTESTING:} {env:_PYTEST_TOX_POSARGS_LSOF:} {env:_PYTEST_TOX_POSARGS_XDIST:}
# See https://docs.python.org/3/library/io.html#io-encoding-warning
# If we don't enable this, neither can any of our downstream users!
PYTHONWARNDEFAULTENCODING=1
# Configuration to run with coverage similar to CI, e.g. # Configuration to run with coverage similar to CI, e.g.
# "tox -e py37-coverage". # "tox -e py37-coverage".
coverage: _PYTEST_TOX_COVERAGE_RUN=coverage run -m coverage: _PYTEST_TOX_COVERAGE_RUN=coverage run -m