Skip to content

Commit

Permalink
Check for duplicate keys in input data
Browse files Browse the repository at this point in the history
Raise an error if two rate items have the same name. E.g, this would
trigger an error:

```
- name: Test Rate
  history:
    - values: "1""
      from: 2023-06
      until: 2023-11
- name: Test Rate
  history:
    - values: "2""
      from: 2023-12
```
  • Loading branch information
larsks committed May 17, 2024
1 parent f59a129 commit 9182aec
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/nerc_rates/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,18 @@ def validate_no_overlap(cls, data: Self):
return data


def check_for_duplicates(items):
data = {}
for item in items:
if item["name"] in data:
raise ValueError(f"found duplicate name \"{item['name']}\" in list")
data[item["name"]] = item
return data


RateItemDict = Annotated[
dict[str, RateItem],
pydantic.BeforeValidator(lambda items: {x["name"]: x for x in items}),
pydantic.BeforeValidator(check_for_duplicates),
]


Expand Down
22 changes: 22 additions & 0 deletions src/nerc_rates/tests/test_rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,25 @@ def test_rates_get_value_at():
assert r.get_value_at("Test Rate", "2021-01") == "2"
with pytest.raises(ValueError):
assert r.get_value_at("Test Rate", "2019-01")


def test_fail_with_duplicate_names():
with pytest.raises(ValueError):
rates.Rates(
[
{
"name": "Test Rate",
"history": [
{"value": "1", "from": "2020-01", "until": "2020-12"},
{"value": "2", "from": "2021-01"},
],
},
{
"name": "Test Rate",
"history": [
{"value": "1", "from": "2020-01", "until": "2020-12"},
{"value": "2", "from": "2021-01"},
],
},
]
)

0 comments on commit 9182aec

Please sign in to comment.