|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Fuzz tests for fsutil I/O utilities using atheris. |
| 4 | +
|
| 5 | +Run with: |
| 6 | + python fuzz/fuzz_io.py |
| 7 | +Or with a corpus: |
| 8 | + python fuzz/fuzz_io.py corpus/ |
| 9 | +""" |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import sys |
| 13 | +import tempfile |
| 14 | + |
| 15 | +import atheris |
| 16 | + |
| 17 | +with atheris.instrument_imports(): |
| 18 | + import fsutil |
| 19 | + |
| 20 | + |
| 21 | +def fuzz_one_input(data: bytes) -> None: |
| 22 | + fdp = atheris.FuzzedDataProvider(data) |
| 23 | + |
| 24 | + content = fdp.ConsumeUnicodeNoSurrogates(512) |
| 25 | + encoding = fdp.PickValueInList(["utf-8", "latin-1", "ascii"]) |
| 26 | + |
| 27 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 28 | + filepath = fsutil.join_path(tmpdir, "fuzz_test.txt") |
| 29 | + |
| 30 | + # Fuzz write/read round-trip |
| 31 | + try: |
| 32 | + fsutil.write_file(filepath, content, encoding=encoding) |
| 33 | + fsutil.read_file(filepath, encoding=encoding) |
| 34 | + except (UnicodeEncodeError, UnicodeDecodeError, ValueError): |
| 35 | + pass |
| 36 | + except Exception: |
| 37 | + pass |
| 38 | + |
| 39 | + # Fuzz JSON write/read |
| 40 | + try: |
| 41 | + json_data = {"key": content, "num": fdp.ConsumeInt(4)} |
| 42 | + json_filepath = fsutil.join_path(tmpdir, "fuzz_test.json") |
| 43 | + fsutil.write_file_json(json_filepath, json_data) |
| 44 | + fsutil.read_file_json(json_filepath) |
| 45 | + except (ValueError, OverflowError): |
| 46 | + pass |
| 47 | + except Exception: |
| 48 | + pass |
| 49 | + |
| 50 | + |
| 51 | +def main() -> None: |
| 52 | + atheris.Setup(sys.argv, fuzz_one_input) |
| 53 | + atheris.Fuzz() |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + main() |
0 commit comments