File: generate_tests.py

package info (click to toggle)
python-inline-snapshot 0.23.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,116 kB
  • sloc: python: 6,888; makefile: 34; sh: 28
file content (173 lines) | stat: -rw-r--r-- 3,210 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import ast
import random
import sys

from pysource_minimize import minimize

from inline_snapshot import UsageError
from inline_snapshot.testing import Example

header = """
from dataclasses import dataclass

@dataclass
class A:
    a:int
    b:int=5
    c:int=5

def f(v):
    return v

"""


def chose(l):
    return random.choice(l)


def gen_new_value(values):

    kind = chose(["dataclass", "dict", "tuple", "list", "f"])

    if kind == "dataclass":
        data_type = chose(["A"])
        num_args = chose(range(1, 3))
        num_pos_args = chose(range(num_args))
        assert num_pos_args <= num_args

        args_names = ["a", "b", "c"]
        random.shuffle(args_names)

        args = [
            *[chose(values) for _ in range(num_pos_args)],
            *[
                f"{args_names.pop()}={chose(values)}"
                for _ in range(num_args - num_pos_args)
            ],
        ]

        return f"{data_type}({', '.join(args)})"

    if kind == "tuple":
        return "(" + ", ".join(chose(values) for _ in range(3)) + ")"

    if kind == "list":
        return "[" + ", ".join(chose(values) for _ in range(3)) + "]"

    if kind == "dict":
        return (
            "[" + ", ".join(f"{chose(values)}:{chose(values)}" for _ in range(3)) + "]"
        )

    if kind == "f":
        return f"f({chose(values)})"


context = dict()
exec(header, context, context)


def is_valid_value(v):
    try:
        eval(v, context, {})
    except:
        return False
    return True


def value_of(v):
    return eval(v, context, {})


def gen_values():
    values = [
        "1",
        "'abc'",
        "True",
        "list()",
        "dict()",
        "set()",
        "tuple()",
        "[]",
        "{}",
        "()",
        "{*()}",
    ]

    while len(values) <= 500:
        new_value = gen_new_value([v for v in values if len(v) < 50])

        if is_valid_value(new_value):
            values.append(new_value)

    return values


def fmt(code):
    return ast.unparse(ast.parse(code))


class Store:
    def __eq__(self, other):
        self.value = other
        return True


def gen_test(values):

    va = chose(values)
    vb = chose(values)

    test = f"""
from inline_snapshot import snapshot
{header}

def test_a():
    assert {va} == snapshot({vb})
    assert {vb} == snapshot({va})

def test_b():
    for _ in [1,2,3]:
        assert {va} == snapshot({vb})
        assert {vb} == snapshot({va})

def test_c():
    snapshot({vb})
    snapshot({va})
"""
    test = fmt(test)

    if value_of(va) == value_of(vb):
        return

    def contains_bug(code):

        try:
            Example({"test.py": code}).run_inline(["--inline-snapshot=fix"])
        except UsageError:
            return False
        except KeyboardInterrupt:
            raise
        except AssertionError:
            return True
        except:
            return True

        return False

    if not contains_bug(test):
        return

    test = minimize(test, checker=contains_bug)
    print("minimal code:")
    print("=" * 20)
    print(test)
    sys.exit()


if __name__ == "__main__":
    values = gen_values()

    for i in range(100000):
        gen_test(values)