From c4296671dc10334380fc79f75677a259200ede39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=81=82=E3=81=A7?= Date: Fri, 10 Nov 2023 14:05:18 +0100 Subject: [PATCH] Emit warning on incorrect Objective name --- CHANGELOG.md | 1 + src/autometrics/objectives.py | 9 +++++++++ src/autometrics/test_objectives.py | 16 ++++++++++++++++ 3 files changed, 26 insertions(+) create mode 100644 src/autometrics/test_objectives.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f1e28d0..0d92a2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - [💥 Breaking change] `init` function is now required to be called before using autometrics (#89) - Prometheus exporters are now configured via `init` function (#89) +- `Objective`s will now emit a warning when name contains characters other than alphanumeric and dash (#98) ### Deprecated diff --git a/src/autometrics/objectives.py b/src/autometrics/objectives.py index 73e89ca..e494bdf 100644 --- a/src/autometrics/objectives.py +++ b/src/autometrics/objectives.py @@ -1,4 +1,7 @@ +import logging + from enum import Enum +from re import match from typing import Optional, Tuple @@ -89,3 +92,9 @@ def __init__( self.name = name self.success_rate = success_rate self.latency = latency + + # Check that name only contains alphanumeric characters and hyphens + if match(r"^[\w-]+$", name) is None: + logging.getLogger().warning( + f"Objective name '{name}' contains invalid characters. Only alphanumeric characters and hyphens are allowed." + ) diff --git a/src/autometrics/test_objectives.py b/src/autometrics/test_objectives.py new file mode 100644 index 0000000..1c8e073 --- /dev/null +++ b/src/autometrics/test_objectives.py @@ -0,0 +1,16 @@ +import logging + +from autometrics.objectives import Objective + + +def test_objective_name_warning(caplog): + """Test that a warning is logged when an objective name contains invalid characters.""" + caplog.set_level(logging.WARNING) + caplog.clear() + Objective("Incorrect name.") + assert len(caplog.records) == 1 + assert caplog.records[0].levelname == "WARNING" + assert "contains invalid characters" in caplog.records[0].message + caplog.clear() + Objective("correct-name-123") + assert len(caplog.records) == 0