File: test_customize.py

package info (click to toggle)
python-inline-snapshot 0.32.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,900 kB
  • sloc: python: 11,339; makefile: 40; sh: 36
file content (406 lines) | stat: -rw-r--r-- 10,218 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import pytest

from inline_snapshot import snapshot
from inline_snapshot.testing import Example


@pytest.mark.parametrize(
    "original,flag", [("'a'", "update"), ("'b'", "fix"), ("", "create")]
)
def test_custom_dirty_equal(original, flag):

    Example(
        {
            "tests/conftest.py": """\
from inline_snapshot.plugin import customize
from inline_snapshot.plugin import Builder
from dirty_equals import IsStr

class InlineSnapshotPlugin:
    @customize
    def re_handler(self,value, builder: Builder):
        if value == IsStr(regex="[a-z]"):
            return builder.create_call(IsStr, [], {"regex": "[a-z]"})
""",
            "tests/test_something.py": f"""\
from inline_snapshot import snapshot

def test_a():
    assert snapshot({original}) == "a"
""",
        }
    ).run_inline(
        [f"--inline-snapshot={flag}"],
        changed_files=snapshot(
            {
                "tests/test_something.py": """\
from inline_snapshot import snapshot

from dirty_equals import IsStr

def test_a():
    assert snapshot(IsStr(regex="[a-z]")) == "a"
"""
            }
        ),
    )


@pytest.mark.parametrize(
    "original,flag",
    [("{'1': 1, '2': 2}", "update"), ("5", "fix"), ("", "create")],
)
def test_create_imports(original, flag):

    Example(
        {
            "tests/test_something.py": f"""\
from inline_snapshot import snapshot

def counter():
    from collections import Counter
    return Counter("122")

def test():
    assert counter() == snapshot({original})
"""
        }
    ).run_inline(
        [f"--inline-snapshot={flag}"],
        changed_files=snapshot(
            {
                "tests/test_something.py": """\
from inline_snapshot import snapshot

from collections import Counter

def counter():
    from collections import Counter
    return Counter("122")

def test():
    assert counter() == snapshot(Counter({"1": 1, "2": 2}))
"""
            }
        ),
    )


@pytest.mark.parametrize(
    "original,flag",
    [("ComplexObj(1, 2)", "update"), ("'wrong'", "fix"), ("", "create")],
)
def test_with_import(original, flag):
    """Test that with_import adds both simple and nested module import statements correctly."""

    Example(
        {
            "conftest.py": """\
from inline_snapshot.plugin import customize
from inline_snapshot.plugin import Builder, Import
from pkg.subpkg import ComplexObj

class InlineSnapshotPlugin:
    @customize
    def complex_handler(self, value, builder: Builder):
        if isinstance(value, ComplexObj):
            return builder.create_code(
                f"mod1.helper(pkg.subpkg.create({value.a!r}, {value.b!r}))",
                imports=[Import("mod1"), Import("pkg.subpkg")]
            )
""",
            "mod1.py": """\
def helper(obj):
    return obj
""",
            "pkg/__init__.py": "",
            "pkg/subpkg.py": """\
class ComplexObj:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __eq__(self, other):
        return isinstance(other, ComplexObj) and self.a == other.a and self.b == other.b

def create(a, b):
    return ComplexObj(a, b)
""",
            "test_something.py": f"""\
from inline_snapshot import snapshot
from pkg.subpkg import ComplexObj

def test_a():
    assert snapshot({original}) == ComplexObj(1, 2)
""",
        }
    ).run_inline(
        [f"--inline-snapshot={flag}"],
        changed_files=snapshot(
            {
                "test_something.py": """\
from inline_snapshot import snapshot
from pkg.subpkg import ComplexObj

import mod1
import pkg.subpkg

def test_a():
    assert snapshot(mod1.helper(pkg.subpkg.create(1, 2))) == ComplexObj(1, 2)
"""
            }
        ),
    ).run_inline()


@pytest.mark.parametrize(
    "original,flag", [("MyClass('value')", "update"), ("'wrong'", "fix")]
)
@pytest.mark.parametrize("existing_import", ["\nimport mymodule\n", ""])
def test_with_import_preserves_existing(original, flag, existing_import):
    """Test that with_import preserves existing import statements."""

    Example(
        {
            "conftest.py": """\
from inline_snapshot.plugin import customize
from inline_snapshot.plugin import Builder, Import
from mymodule import MyClass

class InlineSnapshotPlugin:
    @customize
    def myclass_handler(self, value, builder: Builder):
        if isinstance(value, MyClass):
            return builder.create_code(
                f"mymodule.MyClass({value.value!r})",
                imports=[Import("mymodule")]
            )
""",
            "mymodule.py": """\
class MyClass:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return isinstance(other, MyClass) and self.value == other.value
""",
            "test_something.py": f"""\
from inline_snapshot import snapshot
from mymodule import MyClass

import os # just another import
{existing_import}\

def test_a():
    assert snapshot({original}) == MyClass("value")
""",
        }
    ).run_inline(
        [f"--inline-snapshot={flag}"],
        changed_files=snapshot(
            {
                "test_something.py": """\
from inline_snapshot import snapshot
from mymodule import MyClass

import os # just another import

import mymodule

def test_a():
    assert snapshot(mymodule.MyClass("value")) == MyClass("value")
"""
            }
        ),
    ).run_inline()


def test_customized_value_mismatch_error():
    """Test that UsageError is raised when customized value doesn't match original."""

    Example(
        {
            "conftest.py": """\
from inline_snapshot.plugin import customize
from inline_snapshot.plugin import Builder

class InlineSnapshotPlugin:
    @customize
    def bad_handler(self, value, builder: Builder):
        if value == 42:
            # Return a CustomCode with wrong value - repr evaluates to 100 but original is 42
            return builder.create_code("100")
""",
            "test_something.py": """\
from inline_snapshot import snapshot

def test_a():
    assert snapshot() == 42
""",
        }
    ).run_inline(
        ["--inline-snapshot=create"],
        raises=snapshot(
            """\
UsageError:
Customized value does not match original value:

original_value=42

customized_value=100
customized_representation=CustomCode('100')
"""
        ),
    )


@pytest.mark.parametrize("original,flag", [("'wrong'", "fix"), ("", "create")])
def test_global_var_lookup(original, flag):
    """Test that create_code can look up global variables."""

    Example(
        {
            "conftest.py": """\
from inline_snapshot.plugin import customize
from inline_snapshot.plugin import Builder

class InlineSnapshotPlugin:
    @customize
    def use_global(self, value, builder: Builder):
        if value == "test_value":
            return builder.create_code("GLOBAL_VAR")
""",
            "test_something.py": f"""\
from inline_snapshot import snapshot

GLOBAL_VAR = "test_value"

def test_a():
    assert snapshot({original}) == "test_value"
""",
        }
    ).run_inline(
        [f"--inline-snapshot={flag}"],
        changed_files=snapshot(
            {
                "test_something.py": """\
from inline_snapshot import snapshot

GLOBAL_VAR = "test_value"

def test_a():
    assert snapshot(GLOBAL_VAR) == "test_value"
"""
            }
        ),
    )


@pytest.mark.parametrize("original,flag", [("'wrong'", "fix"), ("", "create")])
def test_file_handler(original, flag):
    """Test that __file__ handler creates correct code."""

    Example(
        {
            "test_something.py": f"""\
from inline_snapshot import snapshot

def test_a():
    assert snapshot({original}) == __file__
""",
        }
    ).run_inline(
        [f"--inline-snapshot={flag}"],
        changed_files=snapshot(
            {
                "test_something.py": """\
from inline_snapshot import snapshot

def test_a():
    assert snapshot(__file__) == __file__
"""
            }
        ),
    )


def test_datetime_types():
    """Test that datetime types generate correct snapshots with proper imports."""

    Example(
        {
            "test_something.py": """\
from datetime import datetime, date, time, timedelta
from inline_snapshot import snapshot

def test_datetime_types():
    assert snapshot() == datetime(2024, 1, 15, 10, 30, 45, 123456)
    assert snapshot() == date(2024, 1, 15)
    assert snapshot() == time(10, 30, 45, 123456)
    assert snapshot() == timedelta(days=1, hours=2, minutes=30)
    assert snapshot() == timedelta(seconds=5, microseconds=123456)
""",
        }
    ).run_inline(
        ["--inline-snapshot=create"],
        changed_files=snapshot(
            {
                "test_something.py": """\
from datetime import datetime, date, time, timedelta
from inline_snapshot import snapshot

def test_datetime_types():
    assert snapshot(datetime(2024, 1, 15, hour=10, minute=30, second=45, microsecond=123456)) == datetime(2024, 1, 15, 10, 30, 45, 123456)
    assert snapshot(date(2024, 1, 15)) == date(2024, 1, 15)
    assert snapshot(time(hour=10, minute=30, second=45, microsecond=123456)) == time(10, 30, 45, 123456)
    assert snapshot(timedelta(days=1, seconds=9000)) == timedelta(days=1, hours=2, minutes=30)
    assert snapshot(timedelta(seconds=5, microseconds=123456)) == timedelta(seconds=5, microseconds=123456)
"""
            }
        ),
    ).run_inline()


def test_custom_children():
    Example(
        {
            "c.py": """\
from dataclasses import dataclass

@dataclass
class C:
    i:int
""",
            "conftest.py": """\
from inline_snapshot.plugin import customize
from c import C

@customize
def handler(value,builder):
    if isinstance(value,C) and value.i==2:
        return builder.create_call(C,[],{"i":builder.create_code("1+1")})
             """,
            "test_example.py": """\
from inline_snapshot import snapshot
from c import C

def test():
    assert C(i=2) == snapshot()
""",
        }
    ).run_inline(
        ["--inline-snapshot=create"],
        changed_files=snapshot(
            {
                "test_example.py": """\
from inline_snapshot import snapshot
from c import C

def test():
    assert C(i=2) == snapshot(C(i=1 + 1))
"""
            }
        ),
    ).run_inline(
        ["--inline-snapshot=fix"]
    )