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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ jobs:
--net=host \
--platform linux/${{ matrix.arch }} \
localhost/nox-cross-arch:latest \
bash -c "pip install -e .[dev-noxfile]; nox --install-only -e ${{ matrix.nox-session }}; pip freeze; nox -e ${{ matrix.nox-session }}"
bash -c "pip install -e .[dev-noxfile]; nox --install-only -e ${{ matrix.nox-session }}; pip freeze; nox -R -e ${{ matrix.nox-session }}"
timeout-minutes: 30

# This ensures that the runner has access to the pip cache.
Expand Down
2 changes: 1 addition & 1 deletion RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

## New Features

<!-- Here goes the main new features and examples or instructions on how to use them -->
- A new module `frequenz.client.dispatch.test` has been added, providing a fake Service and Client as well as a `DispatchGenerator` to generate `Dispatch` instances filled with random data.

## Bug Fixes

Expand Down
6 changes: 2 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ dependencies = [
# Use direct commit until release
"frequenz-api-dispatch @ git+https://github.com/frequenz-floss/frequenz-api-dispatch.git@223315c",
# "frequenz-api-dispatch >= 0.13.0, < 0.14",
# Directly use unreleased commit until the next release
"frequenz-client-base @ git+https://github.com/frequenz-floss/frequenz-client-base-python.git@57d3093",
# "frequenz-client-base >= 0.1.0, < 0.2",
"frequenz-client-base >= 0.2.1, < 0.3.0",
# Directly use unreleased commit until the first release
"frequenz-client-common @ git+https://github.com/frequenz-floss/frequenz-client-common-python.git@5e6e7b7",
# "frequenz-client-common == 0.1.0",
Expand Down Expand Up @@ -82,7 +80,7 @@ dev-pylint = [
"frequenz-api-dispatch @ git+https://github.com/frequenz-floss/frequenz-api-dispatch.git@223315c",
]
dev-pytest = [
"pytest == 8.1.0",
"pytest == 8.0.2",
"frequenz-repo-config[extra-lint-examples] == 0.9.1",
"pytest-mock == 3.12.0",
"pytest-asyncio == 0.23.5",
Expand Down
4 changes: 4 additions & 0 deletions src/frequenz/client/dispatch/test/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# License: MIT
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH

"""Helpful utilities for testing with the dispatch client."""
244 changes: 244 additions & 0 deletions src/frequenz/client/dispatch/test/_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
# License: MIT
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH

"""Mock classes for the dispatch api.

Useful for testing.
"""

import dataclasses
from dataclasses import dataclass
from datetime import datetime, timezone

import grpc
import grpc.aio

# pylint: disable=no-name-in-module
from frequenz.api.dispatch.v1.dispatch_pb2 import Dispatch as PBDispatch
from frequenz.api.dispatch.v1.dispatch_pb2 import (
DispatchCreateRequest as PBDispatchCreateRequest,
)
from frequenz.api.dispatch.v1.dispatch_pb2 import (
DispatchDeleteRequest,
DispatchGetRequest,
DispatchList,
)
from frequenz.api.dispatch.v1.dispatch_pb2 import (
DispatchListRequest as PBDispatchListRequest,
)
from frequenz.api.dispatch.v1.dispatch_pb2 import DispatchUpdateRequest
from google.protobuf.empty_pb2 import Empty

from frequenz.client.base.conversion import to_datetime as _to_dt

# pylint: enable=no-name-in-module
from frequenz.client.dispatch._internal_types import DispatchCreateRequest
from frequenz.client.dispatch.types import Dispatch


@dataclass
class FakeService:
"""Dispatch mock service for testing."""

dispatches: list[Dispatch] = dataclasses.field(default_factory=list)
"""List of dispatches."""

_last_id: int = 0
"""Last used dispatch id."""

# pylint: disable=invalid-name
async def ListMicrogridDispatches(
self, request: PBDispatchListRequest
) -> DispatchList:
"""List microgrid dispatches.

Args:
request: The request.

Returns:
The dispatch list.
"""
return DispatchList(
dispatches=map(
lambda d: d.to_protobuf(),
filter(
lambda d: self._filter_dispatch(d, request),
self.dispatches,
),
)
)

# pylint: disable=too-many-branches
@staticmethod
def _filter_dispatch(dispatch: Dispatch, request: PBDispatchListRequest) -> bool:
"""Filter a dispatch based on the request."""
if dispatch.microgrid_id != request.microgrid_id:
return False

if request.HasField("filter"):
_filter = request.filter
for selector in _filter.selectors:
if selector != dispatch.selector:
return False
if _filter.HasField("time_interval"):
if start_from := _filter.time_interval.start_from:
if dispatch.start_time < _to_dt(start_from):
return False
if start_to := _filter.time_interval.start_to:
if dispatch.start_time >= _to_dt(start_to):
return False
if end_from := _filter.time_interval.end_from:
if dispatch.start_time + dispatch.duration < _to_dt(end_from):
return False
if end_to := _filter.time_interval.end_to:
if dispatch.start_time + dispatch.duration >= _to_dt(end_to):
return False
if _filter.HasField("is_active"):
if dispatch.active != _filter.is_active:
return False
if _filter.HasField("is_dry_run"):
if dispatch.dry_run != _filter.is_dry_run:
return False

return True

async def CreateMicrogridDispatch(
self,
request: PBDispatchCreateRequest,
) -> Empty:
"""Create a new dispatch."""
self._last_id += 1

self.dispatches.append(
_dispatch_from_request(
DispatchCreateRequest.from_protobuf(request),
self._last_id,
create_time=datetime.now(tz=timezone.utc),
update_time=datetime.now(tz=timezone.utc),
)
)
return Empty()

async def UpdateMicrogridDispatch(
self,
request: DispatchUpdateRequest,
) -> Empty:
"""Update a dispatch."""
dispatch = next((d for d in self.dispatches if d.id == request.id), None)

if dispatch is None:
return Empty()

pb_dispatch = dispatch.to_protobuf()

# Go through the paths in the update mask and update the dispatch
for path in request.update_mask.paths:
split_path = path.split(".")

match split_path[0]:
# Fields that can be assigned directly
case "is_active" | "is_dry_run" | "duration":
setattr(
pb_dispatch,
split_path[0],
getattr(request.update, split_path[0]),
)
# Fields that need to be copied
case "start_time" | "selector" | "payload":
getattr(pb_dispatch, split_path[0]).CopyFrom(
getattr(request.update, split_path[0])
)
case "recurrence":
match split_path[1]:
case "end_criteria":
pb_dispatch.recurrence.end_criteria.CopyFrom(
request.update.recurrence.end_criteria
)
case "freq" | "interval":
setattr(
pb_dispatch.recurrence,
split_path[1],
getattr(request.update.recurrence, split_path[1]),
)
# Fields of type list that need to be copied
case (
"byminutes"
| "byhours"
| "byweekdays"
| "bymonthdays"
| "bymonths"
):
getattr(pb_dispatch.recurrence, split_path[1])[:] = getattr(
request.update.recurrence, split_path[1]
)[:]

dispatch = Dispatch.from_protobuf(pb_dispatch)
dispatch.update_time = datetime.now(tz=timezone.utc)

return Empty()

async def GetMicrogridDispatch(
self,
request: DispatchGetRequest,
) -> PBDispatch:
"""Get a single dispatch."""
dispatch = next((d for d in self.dispatches if d.id == request.id), None)

if dispatch is None:
error = grpc.RpcError()
# pylint: disable=protected-access
error._code = grpc.StatusCode.NOT_FOUND # type: ignore
error._details = "Dispatch not found" # type: ignore
# pylint: enable=protected-access
raise error

return dispatch.to_protobuf()

async def DeleteMicrogridDispatch(
self,
request: DispatchDeleteRequest,
) -> Empty:
"""Delete a given dispatch."""
num_dispatches = len(self.dispatches)
self.dispatches = [d for d in self.dispatches if d.id != request.id]

if len(self.dispatches) == num_dispatches:
error = grpc.RpcError()
# pylint: disable=protected-access
error._code = grpc.StatusCode.NOT_FOUND # type: ignore
error._details = "Dispatch not found" # type: ignore
# pylint: enable=protected-access
raise error

return Empty()

# pylint: enable=invalid-name


def _dispatch_from_request(
_request: DispatchCreateRequest,
_id: int,
create_time: datetime,
update_time: datetime,
) -> Dispatch:
"""Initialize a Dispatch object from a request.

Args:
_request: The dispatch create request.
_id: The unique identifier for the dispatch.
create_time: The creation time of the dispatch in UTC.
update_time: The last update time of the dispatch in UTC.

Returns:
The initialized dispatch.
"""
params = _request.__dict__
params["active"] = params.pop("is_active")
params["dry_run"] = params.pop("is_dry_run")

return Dispatch(
id=_id,
create_time=create_time,
update_time=update_time,
**params,
)
73 changes: 73 additions & 0 deletions src/frequenz/client/dispatch/test/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# License: MIT
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH

"""Fake client for testing."""

from typing import Any, cast

import grpc.aio

from frequenz.client.dispatch import Client
from frequenz.client.dispatch.test._service import FakeService
from frequenz.client.dispatch.types import Dispatch


class FakeClient(Client):
"""Fake client for testing.

This client uses a fake service to simulate the dispatch api.
"""

def __init__(self) -> None:
"""Initialize the mock client."""
super().__init__(grpc.aio.insecure_channel("mock"), "mock")
self._stub = FakeService() # type: ignore

@property
def dispatches(self) -> list[Dispatch]:
"""List of dispatches.

Returns:
list[Dispatch]: The list of dispatches
"""
return self._service.dispatches

@dispatches.setter
def dispatches(self, value: list[Dispatch]) -> None:
"""Set the list of dispatches.

Args:
value: The list of dispatches to set.
"""
self._service.dispatches = value

@property
def _service(self) -> FakeService:
"""The fake service.

Returns:
FakeService: The fake service.
"""
return cast(FakeService, self._stub)


def to_create_params(dispatch: Dispatch) -> dict[str, Any]:
"""Convert a dispatch to client.create parameters.

Args:
dispatch: The dispatch to convert.

Returns:
dict[str, Any]: The create parameters.
"""
return {
"microgrid_id": dispatch.microgrid_id,
"_type": dispatch.type,
"start_time": dispatch.start_time,
"duration": dispatch.duration,
"selector": dispatch.selector,
"active": dispatch.active,
"dry_run": dispatch.dry_run,
"payload": dispatch.payload,
"recurrence": dispatch.recurrence,
}
Loading