Skip to content

Commit

Permalink
Add as_json to responses
Browse files Browse the repository at this point in the history
  • Loading branch information
PerchunPak committed Jul 23, 2024
1 parent ba5f10e commit a463a49
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
7 changes: 6 additions & 1 deletion mcstatus/responses.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass
from dataclasses import dataclass, asdict
from typing import Any, TYPE_CHECKING

from mcstatus.forge_data import ForgeData, RawForgeData
Expand Down Expand Up @@ -101,6 +101,11 @@ def build(cls, *args, **kwargs) -> Self:
"""
raise NotImplementedError("You can't use abstract methods.")

def as_json(self) -> dict:
as_dict = asdict(self)
as_dict["motd"] = self.motd.to_minecraft()
return as_dict


@dataclass(frozen=True)
class JavaStatusResponse(BaseStatusResponse):
Expand Down
10 changes: 10 additions & 0 deletions tests/responses/test_bedrock.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ def test_optional_parameters_is_none(self, field, pop_index):
build = BedrockStatusResponse.build(parameters, 123.0)
assert getattr(build, field) is None

def test_as_json(self, build: BedrockStatusResponse):
assert build.as_json() == {
"gamemode": "Default",
"latency": 123.0,
"map_name": "map name here",
"motd": "§r§4G§r§6a§r§ey§r§2B§r§1o§r§9w§r§ds§r§4e§r§6r",
"players": {"max": 69, "online": 1},
"version": {"brand": "MCPE", "name": "1.18.100500", "protocol": 422},
}


@BaseResponseTest.construct
class TestBedrockStatusPlayers(BaseResponseTest):
Expand Down
18 changes: 18 additions & 0 deletions tests/responses/test_java.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@ class TestJavaStatusResponse(BaseResponseTest):
def build(self) -> JavaStatusResponse:
return JavaStatusResponse.build(self.RAW) # type: ignore # dict[str, Unknown] cannot be assigned to TypedDict

def test_as_json(self, build: JavaStatusResponse):
assert build.as_json() == {
"enforces_secure_chat": True,
"forge_data": None,
"icon": "data:image/png;base64,foo",
"latency": 0,
"motd": "A Minecraft Server",
"players": {"max": 20, "online": 0, "sample": None},
"raw": {
"description": "A Minecraft Server",
"enforcesSecureChat": True,
"favicon": "data:image/png;base64,foo",
"players": {"max": 20, "online": 0},
"version": {"name": "1.8-pre1", "protocol": 44},
},
"version": {"name": "1.8-pre1", "protocol": 44},
}


@BaseResponseTest.construct
class TestJavaStatusPlayers(BaseResponseTest):
Expand Down

0 comments on commit a463a49

Please sign in to comment.