Skip to content

Commit 05731c0

Browse files
authored
Fix profiling scripts with a UTF-8 BOM (#1092)
1 parent 9069a32 commit 05731c0

2 files changed

Lines changed: 51 additions & 1 deletion

File tree

scalene/scalene_profiler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2027,7 +2027,7 @@ def run_profiler(
20272027
raise FileNotFoundError
20282028
# Use the full absolute path of the program being profiled, expanding ~ if need be.
20292029
prog_name = os.path.abspath(os.path.expanduser(progs[0]))
2030-
with open(prog_name, encoding="utf-8") as prog_being_profiled:
2030+
with open(prog_name, encoding="utf-8-sig") as prog_being_profiled:
20312031
# Read in the code and compile it.
20322032
code: Any = ""
20332033
try:

tests/test_issue1091_bom.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""Regression test for issue #1091: UTF-8 BOM in a profiled script."""
2+
3+
from __future__ import annotations
4+
5+
import subprocess
6+
import sys
7+
from pathlib import Path
8+
9+
import pytest
10+
11+
12+
@pytest.mark.parametrize(
13+
("name", "source", "expected"),
14+
[
15+
("plain", b'print("PLAIN_OK")\n', "PLAIN_OK"),
16+
("bom", b'\xef\xbb\xbfprint("BOM_OK")\n', "BOM_OK"),
17+
("utf8_non_ascii", 'print("é_OK")\n'.encode(), "é_OK"),
18+
],
19+
)
20+
def test_cpu_only_cli_accepts_utf8_script_variants(
21+
tmp_path: Path, name: str, source: bytes, expected: str
22+
) -> None:
23+
"""The real CLI must execute BOM and ordinary UTF-8 scripts successfully."""
24+
script = tmp_path / f"{name}.py"
25+
script.write_bytes(source)
26+
27+
result = subprocess.run(
28+
[
29+
sys.executable,
30+
"-m",
31+
"scalene",
32+
"run",
33+
"--cpu-only",
34+
"--no-browser",
35+
str(script),
36+
],
37+
cwd=tmp_path,
38+
check=False,
39+
capture_output=True,
40+
text=True,
41+
timeout=60,
42+
)
43+
output = result.stdout + result.stderr
44+
45+
assert result.returncode == 0, (
46+
f"Scalene failed for {name}: exit={result.returncode}\n{output[-3000:]}"
47+
)
48+
assert expected in result.stdout, (
49+
f"Profiled {name} script did not run to completion:\n{output[-3000:]}"
50+
)

0 commit comments

Comments
 (0)