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
21 changes: 16 additions & 5 deletions src/tagreader/web_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,8 @@ def generate_search_query(
raise ValueError("Data source is required argument")

# Aspen Web API expects single space instead of consecutive spaces.
tag = " ".join(tag.split())
if tag:
tag = " ".join(tag.split())
params = {"datasource": datasource, "tag": tag, "max": max, "getTrendable": 0}
return params

Expand Down Expand Up @@ -374,14 +375,14 @@ def generate_read_query(
}.get(read_type, -1)

if read_type == ReaderType.SNAPSHOT:
end_snap = 0
if end is not None:
use_current = 0
end = int(end.timestamp()) * 1000
end_snap = int(end.timestamp()) * 1000
else:
use_current = 1
end = 0

query = f'<Q f="d" allQuotes="1" rt="{end}" uc="{use_current}">'
query = f'<Q f="d" allQuotes="1" rt="{end_snap}" uc="{use_current}">'
else:
query = '<Q f="d" allQuotes="1">'

Expand Down Expand Up @@ -656,6 +657,10 @@ def read_tag(
# so we need to limit the range. Note -1 because INT normally includes
# both start and end time.
if read_type == ReaderType.INT:
if start is None or end is None or sample_time is None:
raise ValueError(
"Interpolated reads require start, end, and sample_time."
)
end = min(end, start + sample_time * (self.max_rows - 1))

tag_name, map_name = self.split_tagmap(tag)
Expand Down Expand Up @@ -885,6 +890,8 @@ def generate_read_query(

seconds = 0
if read_type != ReaderType.SNAPSHOT:
if sample_time is None:
raise ValueError("Sample time must be provided for non-snapshot reads.")
seconds = int(sample_time.total_seconds())

get_action = {
Expand All @@ -897,6 +904,10 @@ def generate_read_query(
params: Dict[str, Union[str, int]] = {}

if read_type != ReaderType.SNAPSHOT:
if end is None:
raise ValueError("End time must be provided for non-snapshot reads.")
if start is None:
raise ValueError("Start time must be provided for non-snapshot reads.")
params["startTime"] = self._time_to_UTC_string(start)
params["endTime"] = self._time_to_UTC_string(end)
params["timeZone"] = "UTC"
Expand Down Expand Up @@ -1153,7 +1164,7 @@ def read_tag(
# all the other summaries stamp start of interval by shifting all timestamps
# one interval down.
if read_type == ReaderType.MAX and df.index[0] > start:
df.index = df.index - sample_time
df.index = pd.DatetimeIndex(df.index) - sample_time

if get_status:
df["Status"] = (
Expand Down
45 changes: 43 additions & 2 deletions tests/test_AspenHandlerREST.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import timedelta
from datetime import datetime, timedelta
from inspect import signature
from typing import Generator, Optional
from typing import Any, Generator, List, Optional

import pytest

Expand Down Expand Up @@ -88,6 +88,47 @@ def test_read_tag_rejects_empty_tag_name(
assert str(error.value) == (f"Input tag: {tag} returns no tag_name. Invalid input.")


@pytest.mark.parametrize("missing", ["start", "end", "sample_time"]) # type: ignore[misc]
def test_interpolated_read_requires_time_inputs(
aspen_handler: AspenHandlerWeb, missing: str
) -> None:
start = utils.ensure_datetime_with_tz("2020-06-24 17:00:00")
with pytest.raises(ValueError, match="require start, end, and sample_time"):
aspen_handler.read_tag(
tag="ATCAI",
start=None if missing == "start" else start,
end=None if missing == "end" else start + SAMPLE_TIME,
sample_time=None if missing == "sample_time" else SAMPLE_TIME,
read_type=ReaderType.INT,
metadata={},
)


@pytest.mark.parametrize("intervals", [2, 5]) # type: ignore[misc]
def test_interpolated_read_limits_end(
aspen_handler: AspenHandlerWeb, monkeypatch: pytest.MonkeyPatch, intervals: int
) -> None:
start = utils.ensure_datetime_with_tz("2020-06-24 17:00:00")
requested_ends: List[datetime] = []
aspen_handler.max_rows = 4

def fake_generate_read_query(**kwargs: Any) -> str:
requested_ends.append(kwargs["end"])
return ""

monkeypatch.setattr(aspen_handler, "generate_read_query", fake_generate_read_query)
monkeypatch.setattr(aspen_handler, "fetch", lambda *args, **kwargs: {})
aspen_handler.read_tag(
tag="ATCAI",
start=start,
end=start + intervals * SAMPLE_TIME,
sample_time=SAMPLE_TIME,
read_type=ReaderType.INT,
metadata={},
)
assert requested_ends == [start + min(intervals, 3) * SAMPLE_TIME]


def test_split_tagmap() -> None:
assert AspenHandlerWeb.split_tagmap("ATCAI") == ("ATCAI", None)
assert AspenHandlerWeb.split_tagmap("ATCAI;IP_ANALOGMAP") == (
Expand Down
35 changes: 34 additions & 1 deletion tests/test_PIHandlerREST.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import timedelta
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Generator, List, Optional, Union

import pandas as pd
import pytest
import requests

Expand Down Expand Up @@ -194,6 +195,38 @@ def test_is_summary(pi_handler: PIHandlerWeb) -> None:
assert not pi_handler._is_summary(ReaderType.SNAPSHOT)


@pytest.mark.parametrize( # type: ignore[misc]
("read_type", "timestamp", "expected"),
[
(ReaderType.MAX, "2020-04-01T11:06:00Z", "2020-04-01T11:05:00Z"),
(ReaderType.MAX, "2020-04-01T11:05:00Z", "2020-04-01T11:05:00Z"),
(ReaderType.AVG, "2020-04-01T11:06:00Z", "2020-04-01T11:06:00Z"),
],
)
def test_summary_timestamp_alignment(
pi_handler: PIHandlerWeb,
monkeypatch: pytest.MonkeyPatch,
read_type: ReaderType,
timestamp: str,
expected: str,
) -> None:
data = {"Items": [{"Value": {"Timestamp": timestamp, "Value": 42.0}}]}
monkeypatch.setattr(pi_handler, "fetch", lambda *args, **kwargs: data)
start = datetime(2020, 4, 1, 11, 5, tzinfo=timezone.utc)

result = pi_handler.read_tag(
tag="alreadyknowntag",
start=start,
end=start + timedelta(minutes=2),
sample_time=timedelta(minutes=1),
read_type=read_type,
metadata=None,
)

assert result.index.equals(pd.DatetimeIndex([expected], name="time"))
assert result["alreadyknowntag"].tolist() == [42.0]


@pytest.mark.parametrize( # type: ignore[misc]
"read_type",
[
Expand Down
Loading