File: test_redos.py

package info (click to toggle)
python-markdown2 2.5.4-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 6,492 kB
  • sloc: python: 6,201; perl: 1,493; php: 865; makefile: 37
file content (90 lines) | stat: -rw-r--r-- 2,198 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import logging
import subprocess
import sys
import time
from pathlib import Path

log = logging.getLogger("test")
LIB_DIR = Path(__file__).parent.parent / "lib"


def pull_387_example_1():
    # https://github.com/trentm/python-markdown2/pull/387
    return "[#a" + " " * 3456


def pull_387_example_2():
    # https://github.com/trentm/python-markdown2/pull/387
    return "```" + "\n" * 3456


def pull_387_example_3():
    # https://github.com/trentm/python-markdown2/pull/387
    return "-*-" + " " * 3456


def pull_402():
    # https://github.com/trentm/python-markdown2/pull/402
    return " " * 100_000 + "$"


def issue493():
    # https://github.com/trentm/python-markdown2/issues/493
    return "**_" + "*_" * 38730 * 10 + "\x00"


def issue_633():
    # https://github.com/trentm/python-markdown2/issues/633
    return '<p m="1"' * 2500 + " " * 5000 + "</div"


# whack everything in a dict for easy lookup later on
CASES = {
    fn.__name__: fn
    for fn in [
        pull_387_example_1,
        pull_387_example_2,
        pull_387_example_3,
        pull_402,
        issue493,
        issue_633,
    ]
}


if __name__ == "__main__":
    logging.basicConfig()

    if "--execute" in sys.argv:
        testcase = CASES[sys.argv[sys.argv.index("--execute") + 1]]
        sys.path.insert(0, str(LIB_DIR))
        from markdown2 import markdown

        markdown(testcase())
        sys.exit(0)

    print("-- ReDoS tests")

    fails = []
    start_time = time.time()
    for testcase in CASES:
        print(f"markdown2/redos/{testcase} ... ", end="")

        testcase_start_time = time.time()
        try:
            subprocess.run([sys.executable, __file__, "--execute", testcase], timeout=3)
        except subprocess.TimeoutExpired:
            fails.append(testcase)
            print(f"FAIL ({time.time() - testcase_start_time:.3f}s)")
        else:
            print(f"ok ({time.time() - testcase_start_time:.3f}s)")

    print("----------------------------------------------------------------------")
    print(f"Ran {len(CASES)} tests in {time.time() - start_time:.3f}s")

    if fails:
        print("FAIL:", fails)
    else:
        print("OK")

    sys.exit(len(fails))