Skip to content

Commit

Permalink
Filtering out HTTP headers and hiding API keys
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw authored Nov 24, 2024
1 parent 86d9531 commit 5ab8c0d
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions pytest/pytest-recording-vcr.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,41 @@ def test_create():
```

The first time you run the tests, use the `--record-mode=once` option:

pytest -k test_create --record-mode=once

```bash
python -m pytest -k test_create --record-mode=once
```
This defaults to creating a YAML file in `tests/cassettes/test_s3_credentials/test_create.yaml`.

Subsequent runs of `pytest -k test_create` will reuse those recorded HTTP requests and will not make any network requests - I confirmed this by turning off my laptop's WiFi.

## Filtering out HTTP headers and hiding API keys

For my tests that use API key services like the OpenAI API I've settled on this pattern:

```python
import os
import pytest

API_KEY = os.environ.get("PYTEST_OPENAI_API_KEY") or "fake-key"


@pytest.fixture(scope="module")
def vcr_config():
return {"filter_headers": ["authorization"]}
```

The `vcr_config()` there ensures that any `authorization` HTTP headers in the resulting cassette YAML files are redacted, so they don't accidentally get checked in to a public GitHub repo.

I use that `PYTEST_OPENAI_API_KEY` environment variable in tests like this:

```
@pytest.mark.vcr
def test_ask(monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", API_KEY)
# ...
```
Then for the duration of that test the `OPENAI_API_KEY` environment key will either be `fake-key` for test runs against previously recorded cassette or the value of `PYTEST_OPENAI_API_KEY` - which means I can update the cassettes like this:

```bash
PYTEST_OPENAI_API_KEY=your-key python -m pytest --record-mode once
```

0 comments on commit 5ab8c0d

Please sign in to comment.