2023-02-14 21:50:51 +01:00
|
|
|
from khoj.utils import helpers
|
2021-08-22 00:32:23 +02:00
|
|
|
|
2023-02-17 17:04:26 +01:00
|
|
|
|
2021-08-22 00:32:23 +02:00
|
|
|
def test_get_from_null_dict():
|
|
|
|
# null handling
|
|
|
|
assert helpers.get_from_dict(dict()) == dict()
|
|
|
|
assert helpers.get_from_dict(dict(), None) == None
|
|
|
|
|
|
|
|
# key present in nested dictionary
|
|
|
|
# 1-level dictionary
|
2023-02-17 17:04:26 +01:00
|
|
|
assert helpers.get_from_dict({"a": 1, "b": 2}, "a") == 1
|
|
|
|
assert helpers.get_from_dict({"a": 1, "b": 2}, "c") == None
|
2021-08-22 00:32:23 +02:00
|
|
|
|
|
|
|
# 2-level dictionary
|
2023-02-17 17:04:26 +01:00
|
|
|
assert helpers.get_from_dict({"a": {"a_a": 1}, "b": 2}, "a") == {"a_a": 1}
|
|
|
|
assert helpers.get_from_dict({"a": {"a_a": 1}, "b": 2}, "a", "a_a") == 1
|
2021-08-22 00:32:23 +02:00
|
|
|
|
|
|
|
# key not present in nested dictionary
|
|
|
|
# 2-level_dictionary
|
2023-02-17 17:04:26 +01:00
|
|
|
assert helpers.get_from_dict({"a": {"a_a": 1}, "b": 2}, "b", "b_a") == None
|
2021-08-22 00:32:23 +02:00
|
|
|
|
|
|
|
|
|
|
|
def test_merge_dicts():
|
|
|
|
# basic merge of dicts with non-overlapping keys
|
2023-02-17 17:04:26 +01:00
|
|
|
assert helpers.merge_dicts(priority_dict={"a": 1}, default_dict={"b": 2}) == {"a": 1, "b": 2}
|
2021-08-22 00:32:23 +02:00
|
|
|
|
|
|
|
# use default dict items when not present in priority dict
|
2023-02-17 17:04:26 +01:00
|
|
|
assert helpers.merge_dicts(priority_dict={}, default_dict={"b": 2}) == {"b": 2}
|
2021-08-22 00:32:23 +02:00
|
|
|
|
|
|
|
# do not override existing key in priority_dict with default dict
|
2023-02-17 17:04:26 +01:00
|
|
|
assert helpers.merge_dicts(priority_dict={"a": 1}, default_dict={"a": 2}) == {"a": 1}
|
2022-09-04 15:31:46 +02:00
|
|
|
|
|
|
|
|
|
|
|
def test_lru_cache():
|
|
|
|
# Test initializing cache
|
2023-02-17 17:04:26 +01:00
|
|
|
cache = helpers.LRU({"a": 1, "b": 2}, capacity=2)
|
|
|
|
assert cache == {"a": 1, "b": 2}
|
2022-09-04 15:31:46 +02:00
|
|
|
|
|
|
|
# Test capacity overflow
|
2023-02-17 17:04:26 +01:00
|
|
|
cache["c"] = 3
|
|
|
|
assert cache == {"b": 2, "c": 3}
|
2022-09-04 15:31:46 +02:00
|
|
|
|
|
|
|
# Test delete least recently used item from LRU cache on capacity overflow
|
2023-02-17 17:04:26 +01:00
|
|
|
cache["b"] # accessing 'b' makes it the most recently used item
|
|
|
|
cache["d"] = 4 # so 'c' is deleted from the cache instead of 'b'
|
|
|
|
assert cache == {"b": 2, "d": 4}
|