|
12 | 12 | VCR = vcr.VCR(cassette_library_dir="tests/sdk/data/")
|
13 | 13 |
|
14 | 14 |
|
| 15 | +class Cassette(vcr.cassette.Cassette): |
| 16 | + """Subclass `Cassette` to be able to handle two or more identical requests |
| 17 | + with different responses at different positions in the cassette. Thanks to |
| 18 | + @vickyliin for suggesting this workaround for kevin1024/vcrpy#753.""" |
| 19 | + |
| 20 | + def append_and_play(self, request, response) -> None: |
| 21 | + prev_len_data = len(self.data) |
| 22 | + super().append(request, response) |
| 23 | + is_appended = len(self.data) == prev_len_data + 1 |
| 24 | + if is_appended: |
| 25 | + self.play_counts[prev_len_data] += 1 |
| 26 | + |
| 27 | + def _load(self) -> None: |
| 28 | + super()._load() |
| 29 | + self.append = self.append_and_play |
| 30 | + self._load = None |
| 31 | + |
| 32 | + |
15 | 33 | class VCRAPI(API):
|
16 | 34 | """Subclass `API` so that `_send_json_request()` is instrumented to record
|
17 | 35 | and replay VCR.py cassettes.
|
@@ -52,7 +70,12 @@ def use_cassette(func):
|
52 | 70 | def wrapper(self, *args, **kwargs):
|
53 | 71 | # We have to specify an explicit path for each cassette because
|
54 | 72 | # we're not using vcr.use_cassette() directly as a decorator.
|
55 |
| - with VCR.use_cassette(f"{func.__name__}.yaml") as cassette: |
| 73 | + context = VCR.use_cassette(f"{func.__name__}.yaml") |
| 74 | + |
| 75 | + # Override `Cassette` to use our subclass before we enter the |
| 76 | + # context manager. |
| 77 | + context.cls = Cassette |
| 78 | + with context as cassette: |
56 | 79 | with patch.object(VCRAPI, "_cassette", cassette, create=True):
|
57 | 80 | return func(self, *args, **kwargs)
|
58 | 81 |
|
|
0 commit comments