-
Notifications
You must be signed in to change notification settings - Fork 13
/
testing.py
372 lines (344 loc) · 14.9 KB
/
testing.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import io
import json
import sys
import unittest
from collections import OrderedDict
from datetime import datetime, timezone
from unittest.mock import patch
import requests_mock
from colorama import Fore, deinit, init
import Accounting
from gui.gui import close_all_windows, init_gui
from tests.mocks import *
from tests.sampleItems import items
from utils import config, web
LOOKUP_URL = "https://www.pathofexile.com/api/trade/search/Standard"
EXCHANGE_URL = "https://www.pathofexile.com/api/trade/exchange/Standard"
class TestItemLookup(unittest.TestCase):
@patch("tkinter.Tk", TkMock)
@patch("tkinter.Toplevel", ToplevelMock)
@patch("tkinter.Frame", FrameMock)
@patch("tkinter.Label", LabelMock)
@patch("tkinter.Button", ButtonMock)
@patch("screeninfo.get_monitors", mock_get_monitors)
@patch("time.sleep", lambda s: s)
@patch("utils.config.USE_GUI", True)
@patch("os.name", "Mock")
def test_lookups(self):
# Required to do the gui creation step in tests. We need to
# create it here, after we patch our python modules.
init_gui()
config.LEAGUE = "Standard"
# Mockups of response data from pathofexile.com/trade
expected = [
# (mocked up json response, expected condition, search url)
(mockResponse(11), lambda v: "[$]" in v, LOOKUP_URL), # 0
(mockResponse(12), lambda v: "[$]" in v, LOOKUP_URL), # 1
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 2
(mockResponse(10), lambda v: "[$]" in v, LOOKUP_URL,), # 3
(
mockResponse(1),
lambda v: "INFO:root:[!] Not enough data to confidently price this item" # 4
in v,
LOOKUP_URL,
),
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 5
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 6
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 7
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 8
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 9
(mockResponse(66), lambda v: "[$]" in v, LOOKUP_URL), # 10
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 11
(mockResponse(0), lambda v: "INFO:root:" in v, LOOKUP_URL,), # 12
# 13 item in sampleItems is a divination card, which is looked
# up via exchange URL instead of search.
(
mockResponse(0),
lambda v: "INFO:root:" in v,
EXCHANGE_URL,
), # 13
(mockResponse(10), lambda v: "[$]" in v, LOOKUP_URL,), # 14
(mockResponse(10), lambda v: "[$]" in v, LOOKUP_URL), # 15
]
# Mocked up prices to return when searching. We only take the first
# 10 results from any search. We don't have to worry about sorting by
# price here, as we know that PoE/trade sorts by default.
prices = [
[(45, "Alch"),] * 10, # List 0
[ # List 1
# 5 x 1 chaos
*(((1, "Chaos"),) * 5),
# 1 x 3 chaos
(3, "Chaos"),
# 4 x 2 alch
*(((2, "Alch"),) * 4),
],
[], # List 2
[(1, "Chaos")] * 10, # List 3
[(666, "Exa")], # List 4
[], # List 5
[], # List 6
[], # List 7
[], # List 8
[], # List 9
[(2.5, "Mir")] * 10, # List 10
[], # List 11
[], # List 12
[], # List 13
[(25, "Chaos")] * 10, # List 14
[(1, "Fuse")] * 10, # List 15
]
for i in range(len(items)):
with self.subTest(i=i):
sortedPrices = sorted(prices[i])
priceCount = OrderedDict()
for price in sortedPrices:
if price in priceCount:
priceCount[price] += 1
else:
priceCount[price] = 1
# Middleman our stdout, so we can check programmatically
out = io.StringIO()
sys.stdout = out
# Mockup response
with requests_mock.Mocker() as mock:
mock.post(expected[i][2], json=expected[i][0])
with open("tests/mockModifiers.txt") as f:
mock.get(
"https://www.pathofexile.com/api/trade/data/stats",
json=json.load(f),
)
with open("tests/mockItems.txt") as f:
mock.get(
"https://www.pathofexile.com/api/trade/data/items",
json=json.load(f),
)
poePricesRes = {
"min": 57.760000000000005,
"max": 86.64,
"currency": "chaos",
"warning_msg": "",
"error": 0,
"pred_explanation": [
[
"(pseudo) (total) +# to maximum Life",
0.6233922907451513,
],
[
"(pseudo) # Elemental Resistances",
0.05952270963592211,
],
["+# Life gained on Kill", 0.00895634747376225],
[
"(pseudo) (total) +#% to Lightning Resistance",
0.003846337537816363,
],
[
"(pseudo) (total) +#% to Fire Resistance",
-0.013732066984023333,
],
["ES", -0.018150229290251393],
[
"(pseudo) (total) +#% to Cold Resistance",
-0.025894263910260087,
],
[
"(pseudo) +#% total Elemental Resistance",
-0.24650575442281308,
],
],
"pred_confidence_score": 85.2540600516464,
"error_msg": "",
}
mock.get(
makePoePricesURL(i), json=poePricesRes,
)
response = {
"result": [
{
"id": "result%d" % x,
"listing": {
# Mocked account name of the lister
"account": {"name": "account%d" % x},
# Price of this item result; we should mock
# and test against this amount.
"price": {
"type": "~",
"amount": sortedPrices[x][0],
"currency": sortedPrices[x][1],
},
# Indexed now.
"indexed": datetime.strftime(
datetime.now(timezone.utc),
"%Y-%m-%dT%H:%M:%SZ",
),
},
}
for x in range(min(expected[i][0]["total"], 10))
]
}
# If we have at least MIN_RESULTS items, we should mock
# the GET request for fetching the first 10 items.
# See search_item's pathing in parse.py
if len(expected[i][0]["result"]) >= 0:
fetch_url = makeFetchURL(
expected[i][0],
# True if the expected item's search url is EXCHANGE_URL
expected[i][2] == EXCHANGE_URL,
)
mock.get(fetch_url, json=response)
# Callout to API and price the item
with self.assertLogs(level="INFO") as logger:
Accounting.basic_search(items[i])
[output] = logger.output[-1:]
# Get the expected condition
currentExpected = expected[i][1]
# Expect that our truthy condition is true
self.assertTrue(currentExpected(output))
if len(expected[i][0]["result"]) >= config.MIN_RESULTS:
# Expect that the currency is output properly, including
# the color(s) expected.
priceList = []
for k, v in priceCount.items():
# Normalize any non-integer decimal number. That is,
# if k[0] == int(k[0]), output it as a pure integer.
# Otherwise, use the string formatter, so 2.750
# becomes 2.75 but retains it's floating pointness.
fmt = "%i" if int(k[0]) == k[0] else "%s"
priceList.append(
("%s" + fmt + " %s" + Fore.RESET + " x %d")
% (Fore.YELLOW, k[0], k[1], v)
)
expectedStr = "INFO:root:[$] Prices: " + (
", "
).join(priceList)
self.assertTrue(expectedStr in logger.output[-1:])
close_all_windows()
class TestBaseLookup(unittest.TestCase):
@patch("tkinter.Tk", TkMock)
@patch("tkinter.Toplevel", ToplevelMock)
@patch("tkinter.Frame", FrameMock)
@patch("tkinter.Label", LabelMock)
@patch("tkinter.Button", ButtonMock)
@patch("screeninfo.get_monitors", mock_get_monitors)
@patch("time.sleep", lambda s: s)
@patch("utils.config.USE_GUI", True)
@patch("os.name", "Mock")
def test_base_lookups(self):
# Required to do the gui creation step in tests. We need to
# create it here, after we patch our python modules.
init_gui()
config.LEAGUE = "Standard"
# Mock json data for poe.ninja bases
data = {
"lines": [
{
"baseType": "Boot Blade",
"levelRequired": 84,
"variant": None,
"corrupted": True,
"exaltedValue": 0.5,
"chaosValue": 80.0,
"itemType": "Dagger",
},
{
"baseType": "Boot Blade",
"levelRequired": 84,
"variant": "Elder",
"corrupted": True,
"exaltedValue": 0.5,
"chaosValue": 80.0,
"itemType": "Dagger",
},
{
"baseType": "Boot Blade",
"levelRequired": 84,
"variant": "Shaper",
"corrupted": True,
"exaltedValue": 0.5,
"chaosValue": 80.0,
"itemType": "Dagger",
},
{
"baseType": "Boot Blade",
"levelRequired": 84,
"variant": "Warlord",
"corrupted": True,
"exaltedValue": 0.5,
"chaosValue": 80.0,
"itemType": "Dagger",
},
{
"baseType": "Boot Blade",
"levelRequired": 84,
"variant": "Redeemer",
"corrupted": True,
"exaltedValue": 0.5,
"chaosValue": 80.0,
"itemType": "Dagger",
},
{
"baseType": "Boot Blade",
"levelRequired": 84,
"variant": "Crusader",
"corrupted": True,
"exaltedValue": 0.5,
"chaosValue": 80.0,
"itemType": "Dagger",
},
{
"baseType": "Boot Blade",
"levelRequired": 84,
"variant": "Hunter",
"corrupted": False,
"exaltedValue": 0.5,
"chaosValue": 80.0,
"itemType": "Dagger",
},
]
}
expected = [lambda v: "[$]" in v, lambda v: "[!]" in v]
with requests_mock.Mocker(real_http=True) as mock:
web.ninja_bases = []
mock.get(
"https://poe.ninja/api/data/itemoverview?league=Standard&type=BaseType&language=en",
json=data,
)
with open("tests/mockModifiers.txt") as f:
mock.get(
"https://www.pathofexile.com/api/trade/data/stats",
json=json.load(f),
)
with open("tests/mockItems.txt") as f:
mock.get(
"https://www.pathofexile.com/api/trade/data/items",
json=json.load(f),
)
for i in range(len(items[:2])):
item = items[i]
with self.assertLogs(level="INFO") as logger:
Accounting.search_ninja_base(item)
[output] = logger.output[-1:]
self.assertTrue(expected[i](output))
# We'll take the first sample item and modify it so that we
# can match against all types of influences we support.
item = items[0]
supportedInfluence = [
"Elder",
"Shaper",
"Warlord",
"Redeemer",
"Crusader",
"Hunter",
]
for inf in supportedInfluence:
current = item + ("\n--------\n%s Item\n" % inf)
with self.assertLogs(level="INFO") as logger:
Accounting.search_ninja_base(current)
[output] = logger.output[-1:]
self.assertTrue(expected[0](output))
close_all_windows()
if __name__ == "__main__":
init(autoreset=True) # Colorama
unittest.main(failfast=True)
deinit()