This repository was archived by the owner on Feb 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest_metods_for_commands.py
251 lines (200 loc) · 10.3 KB
/
test_metods_for_commands.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""Тесты для общих методов из файла /src/commands/commands_.py."""
from socket import timeout
from discord import Color
from discord.ext.test import message, get_embed
from mcstatus import MinecraftServer
from mcstatus.pinger import PingResponse
from pytest import fixture
from src.objects import ServerInfo
from src.commands.commands_ import MetodsForCommands
class TestMetodsForCommands:
"""Класс для тестов и фикстур."""
@fixture(scope="session")
def metods_for_commands(self, bot):
"""Фикстура сохраняющая экземпляр класса.
Args:
bot: Главный объект бота.
Returns:
Экземпляр класса `MetodsForCommands`.
"""
return MetodsForCommands(bot)
@fixture(scope="class")
async def wait_please(self):
"""Фикстура получающая ответ от тестовой команды wait_please.
Returns:
Embed объект ответа.
"""
await message("wait_please example.com")
return get_embed()
@fixture(scope="class")
async def fail_message_online(self):
"""Фикстура получающая ответ от тестовой команды fail_message.
Returns:
Embed объект ответа.
"""
await message("fail_message example.com 1")
return get_embed()
@fixture(scope="class")
async def fail_message_offline(self):
"""Фикстура получающая ответ от тестовой команды fail_message, но теперь если online=False.
Returns:
Embed объект ответа.
"""
await message("fail_message example.com 0")
return get_embed()
async def test_parse_ip_alias(self, database, metods_for_commands):
"""Тест на проверку алиаса в методе MetodsForCommands.parse_ip.
Args:
database: Объект дата базы.
metods_for_commands: Экземпляр класса `MetodsForCommands`.
"""
await database.pool.execute("INSERT INTO sunservers (ip, port, owner) VALUES ($1, 25565, 0);", "127.0.0.29")
await database.pool.execute(
"UPDATE sunservers SET alias = $2 " "WHERE ip = $1 AND port = 25565;", "127.0.0.29", "тест28"
)
dns_info = MinecraftServer("127.0.0.29")
answer = await metods_for_commands.parse_ip("тест28")
assert answer == ServerInfo(True, "тест28", dns_info, "127.0.0.29", "25565")
async def test_parse_ip_valid(self, metods_for_commands):
"""Тест на проверку действий при валидном айпи.
Args:
metods_for_commands: Экземпляр класса `MetodsForCommands`.
"""
dns_info = MinecraftServer("127.0.0.30")
answer = await metods_for_commands.parse_ip("127.0.0.30")
assert answer == ServerInfo(True, None, dns_info, "127.0.0.30", "25565")
async def test_parse_ip_not_valid(self, metods_for_commands):
"""Тест на проверку действий при не валидном айпи.
Args:
metods_for_commands: Экземпляр класса `MetodsForCommands`.
"""
dns_info = MinecraftServer("not_valid")
answer = await metods_for_commands.parse_ip("not_valid")
assert answer == ServerInfo(False, None, dns_info, None, "25565")
@staticmethod
def compare_ping_response_objects(obj1: PingResponse, obj2: PingResponse) -> bool:
"""Метод сравнивает объекты PingResponse.
Args:
obj1: Первый объект для сравнивания.
obj2: Второй объект для сравнивания.
Returns:
Результат сравнения.
"""
ret = [
obj1.raw == obj2.raw,
obj1.players.__dict__ == obj2.players.__dict__,
obj1.version.__dict__ == obj2.version.__dict__,
obj1.description == obj2.description,
obj1.favicon == obj2.favicon,
]
return False not in ret
async def test_ping_server_valid(self, metods_for_commands, monkeypatch_session):
"""Тест на проверку действий при валидном айпи в методе MetodsForCommands.ping_server.
Args:
metods_for_commands: Экземпляр класса `MetodsForCommands`.
monkeypatch_session: `monkeypatch` фикстура только с scope='session'.
"""
def fake_server_answer(class_self=None) -> PingResponse:
"""Эмулирует ответ сервера.
Args:
class_self: Иногда при вызове метода, так же приходит аргумент `self`.
Returns:
Фейковый ответ сервера.
"""
return PingResponse(
{
"description": {"text": "A Minecraft Server"},
"players": {"max": 20, "online": 5},
"version": {"name": "1.17.1", "protocol": 756},
}
)
monkeypatch_session.setattr(MinecraftServer, "status", fake_server_answer)
expected_dns_info = MinecraftServer.lookup("127.0.0.31")
status, info = await metods_for_commands.ping_server("127.0.0.31")
# __dict__ чтобы можно было сравнивать классы
# без этого при сравнении оно всегда выдает False
assert (
self.compare_ping_response_objects(status, fake_server_answer())
and info.dns.__dict__ == expected_dns_info.__dict__
and info.__dict__ == ServerInfo(True, None, info.dns, "127.0.0.31", "25565").__dict__
)
async def test_ping_server_not_valid(self, metods_for_commands):
"""Тест на проверку действий при не валидном айпи.
Args:
metods_for_commands: Экземпляр класса `MetodsForCommands`.
"""
dns_info = MinecraftServer("not_valid")
answer = await metods_for_commands.ping_server("not_valid")
assert answer == (False, ServerInfo(False, None, dns_info, None, "25565"))
async def test_ping_server_not_answer(self, metods_for_commands, monkeypatch_session):
"""Тест на проверку действий если сервер не ответил.
Args:
metods_for_commands: Экземпляр класса `MetodsForCommands`.
monkeypatch_session: `monkeypatch` фикстура только с scope='session'.
"""
def fake_server_answer(class_self=None):
"""Когда сервер выключен, модуль вызывает exception socket.timeout.
Args:
class_self: Иногда при вызове метода, так же приходит аргумент `self`.
Raises:
Фейковый ответ сервера (то есть негативный).
"""
raise timeout
monkeypatch_session.setattr(MinecraftServer, "status", fake_server_answer)
expected_dns_info = MinecraftServer.lookup("127.0.0.32")
status, info = await metods_for_commands.ping_server("127.0.0.32")
# __dict__ чтобы можно было сравнивать классы
# без этого при сравнении оно всегда выдает False
assert (
status is False
and info.dns.__dict__ == expected_dns_info.__dict__
and info.__dict__ == ServerInfo(True, None, info.dns, "127.0.0.32", "25565").__dict__
)
def test_wait_please_color(self, wait_please):
"""Тест на проверку цвета в сообщении wait_please.
Args:
wait_please: Embed объект ответа.
"""
assert str(wait_please.color) == str(Color.orange())
def test_wait_please_ip_in_title(self, wait_please):
"""Тест на проверку есть ли айпи в title.
Args:
wait_please: Embed объект ответа.
"""
assert "example.com" in wait_please.title
def test_fail_message_online_color(self, fail_message_online):
"""Тест на проверку цвета в сообщении fail_message (online).
Args:
fail_message_online: Embed объект ответа.
"""
assert str(fail_message_online.color) == str(Color.red())
def test_fail_message_online_ip_in_title(self, fail_message_online):
"""Тест на проверку есть ли айпи в title.
Args:
fail_message_online: Embed объект ответа.
"""
assert "example.com" in fail_message_online.title
def test_fail_message_online_status(self, fail_message_online):
"""Тест на проверку правильного статуса в описании Embed'а.
Args:
fail_message_online: Embed объект ответа.
"""
assert "Онлайн" in fail_message_online.description
def test_fail_message_offline_color(self, fail_message_offline):
"""Тест на проверку цвета в сообщении fail_message (offline).
Args:
fail_message_offline: Embed объект ответа.
"""
assert str(fail_message_offline.color) == str(Color.red())
def test_fail_message_offline_ip_in_title(self, fail_message_offline):
"""Тест на проверку есть ли айпи в title.
Args:
fail_message_offline: Embed объект ответа.
"""
assert "example.com" in fail_message_offline.title
def test_fail_message_offline_status(self, fail_message_offline):
"""Тест на проверку правильного статуса в описании Embed'а.
Args:
fail_message_offline: Embed объект ответа.
"""
assert "Офлайн" in fail_message_offline.description