Skip to content

Commit

Permalink
improve convenience space filter merge logic (#1989)
Browse files Browse the repository at this point in the history
  • Loading branch information
haakonvt authored Oct 22, 2024
1 parent a412717 commit 5ee9b3d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion cognite/client/_api/data_modeling/instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -1605,7 +1605,9 @@ def _merge_space_into_filter(
space_filter = filters.SpaceFilter(space, instance_type)
if filter is None:
return space_filter
return filters.And(space_filter, Filter.load(filter) if isinstance(filter, dict) else filter)
filter = Filter.load(filter) if isinstance(filter, dict) else filter
# 'And' the space filter with the user filter (will merge if user filter is 'And')
return space_filter & filter

@staticmethod
def _to_instance_type_str(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from _pytest.mark import ParameterSet

import cognite.client.data_classes.filters as f
from cognite.client._api.data_modeling.instances import InstancesAPI
from cognite.client.data_classes._base import EnumProperty
from cognite.client.data_classes.data_modeling import ViewId
from cognite.client.data_classes.data_modeling.data_types import DirectRelationReference
Expand Down Expand Up @@ -301,6 +302,33 @@ def test_user_given_metadata_keys_are_not_camel_cased(property_cls: type) -> Non
assert dumped["value"] == "value_foo Bar_baz"


@pytest.mark.parametrize("space", (None, "s1", ["s1", "s2"]))
@pytest.mark.parametrize("user_filter", (None, f.Exists("x1"), f.And(f.Exists("x1"), f.Exists("x2"))))
@pytest.mark.parametrize("pass_as_dict", (True, False))
def test_merge_space_into_filter(
space: str | list[str] | None, user_filter: f.Filter | None, pass_as_dict: bool
) -> None:
flt_used = user_filter.dump() if pass_as_dict and user_filter else user_filter
res = InstancesAPI._merge_space_into_filter(
instance_type="node",
space=space,
filter=flt_used,
)
if space is user_filter is None:
assert res is None
elif space is None:
assert res == flt_used
elif user_filter is None:
assert isinstance(res, f.SpaceFilter)
else:
assert isinstance(res, f.And)
f1, *fs = res._filters
assert isinstance(f1, f.SpaceFilter)
# Ensure that the user filter if passed as an And-filter, is merged, rather than nested:
for flt in fs:
assert isinstance(flt, f.Exists)


class TestSpaceFilter:
@pytest.mark.parametrize(
"inst_type, space, expected",
Expand Down

0 comments on commit 5ee9b3d

Please sign in to comment.