diff --git a/app/common/fileutil.py b/app/common/fileutil.py index 60650ff..43a3768 100644 --- a/app/common/fileutil.py +++ b/app/common/fileutil.py @@ -44,15 +44,19 @@ def _get_file_mime(file_path): def _is_perf_file(file_path): f = get_file(file_path) - for line in f: - if (line[0] == '#'): - continue - r = event_regexp.search(line) - if r: - f.close() - return True - f.close() + try: + for line in f: + if line and line[0] == '#': + continue + r = event_regexp.search(line) + if r: + return True + return False + except Exception: return False + finally: + f.close() + return False def get_file(file_path): diff --git a/tests/test_fileutil.py b/tests/test_fileutil.py new file mode 100644 index 0000000..5b1026f --- /dev/null +++ b/tests/test_fileutil.py @@ -0,0 +1,18 @@ +import os +import tempfile +from app import config +from app.common.fileutil import _is_perf_file + + +def test_is_perf_file_unreadable_bytes(): + # Create a temporary file in PROFILE_DIR containing invalid UTF-8 bytes + with tempfile.NamedTemporaryFile(dir=config.PROFILE_DIR, mode="wb", delete=False) as f: + f.write(b"\xff\xfe\xfd\x00\x98\xa1\xb2\xc3") + temp_path = f.name + + try: + # Should return False without raising UnicodeDecodeError + assert _is_perf_file(temp_path) is False + finally: + if os.path.exists(temp_path): + os.remove(temp_path)