DeebotUniverse / client.py

Deebot client library in python
https://deebot.readthedocs.io
GNU General Public License v3.0
27 stars 41 forks source link

Add sweep_type to WaterInfo event #511

Closed Ulfmerbold2000 closed 3 months ago

Ulfmerbold2000 commented 3 months ago

Summary by CodeRabbit

coderabbitai[bot] commented 3 months ago

Walkthrough

The recent changes enhance the deebot_client library by introducing new parameters and improving error handling. Specifically, the InitParam class now includes an optional flag, and the create_from_mqtt method in CommandMqttP2P class has refined exception handling. Additionally, the WaterInfoEvent and SetWaterInfo classes now support a new sweepType parameter, and corresponding test cases have been updated to ensure proper functionality.

Changes

File Path Change Summary
deebot_client/command.py Added optional field to InitParam and updated exception handling in CommandMqttP2P.create_from_mqtt.
deebot_client/commands/json/water_info.py Added sweepType parameter to WaterInfoEvent and SetWaterInfo classes.
deebot_client/events/__init__.py Imported SweepType from water_info.
deebot_client/events/water_info.py Added sweepType field to WaterInfoEvent and defined SweepType enum.
tests/commands/json/test_water_info.py Added test cases for sweepType and updated existing tests for SetWaterInfo.

Poem

In the land of code, where robots sweep,
New parameters now run deep.
With sweeping types and water's flow,
Our tests ensure the best we know.
Bugs beware, for now we see,
Deebots dance in harmony!
🐰✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)
Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `Generate unit testing code for this file.` - `Open a follow-up GitHub issue for this discussion.` - Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples: - `@coderabbitai generate unit testing code for this file.` - `@coderabbitai modularize this function.` - PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples: - `@coderabbitai generate interesting stats about this repository and render them as a table.` - `@coderabbitai show all the console.log statements in this repository.` - `@coderabbitai read src/utils.ts and generate unit testing code.` - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.` - `@coderabbitai help me debug CodeRabbit configuration file.` Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. ### CodeRabbit Commands (invoked as PR comments) - `@coderabbitai pause` to pause the reviews on a PR. - `@coderabbitai resume` to resume the paused reviews. - `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository. - `@coderabbitai full review` to do a full review from scratch and review all the files again. - `@coderabbitai summary` to regenerate the summary of the PR. - `@coderabbitai resolve` resolve all the CodeRabbit review comments. - `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository. - `@coderabbitai help` to get help. Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed. ### CodeRabbit Configration File (`.coderabbit.yaml`) - You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository. - Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information. - If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json` ### Documentation and Community - Visit our [Documentation](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.
Ulfmerbold2000 commented 3 months ago

Since that bot wanted me to rename that sweepType Variable, please verify the correct usage in the command file!

I'm a bit unsure what is the variable sweep_type and what is the payload sweepType...sorry for that

Ulfmerbold2000 commented 3 months ago

Please verify my editing in the test_water_info...i've used the variable sweep_type as i interpreted the usage as the variable name instead the payload sweepType

I personally would prefer to have that variable name change in the eventfile "water_info" reverted to the payloadname (but dont know how without a new commit-which would the bot surely note again :( ), since that variable amount for example has the payload amount, which would make the things a lot easier for me in this case...

edenhaus commented 3 months ago

I personally would prefer to have that variable name change in the eventfile "water_info" reverted to the payloadname (but dont know how without a new commit-which would the bot surely note again :( ), since that variable amount for example has the payload amount, which would make the things a lot easier for me in this case...

No, this library follows the Python naming convention and if they data name and python name is not matching as in this case, than we use the python naming convention until we send the data. So the bot suggestion was correct.

Ulfmerbold2000 commented 3 months ago

Could need a bit help with that separation...that sweeptype var makes me nuts

Where is my fault?

Before it will goto nil, an idea:

Is it better to separate the event section in events/water_info? This way for example? Add an own Event for SweepType:

@dataclass(frozen=True)
class SweepTypeEvent(Event):
    """SweepType info event representation."""

    sweep_type: SweepType | None = None

And with following changes in commands/json/water_info?

    event_bus.notify(
        WaterInfoEvent(WaterAmount(int(data["amount"])), mop_attached=mop_attached),
        SweepTypeEvent(SweepType(int(data["sweepType"]))) )

Is it possible to have two events with only one command and payload from bot? Separating that SweepType from that Waterinfoevent would make it clearer...but since that payload comes from one message i have no real clue if this would work... Especially with the point that not always a payload with SweepType is send, as you stated?

All in all i would say it has to be in water_info since it comes over the same message and the same command to set the values. But can fire one message two events in the way it is scripted?

edenhaus commented 3 months ago

It is possible to separate but we don't need it for this type. You need only to check if the sweepType is in the returned response

edenhaus commented 3 months ago

pre-commit.ci autofix

Ulfmerbold2000 commented 3 months ago

Deleted

Ulfmerbold2000 commented 3 months ago

I've hunted many errors, but now i'm stuck with:

What is wrong with test_SetWaterInfo_Wateramount? Why is sweepType noted there???

And whats wrong with test_SetWaterInfo_SweepType? I've tried that args with Variablename sweep_type and Payloadname sweepType, both wrong...

=================================== FAILURES ===================================
_______________________ test_SetWaterInfo_Wateramount[2] _______________________

name = 'sweepType', type_ = <enum 'SweepType'>, data = {}

    def _pop_or_raise(name: str, type_: type, data: dict[str, Any]) -> Any:
        try:
>           value = data.pop(name)
E           KeyError: 'sweepType'

deebot_client/command.py:296: KeyError

The above exception was the direct cause of the following exception:

watervalue = <WaterAmount.MEDIUM: 2>

    @pytest.mark.parametrize(("watervalue"), [WaterAmount.MEDIUM])
    async def test_SetWaterInfo_Wateramount(watervalue: WaterAmount | str) -> None:
        command = SetWaterInfo(watervalue)
        args = {"amount": 2}
>       await assert_set_command(command, args, WaterInfoEvent(WaterAmount.MEDIUM))

tests/commands/json/test_water_info.py:48: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
tests/commands/json/__init__.py:80: in assert_set_command
    mqtt_command = command.create_from_mqtt(args)
deebot_client/command.py:286: in create_from_mqtt
    values[param.name or name] = _pop_or_raise(name, param.type_, data)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

name = 'sweepType', type_ = <enum 'SweepType'>, data = {}

    def _pop_or_raise(name: str, type_: type, data: dict[str, Any]) -> Any:
        try:
            value = data.pop(name)
        except KeyError as err:
            msg = f'"{name}" is missing in {data}'
>           raise DeebotError(msg) from err
E           deebot_client.exceptions.DeebotError: "sweepType" is missing in {}

deebot_client/command.py:299: DeebotError
------------------------------ Captured log call -------------------------------
WARNING  deebot_client.commands.json.common:common.py:75 Command "setWaterInfo" was not successfully. body={'code': 500, 'msg': 'fail'}
________________________ test_SetWaterInfo_SweepType[1] ________________________

sweepvalue = <SweepType.STANDARD: 1>

    @pytest.mark.parametrize(("sweepvalue"), [SweepType.STANDARD])
    async def test_SetWaterInfo_SweepType(sweepvalue: SweepType | str) -> None:
        command = SetWaterInfo(sweepvalue)
        args = {"sweepType": 1}
>       await assert_set_command(command, args, WaterInfoEvent(SweepType.STANDARD))

tests/commands/json/test_water_info.py:55: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
tests/commands/json/__init__.py:62: in assert_set_command
    await assert_execute_command(command, args)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

command = <deebot_client.commands.json.water_info.SetWaterInfo object at 0x7fe7ca20ff20>
args = {'sweepType': 1}

    async def assert_execute_command(
        command: ExecuteCommand, args: dict[str, Any] | list[Any] | None
    ) -> None:
        assert command.name != "invalid"
>       assert command._args == args
E       AssertionError

tests/commands/json/__init__.py:34: AssertionError
Ulfmerbold2000 commented 3 months ago

HELP :/ every change make it worse

Ulfmerbold2000 commented 3 months ago

Question, are the "commands" for Example: class SetWaterInfo(JsonSetCommand): Virtual commands or will they be send to the bot?

As my point of understanding they are all virtual and only the set operation into the payload variables is an bot command. Would'nt be better to separate the whole operation from WaterInfo?

Eventually like this way:

class GetSweepTypeInfo(JsonGetCommand):
    """Get sweeptype info command."""

    name = "getSweepTypeInfo"

    @classmethod
    def _handle_body_data_dict(
        cls, event_bus: EventBus, data: dict[str, Any]
    ) -> HandlingResult:
        """Handle message->body->data and notify the correct event subscribers.

        :return: A message response
        """

        event_bus.notify(
            SweepTypeEvent(SweepType(int(data["sweepType"])))
        )
        return HandlingResult.success()

class SetSweepTypeInfo(JsonSetCommand):
    """Set sweeptype info command."""

    name = "setSweepTypeInfo"
    get_command = GetSweepTypeInfo
    _mqtt_params = MappingProxyType(
        {
            "sweepType": InitParam(SweepType),
        }
    )

    def __init__(self, sweepType: SweepType | str) -> None:
        if isinstance(sweep_type, str):
            sweep_type = get_enum(SweepType, sweep_type)
        super().__init__({"sweepType": sweep_type.value})

As i've seen the tests always fail, especially test_SetWaterInfoWateramount and the system notes the name = 'sweepType', type = <enum 'SweepType'>, data = {} as failure, but i cant figure out WHY exactly the sweepType is asked for in this special test...

_______________________ test_SetWaterInfo_Wateramount[2] _______________________

name = 'sweepType', type_ = <enum 'SweepType'>, data = {}

    def _pop_or_raise(name: str, type_: type, data: dict[str, Any]) -> Any:
        try:
>           value = data.pop(name)
E           KeyError: 'sweepType'

deebot_client/command.py:296: KeyError

The above exception was the direct cause of the following exception:

watervalue = <WaterAmount.MEDIUM: 2>

    @pytest.mark.parametrize(("watervalue"), [WaterAmount.MEDIUM, "medium"])
    async def test_SetWaterInfo_Wateramount(watervalue: WaterAmount | str) -> None:
        command = SetWaterInfo(watervalue)
        args = {"amount": 2}
>       await assert_set_command(command, args, WaterInfoEvent(WaterAmount.MEDIUM))

In the parameters "sweepType" is not there...so where comes that asking for?

edenhaus commented 3 months ago

The AI bot is only here to help, but no all suggestions are correct. Will give it a deeper look in the next days

codecov[bot] commented 3 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 85.80%. Comparing base (0beebab) to head (6412166). Report is 4 commits behind head on dev.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## dev #511 +/- ## ========================================== + Coverage 85.60% 85.80% +0.20% ========================================== Files 86 87 +1 Lines 3238 3284 +46 Branches 528 537 +9 ========================================== + Hits 2772 2818 +46 Misses 414 414 Partials 52 52 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.