cros lint: require encoding='utf-8' with pathlib write_text calls
When writing a file in text mode, the default encoding used is whatever
the system default is which can be just about anything. To avoid errors
when run in non-UTF-8 locales, force people to always specify encoding
and be set to UTF-8.
This also helps remind people when they want to write files in text or
in binary mode. Ad-hoc & unittest coverage isn't always sufficient.
BUG=b:187789896
TEST=`cros lint` is clean in chromite
Change-Id: Icd7f845d20490ce2f0a465db48894cbc08ca0657
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/4188829
Reviewed-by: Sloan Johnson <sloanjohnson@google.com>
Commit-Queue: Mike Frysinger <vapier@chromium.org>
Tested-by: Mike Frysinger <vapier@chromium.org>
diff --git a/scripts/wrapper3_unittest.py b/scripts/wrapper3_unittest.py
index dfdfe8b..39f0ef6 100644
--- a/scripts/wrapper3_unittest.py
+++ b/scripts/wrapper3_unittest.py
@@ -71,7 +71,9 @@
"""Create a script at |path|."""
path.parent.mkdir(parents=True, exist_ok=True)
path = path.with_suffix(".py")
- path.write_text('def main(argv):\n print("hi", argv)\n')
+ path.write_text(
+ 'def main(argv):\n print("hi", argv)\n', encoding="utf-8"
+ )
if wrapper is None:
wrapper = path.with_suffix("")
wrapper.symlink_to(self.wrapper)
@@ -158,7 +160,9 @@
prog = self.chromite_dir / "subdir" / "prog_unittest"
prog.parent.mkdir(parents=True, exist_ok=True)
path = prog.with_suffix(".py")
- path.write_text('import sys; print("hi", sys.argv[1:])\n')
+ path.write_text(
+ 'import sys; print("hi", sys.argv[1:])\n', encoding="utf-8"
+ )
prog.symlink_to(self.wrapper)
self._run_tests(prog)
@@ -168,7 +172,7 @@
prog.parent.mkdir(parents=True, exist_ok=True)
prog.symlink_to(self.wrapper)
prog.with_suffix(".py").write_text(
- 'import sys; print("hi", sys.argv[1:])\n'
+ 'import sys; print("hi", sys.argv[1:])\n', encoding="utf-8"
)
self._run_tests(prog)
@@ -190,7 +194,7 @@
prog = self.scripts_dir / "prog"
prog.symlink_to(self.wrapper)
# Script has syntax errors and cannot be imported.
- prog.with_suffix(".py").write_text("}")
+ prog.with_suffix(".py").write_text("}", encoding="utf-8")
self._run_tests(prog, verify=verify, check=False)
def testDashes(self):