Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions cql2.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ class Expr:
>>> expr.validate()
"""

def matches(self, item: dict[str, Any]) -> bool:
"""Matches this expression against an item.

Args:
item (dict[str, Any]): The item to match against

Returns:
bool: True if the expression matches the item, False otherwise
"""

def to_json(self) -> dict[str, Any]:
"""Converts this cql2 expression to a cql2-json dictionary.

Expand Down
1 change: 1 addition & 0 deletions python/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ cql2 = { path = ".." }
cql2-cli = { path = "../cli" }
pyo3 = { version = "0.23.3", features = ["extension-module"] }
pythonize = "0.23.0"
serde_json = "1.0.138"
7 changes: 7 additions & 0 deletions python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use pyo3::{
create_exception,
exceptions::{PyException, PyIOError, PyValueError},
prelude::*,
types::PyDict,
};
use serde_json::Value;
use std::path::PathBuf;

create_exception!(cql2, ValidationError, PyException);
Expand Down Expand Up @@ -74,6 +76,11 @@ impl Expr {
}
}

fn matches(&self, item: Bound<'_, PyDict>) -> Result<bool> {
let value: Value = pythonize::depythonize(&item)?;
self.0.clone().matches(Some(&value)).map_err(Error::from)
}

fn to_json<'py>(&self, py: Python<'py>) -> Result<Bound<'py, PyAny>> {
pythonize::pythonize(py, &self.0).map_err(Error::from)
}
Expand Down
64 changes: 53 additions & 11 deletions python/tests/test_expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import cql2
import pytest
from cql2 import Expr, ParseError, ValidationError


def test_parse_file(fixtures: Path) -> None:
Expand All @@ -16,52 +15,95 @@ def test_parse_file_str(fixtures: Path) -> None:


def test_init(example01_text: str) -> None:
Expr(example01_text)
cql2.Expr(example01_text)


def test_parse_json(example01_text: str, example01_json: dict[str, Any]) -> None:
cql2.parse_json(json.dumps(example01_json))
with pytest.raises(ParseError):
with pytest.raises(cql2.ParseError):
cql2.parse_json(example01_text)


def test_parse_text(example01_text: str, example01_json: dict[str, Any]) -> None:
cql2.parse_text(example01_text)
with pytest.raises(ParseError):
with pytest.raises(cql2.ParseError):
cql2.parse_text(json.dumps(example01_json))


def test_to_json(example01_text: str) -> None:
Expr(example01_text).to_json() == {
cql2.Expr(example01_text).to_json() == {
"op": "=",
"args": [{"property": "landsat:scene_id"}, "LC82030282019133LGN00"],
}


def test_to_text(example01_json: dict[str, Any]) -> None:
Expr(example01_json).to_text() == "landsat:scene_id = 'LC82030282019133LGN00'"
cql2.Expr(example01_json).to_text() == "landsat:scene_id = 'LC82030282019133LGN00'"


def test_to_sql(example01_text: str) -> None:
sql_query = Expr(example01_text).to_sql()
sql_query = cql2.Expr(example01_text).to_sql()
assert sql_query.query == '("landsat:scene_id" = $1)'
assert sql_query.params == ["LC82030282019133LGN00"]


def test_validate() -> None:
expr = Expr(
expr = cql2.Expr(
{
"op": "t_before",
"args": [{"property": "updated_at"}, {"timestamp": "invalid-timestamp"}],
}
)
with pytest.raises(ValidationError):
with pytest.raises(cql2.ValidationError):
expr.validate()


def test_add() -> None:
assert Expr("True") + Expr("false") == Expr("true AND false")
assert cql2.Expr("True") + cql2.Expr("false") == cql2.Expr("true AND false")


def test_eq() -> None:
assert Expr("True") == Expr("true")
assert cql2.Expr("True") == cql2.Expr("true")


@pytest.mark.parametrize(
"expr, item, should_match",
[
pytest.param(
"boolfield and 1 + 2 = 3",
{
"properties": {
"eo:cloud_cover": 10,
"datetime": "2020-01-01 00:00:00Z",
"boolfield": True,
}
},
True,
id="pass on bool & cql2 arithmetic",
),
pytest.param(
"eo:cloud_cover <= 9",
{
"properties": {
"eo:cloud_cover": 10,
"datetime": "2020-01-01 00:00:00Z",
},
},
False,
id="fail on property value comparison",
),
pytest.param(
"eo:cloud_cover <= 9",
{
"properties": {
"eo:cloud_cover": 8,
"datetime": "2020-01-01 00:00:00Z",
},
},
True,
id="pass on property value comparison",
),
],
)
def test_matches(expr, item, should_match) -> None:
assert cql2.Expr(expr).matches(item) == should_match
3 changes: 3 additions & 0 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,9 @@ impl Expr {
///
/// let mut expr: Expr = "boolfield and 1 + 2 = 3".parse().unwrap();
/// assert_eq!(true, expr.matches(Some(&item)).unwrap());
///
/// let mut expr: Expr = "eo:cloud_cover <= 9".parse().unwrap();
/// assert_eq!(false, expr.matches(Some(&item)).unwrap());
/// ```
pub fn matches(self, j: Option<&Value>) -> Result<bool, Error> {
let reduced = self.reduce(j)?;
Expand Down