Skip to content

Commit 10686b0

Browse files
committed
improv: add fixtures to aid tests #161
Signed-off-by: heitorlessa <[email protected]>
1 parent 7980860 commit 10686b0

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

docs/content/core/metrics.mdx

+28-2
Original file line numberDiff line numberDiff line change
@@ -251,11 +251,37 @@ This has the advantage of keeping cold start metric separate from your applicati
251251

252252
## Testing your code
253253

254+
### Environment variables
255+
254256
Use `POWERTOOLS_METRICS_NAMESPACE` and `POWERTOOLS_SERVICE_NAME` env vars when unit testing your code to ensure metric namespace and dimension objects are created, and your code doesn't fail validation.
255257

256258
```bash:title=pytest_metric_namespace.sh
257-
258259
POWERTOOLS_SERVICE_NAME="Example" POWERTOOLS_METRICS_NAMESPACE="Application" python -m pytest
259260
```
260261

261-
You can ignore this if you are explicitly setting namespace/default dimension by passing the `namespace` and `service` parameters when initializing Metrics: `metrics = Metrics(namespace=ApplicationName, service=ServiceName)`.
262+
If you prefer setting environment variable for specific tests, and are using Pytest, you can use [monkeypatch](https://docs.pytest.org/en/latest/monkeypatch.html) fixture:
263+
264+
```python:title=pytest_env_var.py
265+
def test_namespace_env_var(monkeypatch):
266+
# Set POWERTOOLS_METRICS_NAMESPACE before initializating Metrics
267+
monkeypatch.setenv("POWERTOOLS_METRICS_NAMESPACE", namespace)
268+
269+
metrics = Metrics()
270+
...
271+
```
272+
273+
> Ignore this, if you are explicitly setting namespace/default dimension via `namespace` and `service` parameters: `metrics = Metrics(namespace=ApplicationName, service=ServiceName)`
274+
275+
### Clearing metrics
276+
277+
`Metrics` keep metrics in memory across multiple instances. If you need to test this behaviour, you can use the following Pytest fixture to ensure metrics are reset incl. cold start:
278+
279+
```python:title=pytest_metrics_reset_fixture.py
280+
@pytest.fixture(scope="function", autouse=True)
281+
def reset_metric_set():
282+
# Clear out every metric data prior to every test
283+
metrics = Metrics()
284+
metrics.clear_metrics()
285+
metrics_global.is_cold_start = True # ensure each test has cold start
286+
yield
287+
```

0 commit comments

Comments
 (0)