Skip to content

Commit 3c6606e

Browse files
committed
Specify encoding in more tests
1 parent 4e743be commit 3c6606e

31 files changed

+217
-149
lines changed

doc/en/example/simple.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,7 @@ case we just write some information out to a ``failures`` file:
817817
# we only look at actual failing test calls, not setup/teardown
818818
if rep.when == "call" and rep.failed:
819819
mode = "a" if os.path.exists("failures") else "w"
820-
with open("failures", mode) as f:
820+
with open("failures", mode, encoding="utf-8") as f:
821821
# let's also access a fixture for the fun of it
822822
if "tmp_path" in item.fixturenames:
823823
extra = " ({})".format(item.funcargs["tmp_path"])

doc/en/how-to/fixtures.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1698,7 +1698,7 @@ and declare its use in a test module via a ``usefixtures`` marker:
16981698
class TestDirectoryInit:
16991699
def test_cwd_starts_empty(self):
17001700
assert os.listdir(os.getcwd()) == []
1701-
with open("myfile", "w") as f:
1701+
with open("myfile", "w", encoding="utf-8") as f:
17021702
f.write("hello")
17031703
17041704
def test_cwd_again_starts_empty(self):

doc/en/how-to/unittest.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,10 @@ creation of a per-test temporary directory:
207207
@pytest.fixture(autouse=True)
208208
def initdir(self, tmp_path, monkeypatch):
209209
monkeypatch.chdir(tmp_path) # change to pytest-provided temporary directory
210-
tmp_path.joinpath("samplefile.ini").write_text("# testdata")
210+
tmp_path.joinpath("samplefile.ini").write_text("# testdata", encoding="utf-8")
211211
212212
def test_method(self):
213-
with open("samplefile.ini") as f:
213+
with open("samplefile.ini", encoding="utf-8") as f:
214214
s = f.read()
215215
assert "testdata" in s
216216

scripts/towncrier-draft-to-file.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ def main():
77
Platform agnostic wrapper script for towncrier.
88
Fixes the issue (#7251) where windows users are unable to natively run tox -e docs to build pytest docs.
99
"""
10-
with open("doc/en/_changelog_towncrier_draft.rst", "w") as draft_file:
10+
with open(
11+
"doc/en/_changelog_towncrier_draft.rst", "w", encoding="utf-8"
12+
) as draft_file:
1113
return call(("towncrier", "--draft"), stdout=draft_file)
1214

1315

src/_pytest/helpconfig.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def pytest_cmdline_parse():
105105
if config.option.debug:
106106
# --debug | --debug <file.log> was provided.
107107
path = config.option.debug
108-
debugfile = open(path, "w")
108+
debugfile = open(path, "w", encoding="utf-8")
109109
debugfile.write(
110110
"versions pytest-%s, "
111111
"python-%s\ncwd=%s\nargs=%s\n\n"

testing/_py/test_local.py

Lines changed: 58 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
1+
import contextlib
12
import multiprocessing
23
import os
34
import sys
45
import time
6+
import warnings
57
from unittest import mock
68

79
import pytest
810
from py import error
911
from py.path import local
1012

1113

14+
@contextlib.contextmanager
15+
def ignore_encoding_warning():
16+
with warnings.catch_warnings():
17+
with contextlib.suppress(NameError): # new in 3.10
18+
warnings.simplefilter("ignore", EncodingWarning)
19+
yield
20+
21+
1222
class CommonFSTests:
1323
def test_constructor_equality(self, path1):
1424
p = path1.__class__(path1)
@@ -223,7 +233,7 @@ def test_cmp(self, path1):
223233
assert not (path1 < path1)
224234

225235
def test_simple_read(self, path1):
226-
x = path1.join("samplefile").read("r")
236+
x = path1.join("samplefile").read_text("r")
227237
assert x == "samplefile\n"
228238

229239
def test_join_div_operator(self, path1):
@@ -265,12 +275,14 @@ def test_newext(self, path1):
265275

266276
def test_readlines(self, path1):
267277
fn = path1.join("samplefile")
268-
contents = fn.readlines()
278+
with ignore_encoding_warning():
279+
contents = fn.readlines()
269280
assert contents == ["samplefile\n"]
270281

271282
def test_readlines_nocr(self, path1):
272283
fn = path1.join("samplefile")
273-
contents = fn.readlines(cr=0)
284+
with ignore_encoding_warning():
285+
contents = fn.readlines(cr=0)
274286
assert contents == ["samplefile", ""]
275287

276288
def test_file(self, path1):
@@ -362,8 +374,8 @@ def test_copy_file(self, path1):
362374
initpy.copy(copied)
363375
try:
364376
assert copied.check()
365-
s1 = initpy.read()
366-
s2 = copied.read()
377+
s1 = initpy.read_text(encoding="utf-8")
378+
s2 = copied.read_text(encoding="utf-8")
367379
assert s1 == s2
368380
finally:
369381
if copied.check():
@@ -376,8 +388,8 @@ def test_copy_dir(self, path1):
376388
otherdir.copy(copied)
377389
assert copied.check(dir=1)
378390
assert copied.join("__init__.py").check(file=1)
379-
s1 = otherdir.join("__init__.py").read()
380-
s2 = copied.join("__init__.py").read()
391+
s1 = otherdir.join("__init__.py").read_text(encoding="utf-8")
392+
s2 = copied.join("__init__.py").read_text(encoding="utf-8")
381393
assert s1 == s2
382394
finally:
383395
if copied.check(dir=1):
@@ -463,13 +475,13 @@ def setuptestfs(path):
463475
return
464476
# print "setting up test fs for", repr(path)
465477
samplefile = path.ensure("samplefile")
466-
samplefile.write("samplefile\n")
478+
samplefile.write_text("samplefile\n", encoding="utf-8")
467479

468480
execfile = path.ensure("execfile")
469-
execfile.write("x=42")
481+
execfile.write_text("x=42", encoding="utf-8")
470482

471483
execfilepy = path.ensure("execfile.py")
472-
execfilepy.write("x=42")
484+
execfilepy.write_text("x=42", encoding="utf-8")
473485

474486
d = {1: 2, "hello": "world", "answer": 42}
475487
path.ensure("samplepickle").dump(d)
@@ -481,22 +493,24 @@ def setuptestfs(path):
481493
otherdir.ensure("__init__.py")
482494

483495
module_a = otherdir.ensure("a.py")
484-
module_a.write("from .b import stuff as result\n")
496+
module_a.write_text("from .b import stuff as result\n", encoding="utf-8")
485497
module_b = otherdir.ensure("b.py")
486-
module_b.write('stuff="got it"\n')
498+
module_b.write_text('stuff="got it"\n', encoding="utf-8")
487499
module_c = otherdir.ensure("c.py")
488-
module_c.write(
500+
module_c.write_text(
489501
"""import py;
490502
import otherdir.a
491503
value = otherdir.a.result
492-
"""
504+
""",
505+
encoding="utf-8",
493506
)
494507
module_d = otherdir.ensure("d.py")
495-
module_d.write(
508+
module_d.write_text(
496509
"""import py;
497510
from otherdir import a
498511
value2 = a.result
499-
"""
512+
""",
513+
encoding="utf-8",
500514
)
501515

502516

@@ -534,9 +548,11 @@ def batch_make_numbered_dirs(rootdir, repeats):
534548
for i in range(repeats):
535549
dir_ = local.make_numbered_dir(prefix="repro-", rootdir=rootdir)
536550
file_ = dir_.join("foo")
537-
file_.write("%s" % i)
538-
actual = int(file_.read())
539-
assert actual == i, f"int(file_.read()) is {actual} instead of {i}"
551+
file_.write_text("%s" % i, encoding="utf-8")
552+
actual = int(file_.read_text(encoding="utf-8"))
553+
assert (
554+
actual == i
555+
), f"int(file_.read_text(encoding='utf-8')) is {actual} instead of {i}"
540556
dir_.join(".lock").remove(ignore_errors=True)
541557
return True
542558

@@ -692,14 +708,14 @@ def test_gt_with_strings(self, path1):
692708

693709
def test_open_and_ensure(self, path1):
694710
p = path1.join("sub1", "sub2", "file")
695-
with p.open("w", ensure=1) as f:
711+
with p.open("w", ensure=1, encoding="utf-8") as f:
696712
f.write("hello")
697-
assert p.read() == "hello"
713+
assert p.read_text(encoding="utf-8") == "hello"
698714

699715
def test_write_and_ensure(self, path1):
700716
p = path1.join("sub1", "sub2", "file")
701-
p.write("hello", ensure=1)
702-
assert p.read() == "hello"
717+
p.write_text("hello", ensure=1, encoding="utf-8")
718+
assert p.read_text(encoding="utf-8") == "hello"
703719

704720
@pytest.mark.parametrize("bin", (False, True))
705721
def test_dump(self, tmpdir, bin):
@@ -770,9 +786,9 @@ def test_ensure_filepath_withdir(self, tmpdir):
770786
newfile = tmpdir.join("test1", "test")
771787
newfile.ensure()
772788
assert newfile.check(file=1)
773-
newfile.write("42")
789+
newfile.write_text("42", encoding="utf-8")
774790
newfile.ensure()
775-
s = newfile.read()
791+
s = newfile.read_text(encoding="utf-8")
776792
assert s == "42"
777793

778794
def test_ensure_filepath_withoutdir(self, tmpdir):
@@ -806,9 +822,9 @@ def test_long_filenames(self, tmpdir):
806822
newfilename = "/test" * 60 # type:ignore[unreachable]
807823
l1 = tmpdir.join(newfilename)
808824
l1.ensure(file=True)
809-
l1.write("foo")
825+
l1.write_text("foo", encoding="utf-8")
810826
l2 = tmpdir.join(newfilename)
811-
assert l2.read() == "foo"
827+
assert l2.read_text(encoding="utf-8") == "foo"
812828

813829
def test_visit_depth_first(self, tmpdir):
814830
tmpdir.ensure("a", "1")
@@ -1278,22 +1294,22 @@ class TestPOSIXLocalPath:
12781294
def test_hardlink(self, tmpdir):
12791295
linkpath = tmpdir.join("test")
12801296
filepath = tmpdir.join("file")
1281-
filepath.write("Hello")
1297+
filepath.write_text("Hello", encoding="utf-8")
12821298
nlink = filepath.stat().nlink
12831299
linkpath.mklinkto(filepath)
12841300
assert filepath.stat().nlink == nlink + 1
12851301

12861302
def test_symlink_are_identical(self, tmpdir):
12871303
filepath = tmpdir.join("file")
1288-
filepath.write("Hello")
1304+
filepath.write_text("Hello", encoding="utf-8")
12891305
linkpath = tmpdir.join("test")
12901306
linkpath.mksymlinkto(filepath)
12911307
assert linkpath.readlink() == str(filepath)
12921308

12931309
def test_symlink_isfile(self, tmpdir):
12941310
linkpath = tmpdir.join("test")
12951311
filepath = tmpdir.join("file")
1296-
filepath.write("")
1312+
filepath.write_text("", encoding="utf-8")
12971313
linkpath.mksymlinkto(filepath)
12981314
assert linkpath.check(file=1)
12991315
assert not linkpath.check(link=0, file=1)
@@ -1302,10 +1318,12 @@ def test_symlink_isfile(self, tmpdir):
13021318
def test_symlink_relative(self, tmpdir):
13031319
linkpath = tmpdir.join("test")
13041320
filepath = tmpdir.join("file")
1305-
filepath.write("Hello")
1321+
filepath.write_text("Hello", encoding="utf-8")
13061322
linkpath.mksymlinkto(filepath, absolute=False)
13071323
assert linkpath.readlink() == "file"
1308-
assert filepath.read() == linkpath.read()
1324+
assert filepath.read_text(encoding="utf-8") == linkpath.read_text(
1325+
encoding="utf-8"
1326+
)
13091327

13101328
def test_symlink_not_existing(self, tmpdir):
13111329
linkpath = tmpdir.join("testnotexisting")
@@ -1338,7 +1356,7 @@ def test_symlink_remove(self, tmpdir):
13381356
def test_realpath_file(self, tmpdir):
13391357
linkpath = tmpdir.join("test")
13401358
filepath = tmpdir.join("file")
1341-
filepath.write("")
1359+
filepath.write_text("", encoding="utf-8")
13421360
linkpath.mksymlinkto(filepath)
13431361
realpath = linkpath.realpath()
13441362
assert realpath.basename == "file"
@@ -1383,7 +1401,7 @@ def test_atime(self, tmpdir):
13831401
atime1 = path.atime()
13841402
# we could wait here but timer resolution is very
13851403
# system dependent
1386-
path.read()
1404+
path.read_binary()
13871405
time.sleep(ATIME_RESOLUTION)
13881406
atime2 = path.atime()
13891407
time.sleep(ATIME_RESOLUTION)
@@ -1467,7 +1485,7 @@ def test_copy_stat_dir(self, tmpdir):
14671485
test_files = ["a", "b", "c"]
14681486
src = tmpdir.join("src")
14691487
for f in test_files:
1470-
src.join(f).write(f, ensure=True)
1488+
src.join(f).write_text(f, ensure=True, encoding="utf-8")
14711489
dst = tmpdir.join("dst")
14721490
# a small delay before the copy
14731491
time.sleep(ATIME_RESOLUTION)
@@ -1521,10 +1539,11 @@ def test_listdir(self, tmpdir):
15211539
def test_read_write(self, tmpdir):
15221540
x = tmpdir.join("hello")
15231541
part = "hällo"
1524-
x.write(part)
1525-
assert x.read() == part
1526-
x.write(part.encode(sys.getdefaultencoding()))
1527-
assert x.read() == part.encode(sys.getdefaultencoding())
1542+
with ignore_encoding_warning():
1543+
x.write(part)
1544+
assert x.read() == part
1545+
x.write(part.encode(sys.getdefaultencoding()))
1546+
assert x.read() == part.encode(sys.getdefaultencoding())
15281547

15291548

15301549
class TestBinaryAndTextMethods:

testing/acceptance_test.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ def test_pyargs_only_imported_once(self, pytester: Pytester) -> None:
613613

614614
def test_pyargs_filename_looks_like_module(self, pytester: Pytester) -> None:
615615
pytester.path.joinpath("conftest.py").touch()
616-
pytester.path.joinpath("t.py").write_text("def test(): pass")
616+
pytester.path.joinpath("t.py").write_text("def test(): pass", encoding="utf-8")
617617
result = pytester.runpytest("--pyargs", "t.py")
618618
assert result.ret == ExitCode.OK
619619

@@ -622,8 +622,12 @@ def test_cmdline_python_package(self, pytester: Pytester, monkeypatch) -> None:
622622

623623
monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", False)
624624
path = pytester.mkpydir("tpkg")
625-
path.joinpath("test_hello.py").write_text("def test_hello(): pass")
626-
path.joinpath("test_world.py").write_text("def test_world(): pass")
625+
path.joinpath("test_hello.py").write_text(
626+
"def test_hello(): pass", encoding="utf-8"
627+
)
628+
path.joinpath("test_world.py").write_text(
629+
"def test_world(): pass", encoding="utf-8"
630+
)
627631
result = pytester.runpytest("--pyargs", "tpkg")
628632
assert result.ret == 0
629633
result.stdout.fnmatch_lines(["*2 passed*"])
@@ -662,13 +666,15 @@ def test_cmdline_python_namespace_package(
662666
ns = d.joinpath("ns_pkg")
663667
ns.mkdir()
664668
ns.joinpath("__init__.py").write_text(
665-
"__import__('pkg_resources').declare_namespace(__name__)"
669+
"__import__('pkg_resources').declare_namespace(__name__)",
670+
encoding="utf-8",
666671
)
667672
lib = ns.joinpath(dirname)
668673
lib.mkdir()
669674
lib.joinpath("__init__.py").touch()
670675
lib.joinpath(f"test_{dirname}.py").write_text(
671-
f"def test_{dirname}(): pass\ndef test_other():pass"
676+
f"def test_{dirname}(): pass\ndef test_other():pass",
677+
encoding="utf-8",
672678
)
673679

674680
# The structure of the test directory is now:
@@ -754,10 +760,10 @@ def test_cmdline_python_package_symlink(
754760
lib.mkdir()
755761
lib.joinpath("__init__.py").touch()
756762
lib.joinpath("test_bar.py").write_text(
757-
"def test_bar(): pass\ndef test_other(a_fixture):pass"
763+
"def test_bar(): pass\ndef test_other(a_fixture):pass", encoding="utf-8"
758764
)
759765
lib.joinpath("conftest.py").write_text(
760-
"import pytest\n@pytest.fixture\ndef a_fixture():pass"
766+
"import pytest\n@pytest.fixture\ndef a_fixture():pass", encoding="utf-8"
761767
)
762768

763769
d_local = pytester.mkdir("symlink_root")
@@ -1276,8 +1282,7 @@ def test_simple():
12761282
result.stderr.fnmatch_lines(["*@this is stderr@*"])
12771283

12781284
# now ensure the output is in the junitxml
1279-
with open(pytester.path.joinpath("output.xml")) as f:
1280-
fullXml = f.read()
1285+
fullXml = pytester.path.joinpath("output.xml").read_text(encoding="utf-8")
12811286
assert "@this is stdout@\n" in fullXml
12821287
assert "@this is stderr@\n" in fullXml
12831288

0 commit comments

Comments
 (0)