|
1 | 1 | # tests/conftest.py |
2 | 2 | import os |
3 | 3 | import pytest |
| 4 | +import re |
4 | 5 | from vcr import VCR |
5 | 6 | from dotenv import load_dotenv |
6 | 7 |
|
|
10 | 11 | # Get test API key from environment variables |
11 | 12 | TEST_API_KEY = os.environ.get("MAILERSEND_API_KEY", "test-api-key") |
12 | 13 |
|
| 14 | + |
| 15 | +def sanitize_response_body(response): |
| 16 | + """Sanitize response body to remove sensitive data like accessToken.""" |
| 17 | + try: |
| 18 | + # Get the response body - handle different VCR formats |
| 19 | + body = None |
| 20 | + if response.get('body'): |
| 21 | + if isinstance(response['body'], dict): |
| 22 | + body = response['body'].get('string') |
| 23 | + else: |
| 24 | + body = response['body'] |
| 25 | + |
| 26 | + if not body: |
| 27 | + return response |
| 28 | + |
| 29 | + # Convert bytes to string if needed |
| 30 | + if isinstance(body, bytes): |
| 31 | + body = body.decode('utf-8') |
| 32 | + |
| 33 | + # Only process if it looks like JSON (contains accessToken) |
| 34 | + if 'accessToken' in body or 'mlsn.' in body: |
| 35 | + # Replace accessToken values |
| 36 | + body = re.sub( |
| 37 | + r'"accessToken":"mlsn\.[a-f0-9]+"', |
| 38 | + '"accessToken":"***FILTERED***"', |
| 39 | + body |
| 40 | + ) |
| 41 | + |
| 42 | + # Replace any other mlsn tokens |
| 43 | + body = re.sub( |
| 44 | + r'"mlsn\.[a-f0-9]{60,}"', |
| 45 | + '"***FILTERED***"', |
| 46 | + body |
| 47 | + ) |
| 48 | + |
| 49 | + # Replace preview tokens |
| 50 | + body = re.sub( |
| 51 | + r'"preview":"mlsn\.[a-f0-9]+"', |
| 52 | + '"preview":"***FILTERED***"', |
| 53 | + body |
| 54 | + ) |
| 55 | + |
| 56 | + # Update the response body (convert back to bytes for VCR) |
| 57 | + if isinstance(response['body'], dict): |
| 58 | + response['body']['string'] = body.encode('utf-8') |
| 59 | + else: |
| 60 | + response['body'] = body.encode('utf-8') |
| 61 | + |
| 62 | + except Exception as e: |
| 63 | + print(f"[VCR FILTER] Error sanitizing response: {e}") |
| 64 | + # Don't fail tests if filtering fails |
| 65 | + pass |
| 66 | + |
| 67 | + return response |
| 68 | + |
| 69 | + |
13 | 70 | # Configure VCR globally |
14 | 71 | vcr = VCR( |
15 | 72 | cassette_library_dir="tests/fixtures/cassettes", |
|
18 | 75 | filter_headers=["authorization"], |
19 | 76 | filter_post_data_parameters=["api_key", "token", "accessToken"], |
20 | 77 | serializer="yaml", |
| 78 | + before_record_response=sanitize_response_body, |
21 | 79 | ) |
22 | 80 |
|
23 | 81 | # Create a pytest fixture for the API key |
|
0 commit comments