Skip to content
This repository has been archived by the owner on Nov 19, 2023. It is now read-only.

Commit

Permalink
Merge pull request #301 from arttuperala/unique-dict
Browse files Browse the repository at this point in the history
Handle dicts in validate_unique_items
  • Loading branch information
sondrelg committed Jul 4, 2023
2 parents 41f10dc + 457384d commit 6a9a2c9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
8 changes: 5 additions & 3 deletions openapi_tester/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import base64
import json
import re
from typing import TYPE_CHECKING
from uuid import UUID
Expand Down Expand Up @@ -147,9 +148,10 @@ def validate_minimum(schema_section: dict[str, Any], data: int | float) -> str |

def validate_unique_items(schema_section: dict[str, Any], data: list[Any]) -> str | None:
unique_items = schema_section.get("uniqueItems")
if unique_items and len(set(data)) != len(data):
return VALIDATE_UNIQUE_ITEMS_ERROR.format(data=data)
# TODO: handle deep dictionary comparison - for lists of dicts
if unique_items:
comparison_data = (json.dumps(item, sort_keys=True) if isinstance(item, dict) else item for item in data)
if len(set(comparison_data)) != len(data):
return VALIDATE_UNIQUE_ITEMS_ERROR.format(data=data)
return None


Expand Down
22 changes: 21 additions & 1 deletion tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
VALIDATE_TYPE_ERROR,
)
from openapi_tester.exceptions import DocumentationError, OpenAPISchemaError
from openapi_tester.validators import VALIDATOR_MAP
from openapi_tester.validators import VALIDATOR_MAP, validate_unique_items
from tests import (
example_response_types,
example_schema_array,
Expand Down Expand Up @@ -324,3 +324,23 @@ def test_is_nullable_oneof():

with pytest.raises(DocumentationError):
tester.test_schema_section({"oneOf": [{"type": "object"}, {"type": "string"}]}, None)


def test_validate_unique_items_dict():
# Only unique objects.
result = validate_unique_items(
{"uniqueItems": True},
[{"id": 123, "type": "Potato"}, {"id": 234, "type": "Potato"}, {"type": "Tomato", "id": 123}],
)
assert result is None

# Repeated object (in reverse key order).
result = validate_unique_items(
{"uniqueItems": True},
[{"id": 123, "type": "Potato"}, {"id": 234, "type": "Potato"}, {"type": "Potato", "id": 123}],
)
assert (
result
== "The array [{'id': 123, 'type': 'Potato'}, {'id': 234, 'type': 'Potato'}, "
"{'type': 'Potato', 'id': 123}] must contain unique items only"
)

0 comments on commit 6a9a2c9

Please sign in to comment.