|
| 1 | +import os |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +import vcr |
| 5 | + |
| 6 | +vcr_cassette_path = os.path.join(os.path.dirname(__file__), "vcr_cassettes") |
| 7 | + |
| 8 | + |
| 9 | +def remove_set_cookie_header(response: dict[str, Any]): |
| 10 | + """ |
| 11 | + Removes the Set-Cookie header from a VCR.py response object to improve cassette consistency. |
| 12 | +
|
| 13 | + This function can be used as a before_record callback in your VCR configuration |
| 14 | + to ensure that Set-Cookie headers are stripped from responses before they are |
| 15 | + recorded to cassettes. |
| 16 | +
|
| 17 | + Args: |
| 18 | + response (vcr.request.Response): The VCR.py response object to modify |
| 19 | +
|
| 20 | + Returns: |
| 21 | + vcr.request.Response: The modified response object with Set-Cookie headers removed |
| 22 | +
|
| 23 | + Example: |
| 24 | + import vcr |
| 25 | +
|
| 26 | + # Configure VCR with the callback |
| 27 | + vcr = vcr.VCR( |
| 28 | + before_record_response=remove_set_cookie_header, |
| 29 | + match_on=['uri', 'method'] |
| 30 | + ) |
| 31 | +
|
| 32 | + with vcr.use_cassette('tests/fixtures/my_cassette.yaml'): |
| 33 | + # Make your HTTP requests here |
| 34 | + pass |
| 35 | + """ |
| 36 | + |
| 37 | + # Get the headers from the response |
| 38 | + headers = response["headers"] |
| 39 | + |
| 40 | + # Headers to remove (case-insensitive) |
| 41 | + headers_to_remove = ["set-cookie", "Set-Cookie"] |
| 42 | + |
| 43 | + # Remove Set-Cookie headers if they exist |
| 44 | + for header in headers_to_remove: |
| 45 | + if header in headers: |
| 46 | + del headers[header] |
| 47 | + |
| 48 | + return response |
| 49 | + |
| 50 | + |
| 51 | +http_recorder = vcr.VCR( |
| 52 | + cassette_library_dir=vcr_cassette_path, |
| 53 | + record_mode="once", |
| 54 | + filter_headers=["authorization", "cookie"], |
| 55 | + before_record_response=remove_set_cookie_header, |
| 56 | +) |
0 commit comments