Skip to main content

tests/test_key.py

1"""
2Tests for `funkycache.key`.
3"""
5from dataclasses import dataclass
6from pathlib import Path
7from typing import Any
9from pydantic import BaseModel
10import pytest
11from _pytest.mark.structures import ParameterSet
13from funkycache.key import encode_key_as_json
16class Shape(BaseModel):
17 """A basic model that uses Pydantic."""
19 sides: int
20 colour: str
23@dataclass
24class Greeting:
25 """A basic model that uses dataclasses."""
27 name: str
28 message: str
31KEY_ENCODING_TEST_CASES: list[ParameterSet] = [
32 pytest.param({"n": "one"}, '{"n":"one"}', id="str"),
33 pytest.param({"n": 1}, '{"n":1}', id="int"),
34 pytest.param(
35 {"n": ["one", "uno", "eins"]}, '{"n":["one","uno","eins"]}', id="list"
36 ),
37 pytest.param(
38 {"n": ("one", "uno", "eins")}, '{"n":["one","uno","eins"]}', id="tuple"
39 ),
40 pytest.param({"n": []}, '{"n":[]}', id="empty_list"),
41 pytest.param({"n": [{"en": "one"}]}, '{"n":[{"en":"one"}]}', id="list_1"),
42 pytest.param(
43 {
44 "n": [
45 {"lang": "en", "val": "one"},
46 {"lang": "fr", "val": "un"},
47 {"lang": "de", "val": "eins"},
48 ]
49 },
50 '{"n":{"_keys":["lang","val"],"_values":[["en","one"],["fr","un"],["de","eins"]]}}',
51 id="list_many",
52 ),
53 pytest.param(
54 {"n": Shape(sides=4, colour="red")},
55 '{"n":{"colour":"red","sides":4}}',
56 id="pydantic",
57 ),
58 pytest.param(
59 {"n": Greeting(name="alex", message="hello")},
60 '{"n":{"message":"hello","name":"alex"}}',
61 id="dataclass",
62 ),
63 pytest.param(
64 {"long": "a" * 5000, "short": "a"},
65 '{"long":"xxh64:b2b67943d4803cd6","short":"a"}',
66 id="long_str",
67 ),
68 pytest.param(
69 {"n": {"long": "a" * 5000, "short": "a"}},
70 '{"n":{"long":"xxh64:b2b67943d4803cd6","short":"a"}}',
71 id="long_str",
72 ),
73 pytest.param({"n": {Path("1"): "one"}}, '{"n":{"1":"one"}}', id="nested_path_key"),
77@pytest.mark.parametrize(
78 "key, json_key",
79 KEY_ENCODING_TEST_CASES,
81def test_encode_key_as_json(key: dict[str, Any], json_key: str) -> None:
82 """
83 Tests for encode_key_as_json.
84 """
85 assert encode_key_as_json(key) == json_key