]>
Commit | Line | Data |
---|---|---|
c682bdf4 IB |
1 | from .helper import * |
2 | import requests | |
3 | import datetime | |
4 | import threading | |
5 | import market, portfolio, store | |
6 | ||
3080f31d | 7 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
c682bdf4 IB |
8 | class NoopLockTest(unittest.TestCase): |
9 | def test_with(self): | |
10 | noop_lock = store.NoopLock() | |
11 | with noop_lock: | |
12 | self.assertTrue(True) | |
13 | ||
3080f31d | 14 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
c682bdf4 IB |
15 | class LockedVarTest(unittest.TestCase): |
16 | ||
17 | def test_values(self): | |
18 | locked_var = store.LockedVar("Foo") | |
19 | self.assertIsInstance(locked_var.lock, store.NoopLock) | |
20 | self.assertEqual("Foo", locked_var.val) | |
21 | ||
22 | def test_get(self): | |
23 | with self.subTest(desc="Normal case"): | |
24 | locked_var = store.LockedVar("Foo") | |
25 | self.assertEqual("Foo", locked_var.get()) | |
26 | with self.subTest(desc="Dict"): | |
27 | locked_var = store.LockedVar({"foo": "bar"}) | |
28 | self.assertEqual({"foo": "bar"}, locked_var.get()) | |
29 | self.assertEqual("bar", locked_var.get("foo")) | |
30 | self.assertIsNone(locked_var.get("other")) | |
31 | ||
32 | def test_set(self): | |
33 | locked_var = store.LockedVar("Foo") | |
34 | locked_var.set("Bar") | |
35 | self.assertEqual("Bar", locked_var.get()) | |
36 | ||
37 | def test__getattr(self): | |
38 | dummy = type('Dummy', (object,), {})() | |
39 | dummy.attribute = "Hey" | |
40 | ||
41 | locked_var = store.LockedVar(dummy) | |
42 | self.assertEqual("Hey", locked_var.attribute) | |
43 | with self.assertRaises(AttributeError): | |
44 | locked_var.other | |
45 | ||
46 | def test_start_lock(self): | |
47 | locked_var = store.LockedVar("Foo") | |
48 | locked_var.start_lock() | |
49 | self.assertEqual("lock", locked_var.lock.__class__.__name__) | |
50 | ||
51 | thread1 = threading.Thread(target=locked_var.set, args=["Bar1"]) | |
52 | thread2 = threading.Thread(target=locked_var.set, args=["Bar2"]) | |
53 | thread3 = threading.Thread(target=locked_var.set, args=["Bar3"]) | |
54 | ||
55 | with locked_var.lock: | |
56 | thread1.start() | |
57 | thread2.start() | |
58 | thread3.start() | |
59 | ||
60 | self.assertEqual("Foo", locked_var.val) | |
61 | thread1.join() | |
62 | thread2.join() | |
63 | thread3.join() | |
64 | self.assertEqual("Bar", locked_var.get()[0:3]) | |
65 | ||
3080f31d | 66 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
c682bdf4 IB |
67 | class TradeStoreTest(WebMockTestCase): |
68 | def test_compute_trades(self): | |
69 | self.m.balances.currencies.return_value = ["XMR", "DASH", "XVG", "BTC", "ETH"] | |
70 | ||
71 | values_in_base = { | |
72 | "XMR": portfolio.Amount("BTC", D("0.9")), | |
73 | "DASH": portfolio.Amount("BTC", D("0.4")), | |
74 | "XVG": portfolio.Amount("BTC", D("-0.5")), | |
75 | "BTC": portfolio.Amount("BTC", D("0.5")), | |
76 | } | |
77 | new_repartition = { | |
78 | "DASH": portfolio.Amount("BTC", D("0.5")), | |
79 | "XVG": portfolio.Amount("BTC", D("0.1")), | |
80 | "BTC": portfolio.Amount("BTC", D("0.4")), | |
81 | "ETH": portfolio.Amount("BTC", D("0.3")), | |
82 | } | |
83 | side_effect = [ | |
84 | (True, 1), | |
85 | (False, 2), | |
86 | (False, 3), | |
87 | (True, 4), | |
88 | (True, 5) | |
89 | ] | |
90 | ||
91 | with mock.patch.object(market.TradeStore, "trade_if_matching") as trade_if_matching: | |
92 | trade_store = market.TradeStore(self.m) | |
93 | trade_if_matching.side_effect = side_effect | |
94 | ||
95 | trade_store.compute_trades(values_in_base, | |
96 | new_repartition, only="only") | |
97 | ||
98 | self.assertEqual(5, trade_if_matching.call_count) | |
99 | self.assertEqual(3, len(trade_store.all)) | |
100 | self.assertEqual([1, 4, 5], trade_store.all) | |
101 | self.m.report.log_trades.assert_called_with(side_effect, "only") | |
102 | ||
103 | def test_trade_if_matching(self): | |
104 | ||
105 | with self.subTest(only="nope"): | |
106 | trade_store = market.TradeStore(self.m) | |
107 | result = trade_store.trade_if_matching( | |
108 | portfolio.Amount("BTC", D("0")), | |
109 | portfolio.Amount("BTC", D("0.3")), | |
110 | "ETH", only="nope") | |
111 | self.assertEqual(False, result[0]) | |
112 | self.assertIsInstance(result[1], portfolio.Trade) | |
113 | ||
114 | with self.subTest(only=None): | |
115 | trade_store = market.TradeStore(self.m) | |
116 | result = trade_store.trade_if_matching( | |
117 | portfolio.Amount("BTC", D("0")), | |
118 | portfolio.Amount("BTC", D("0.3")), | |
119 | "ETH", only=None) | |
120 | self.assertEqual(True, result[0]) | |
121 | ||
122 | with self.subTest(only="acquire"): | |
123 | trade_store = market.TradeStore(self.m) | |
124 | result = trade_store.trade_if_matching( | |
125 | portfolio.Amount("BTC", D("0")), | |
126 | portfolio.Amount("BTC", D("0.3")), | |
127 | "ETH", only="acquire") | |
128 | self.assertEqual(True, result[0]) | |
129 | ||
130 | with self.subTest(only="dispose"): | |
131 | trade_store = market.TradeStore(self.m) | |
132 | result = trade_store.trade_if_matching( | |
133 | portfolio.Amount("BTC", D("0")), | |
134 | portfolio.Amount("BTC", D("0.3")), | |
135 | "ETH", only="dispose") | |
136 | self.assertEqual(False, result[0]) | |
137 | ||
138 | def test_prepare_orders(self): | |
139 | trade_store = market.TradeStore(self.m) | |
140 | ||
141 | trade_mock1 = mock.Mock() | |
142 | trade_mock2 = mock.Mock() | |
143 | trade_mock3 = mock.Mock() | |
144 | ||
145 | trade_mock1.prepare_order.return_value = 1 | |
146 | trade_mock2.prepare_order.return_value = 2 | |
147 | trade_mock3.prepare_order.return_value = 3 | |
148 | ||
149 | trade_mock1.pending = True | |
150 | trade_mock2.pending = True | |
151 | trade_mock3.pending = False | |
152 | ||
153 | trade_store.all.append(trade_mock1) | |
154 | trade_store.all.append(trade_mock2) | |
155 | trade_store.all.append(trade_mock3) | |
156 | ||
157 | trade_store.prepare_orders() | |
158 | trade_mock1.prepare_order.assert_called_with(compute_value="default") | |
159 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | |
160 | trade_mock3.prepare_order.assert_not_called() | |
161 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "default") | |
162 | ||
163 | self.m.report.log_orders.reset_mock() | |
164 | ||
165 | trade_store.prepare_orders(compute_value="bla") | |
166 | trade_mock1.prepare_order.assert_called_with(compute_value="bla") | |
167 | trade_mock2.prepare_order.assert_called_with(compute_value="bla") | |
168 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "bla") | |
169 | ||
170 | trade_mock1.prepare_order.reset_mock() | |
171 | trade_mock2.prepare_order.reset_mock() | |
172 | self.m.report.log_orders.reset_mock() | |
173 | ||
174 | trade_mock1.action = "foo" | |
175 | trade_mock2.action = "bar" | |
176 | trade_store.prepare_orders(only="bar") | |
177 | trade_mock1.prepare_order.assert_not_called() | |
178 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | |
179 | self.m.report.log_orders.assert_called_once_with([2], "bar", "default") | |
180 | ||
181 | def test_print_all_with_order(self): | |
182 | trade_mock1 = mock.Mock() | |
183 | trade_mock2 = mock.Mock() | |
184 | trade_mock3 = mock.Mock() | |
185 | trade_store = market.TradeStore(self.m) | |
186 | trade_store.all = [trade_mock1, trade_mock2, trade_mock3] | |
187 | ||
188 | trade_store.print_all_with_order() | |
189 | ||
190 | trade_mock1.print_with_order.assert_called() | |
191 | trade_mock2.print_with_order.assert_called() | |
192 | trade_mock3.print_with_order.assert_called() | |
193 | ||
194 | def test_run_orders(self): | |
195 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | |
196 | order_mock1 = mock.Mock() | |
197 | order_mock2 = mock.Mock() | |
198 | order_mock3 = mock.Mock() | |
199 | trade_store = market.TradeStore(self.m) | |
200 | ||
201 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | |
202 | ||
203 | trade_store.run_orders() | |
204 | ||
205 | all_orders.assert_called_with(state="pending") | |
206 | ||
207 | order_mock1.run.assert_called() | |
208 | order_mock2.run.assert_called() | |
209 | order_mock3.run.assert_called() | |
210 | ||
211 | self.m.report.log_stage.assert_called_with("run_orders") | |
212 | self.m.report.log_orders.assert_called_with([order_mock1, order_mock2, | |
213 | order_mock3]) | |
214 | ||
215 | def test_all_orders(self): | |
216 | trade_mock1 = mock.Mock() | |
217 | trade_mock2 = mock.Mock() | |
218 | ||
219 | order_mock1 = mock.Mock() | |
220 | order_mock2 = mock.Mock() | |
221 | order_mock3 = mock.Mock() | |
222 | ||
223 | trade_mock1.orders = [order_mock1, order_mock2] | |
224 | trade_mock2.orders = [order_mock3] | |
225 | ||
226 | order_mock1.status = "pending" | |
227 | order_mock2.status = "open" | |
228 | order_mock3.status = "open" | |
229 | ||
230 | trade_store = market.TradeStore(self.m) | |
231 | trade_store.all.append(trade_mock1) | |
232 | trade_store.all.append(trade_mock2) | |
233 | ||
234 | orders = trade_store.all_orders() | |
235 | self.assertEqual(3, len(orders)) | |
236 | ||
237 | open_orders = trade_store.all_orders(state="open") | |
238 | self.assertEqual(2, len(open_orders)) | |
239 | self.assertEqual([order_mock2, order_mock3], open_orders) | |
240 | ||
241 | def test_update_all_orders_status(self): | |
242 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | |
243 | order_mock1 = mock.Mock() | |
244 | order_mock2 = mock.Mock() | |
245 | order_mock3 = mock.Mock() | |
246 | ||
247 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | |
248 | ||
249 | trade_store = market.TradeStore(self.m) | |
250 | ||
251 | trade_store.update_all_orders_status() | |
252 | all_orders.assert_called_with(state="open") | |
253 | ||
254 | order_mock1.get_status.assert_called() | |
255 | order_mock2.get_status.assert_called() | |
256 | order_mock3.get_status.assert_called() | |
257 | ||
258 | def test_close_trades(self): | |
259 | trade_mock1 = mock.Mock() | |
260 | trade_mock2 = mock.Mock() | |
261 | trade_mock3 = mock.Mock() | |
262 | ||
263 | trade_store = market.TradeStore(self.m) | |
264 | ||
265 | trade_store.all.append(trade_mock1) | |
266 | trade_store.all.append(trade_mock2) | |
267 | trade_store.all.append(trade_mock3) | |
268 | ||
269 | trade_store.close_trades() | |
270 | ||
271 | trade_mock1.close.assert_called_once_with() | |
272 | trade_mock2.close.assert_called_once_with() | |
273 | trade_mock3.close.assert_called_once_with() | |
274 | ||
275 | def test_pending(self): | |
276 | trade_mock1 = mock.Mock() | |
277 | trade_mock1.pending = True | |
278 | trade_mock2 = mock.Mock() | |
279 | trade_mock2.pending = True | |
280 | trade_mock3 = mock.Mock() | |
281 | trade_mock3.pending = False | |
282 | ||
283 | trade_store = market.TradeStore(self.m) | |
284 | ||
285 | trade_store.all.append(trade_mock1) | |
286 | trade_store.all.append(trade_mock2) | |
287 | trade_store.all.append(trade_mock3) | |
288 | ||
289 | self.assertEqual([trade_mock1, trade_mock2], trade_store.pending) | |
290 | ||
3080f31d | 291 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
c682bdf4 IB |
292 | class BalanceStoreTest(WebMockTestCase): |
293 | def setUp(self): | |
294 | super().setUp() | |
295 | ||
296 | self.fetch_balance = { | |
297 | "ETC": { | |
298 | "exchange_free": 0, | |
299 | "exchange_used": 0, | |
300 | "exchange_total": 0, | |
301 | "margin_total": 0, | |
302 | }, | |
303 | "USDT": { | |
304 | "exchange_free": D("6.0"), | |
305 | "exchange_used": D("1.2"), | |
306 | "exchange_total": D("7.2"), | |
307 | "margin_total": 0, | |
308 | }, | |
309 | "XVG": { | |
310 | "exchange_free": 16, | |
311 | "exchange_used": 0, | |
312 | "exchange_total": 16, | |
313 | "margin_total": 0, | |
314 | }, | |
315 | "XMR": { | |
316 | "exchange_free": 0, | |
317 | "exchange_used": 0, | |
318 | "exchange_total": 0, | |
319 | "margin_total": D("-1.0"), | |
320 | "margin_free": 0, | |
321 | }, | |
322 | } | |
323 | ||
324 | def test_in_currency(self): | |
325 | self.m.get_ticker.return_value = { | |
326 | "bid": D("0.09"), | |
327 | "ask": D("0.11"), | |
328 | "average": D("0.1"), | |
329 | } | |
330 | ||
331 | balance_store = market.BalanceStore(self.m) | |
332 | balance_store.all = { | |
333 | "BTC": portfolio.Balance("BTC", { | |
334 | "total": "0.65", | |
335 | "exchange_total":"0.65", | |
336 | "exchange_free": "0.35", | |
337 | "exchange_used": "0.30"}), | |
338 | "ETH": portfolio.Balance("ETH", { | |
339 | "total": 3, | |
340 | "exchange_total": 3, | |
341 | "exchange_free": 3, | |
342 | "exchange_used": 0}), | |
343 | } | |
344 | ||
345 | amounts = balance_store.in_currency("BTC") | |
346 | self.assertEqual("BTC", amounts["ETH"].currency) | |
347 | self.assertEqual(D("0.65"), amounts["BTC"].value) | |
348 | self.assertEqual(D("0.30"), amounts["ETH"].value) | |
349 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | |
350 | "average", "total") | |
351 | self.m.report.log_tickers.reset_mock() | |
352 | ||
353 | amounts = balance_store.in_currency("BTC", compute_value="bid") | |
354 | self.assertEqual(D("0.65"), amounts["BTC"].value) | |
355 | self.assertEqual(D("0.27"), amounts["ETH"].value) | |
356 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | |
357 | "bid", "total") | |
358 | self.m.report.log_tickers.reset_mock() | |
359 | ||
360 | amounts = balance_store.in_currency("BTC", compute_value="bid", type="exchange_used") | |
361 | self.assertEqual(D("0.30"), amounts["BTC"].value) | |
362 | self.assertEqual(0, amounts["ETH"].value) | |
363 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | |
364 | "bid", "exchange_used") | |
365 | self.m.report.log_tickers.reset_mock() | |
366 | ||
367 | def test_fetch_balances(self): | |
368 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | |
369 | ||
370 | balance_store = market.BalanceStore(self.m) | |
371 | ||
2b1ee8f4 IB |
372 | with self.subTest(log_tickers=False): |
373 | balance_store.fetch_balances() | |
374 | self.assertNotIn("ETC", balance_store.currencies()) | |
375 | self.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store.currencies())) | |
376 | ||
377 | balance_store.all["ETC"] = portfolio.Balance("ETC", { | |
378 | "exchange_total": "1", "exchange_free": "0", | |
379 | "exchange_used": "1" }) | |
380 | balance_store.fetch_balances(tag="foo") | |
381 | self.assertEqual(0, balance_store.all["ETC"].total) | |
382 | self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store.currencies())) | |
383 | self.m.report.log_balances.assert_called_with(tag="foo") | |
384 | ||
385 | with self.subTest(log_tickers=True),\ | |
386 | mock.patch.object(balance_store, "in_currency") as in_currency: | |
387 | in_currency.return_value = "tickers" | |
388 | balance_store.fetch_balances(log_tickers=True, ticker_currency="FOO", | |
389 | ticker_compute_value="compute", ticker_type="type") | |
390 | self.m.report.log_balances.assert_called_with(compute_value='compute', | |
391 | tag=None, ticker_currency='FOO', tickers='tickers', | |
392 | type='type') | |
c682bdf4 IB |
393 | |
394 | @mock.patch.object(market.Portfolio, "repartition") | |
395 | def test_dispatch_assets(self, repartition): | |
396 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | |
397 | ||
398 | balance_store = market.BalanceStore(self.m) | |
399 | balance_store.fetch_balances() | |
400 | ||
401 | self.assertNotIn("XEM", balance_store.currencies()) | |
402 | ||
403 | repartition_hash = { | |
404 | "XEM": (D("0.75"), "long"), | |
405 | "BTC": (D("0.26"), "long"), | |
406 | "DASH": (D("0.10"), "short"), | |
407 | } | |
408 | repartition.return_value = repartition_hash | |
409 | ||
410 | amounts = balance_store.dispatch_assets(portfolio.Amount("BTC", "11.1")) | |
411 | repartition.assert_called_with(liquidity="medium") | |
412 | self.assertIn("XEM", balance_store.currencies()) | |
413 | self.assertEqual(D("2.6"), amounts["BTC"].value) | |
414 | self.assertEqual(D("7.5"), amounts["XEM"].value) | |
415 | self.assertEqual(D("-1.0"), amounts["DASH"].value) | |
416 | self.m.report.log_balances.assert_called_with(tag=None) | |
417 | self.m.report.log_dispatch.assert_called_once_with(portfolio.Amount("BTC", | |
418 | "11.1"), amounts, "medium", repartition_hash) | |
419 | ||
420 | def test_currencies(self): | |
421 | balance_store = market.BalanceStore(self.m) | |
422 | ||
423 | balance_store.all = { | |
424 | "BTC": portfolio.Balance("BTC", { | |
425 | "total": "0.65", | |
426 | "exchange_total":"0.65", | |
427 | "exchange_free": "0.35", | |
428 | "exchange_used": "0.30"}), | |
429 | "ETH": portfolio.Balance("ETH", { | |
430 | "total": 3, | |
431 | "exchange_total": 3, | |
432 | "exchange_free": 3, | |
433 | "exchange_used": 0}), | |
434 | } | |
435 | self.assertListEqual(["BTC", "ETH"], list(balance_store.currencies())) | |
436 | ||
437 | def test_as_json(self): | |
438 | balance_mock1 = mock.Mock() | |
439 | balance_mock1.as_json.return_value = 1 | |
440 | ||
441 | balance_mock2 = mock.Mock() | |
442 | balance_mock2.as_json.return_value = 2 | |
443 | ||
444 | balance_store = market.BalanceStore(self.m) | |
445 | balance_store.all = { | |
446 | "BTC": balance_mock1, | |
447 | "ETH": balance_mock2, | |
448 | } | |
449 | ||
450 | as_json = balance_store.as_json() | |
451 | self.assertEqual(1, as_json["BTC"]) | |
452 | self.assertEqual(2, as_json["ETH"]) | |
453 | ||
3080f31d | 454 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
c682bdf4 IB |
455 | class ReportStoreTest(WebMockTestCase): |
456 | def test_add_log(self): | |
e7d7c0e5 IB |
457 | with self.subTest(market=self.m): |
458 | self.m.user_id = 1 | |
459 | self.m.market_id = 3 | |
460 | report_store = market.ReportStore(self.m) | |
461 | result = report_store.add_log({"foo": "bar"}) | |
462 | ||
463 | self.assertEqual({"foo": "bar", "date": mock.ANY, "user_id": 1, "market_id": 3}, result) | |
464 | self.assertEqual(result, report_store.logs[0]) | |
465 | ||
466 | with self.subTest(market=None): | |
467 | report_store = market.ReportStore(None) | |
468 | result = report_store.add_log({"foo": "bar"}) | |
c682bdf4 | 469 | |
e7d7c0e5 | 470 | self.assertEqual({"foo": "bar", "date": mock.ANY, "user_id": None, "market_id": None}, result) |
c682bdf4 | 471 | |
1593c7a9 IB |
472 | def test_add_redis_status(self): |
473 | report_store = market.ReportStore(self.m) | |
474 | result = report_store.add_redis_status({"foo": "bar"}) | |
475 | ||
476 | self.assertEqual({"foo": "bar"}, result) | |
477 | self.assertEqual(result, report_store.redis_status[0]) | |
478 | ||
c682bdf4 IB |
479 | def test_set_verbose(self): |
480 | report_store = market.ReportStore(self.m) | |
481 | with self.subTest(verbose=True): | |
482 | report_store.set_verbose(True) | |
483 | self.assertTrue(report_store.verbose_print) | |
484 | ||
485 | with self.subTest(verbose=False): | |
486 | report_store.set_verbose(False) | |
487 | self.assertFalse(report_store.verbose_print) | |
488 | ||
489 | def test_merge(self): | |
e7d7c0e5 IB |
490 | self.m.user_id = 1 |
491 | self.m.market_id = 3 | |
c682bdf4 IB |
492 | report_store1 = market.ReportStore(self.m, verbose_print=False) |
493 | report_store2 = market.ReportStore(None, verbose_print=False) | |
494 | ||
495 | report_store2.log_stage("1") | |
496 | report_store1.log_stage("2") | |
497 | report_store2.log_stage("3") | |
498 | ||
499 | report_store1.merge(report_store2) | |
500 | ||
501 | self.assertEqual(3, len(report_store1.logs)) | |
502 | self.assertEqual(["1", "2", "3"], list(map(lambda x: x["stage"], report_store1.logs))) | |
503 | self.assertEqual(6, len(report_store1.print_logs)) | |
504 | ||
505 | def test_print_log(self): | |
506 | report_store = market.ReportStore(self.m) | |
507 | with self.subTest(verbose=True),\ | |
508 | mock.patch.object(store, "datetime") as time_mock,\ | |
509 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | |
e7d7c0e5 | 510 | time_mock.datetime.now.return_value = datetime.datetime(2018, 2, 25, 2, 20, 10) |
c682bdf4 IB |
511 | report_store.set_verbose(True) |
512 | report_store.print_log("Coucou") | |
513 | report_store.print_log(portfolio.Amount("BTC", 1)) | |
514 | self.assertEqual(stdout_mock.getvalue(), "2018-02-25 02:20:10: Coucou\n2018-02-25 02:20:10: 1.00000000 BTC\n") | |
515 | ||
516 | with self.subTest(verbose=False),\ | |
517 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | |
518 | report_store.set_verbose(False) | |
519 | report_store.print_log("Coucou") | |
520 | report_store.print_log(portfolio.Amount("BTC", 1)) | |
521 | self.assertEqual(stdout_mock.getvalue(), "") | |
522 | ||
523 | def test_default_json_serial(self): | |
524 | report_store = market.ReportStore(self.m) | |
525 | ||
526 | self.assertEqual("2018-02-24T00:00:00", | |
e7d7c0e5 | 527 | report_store.default_json_serial(portfolio.datetime.datetime(2018, 2, 24))) |
c682bdf4 IB |
528 | self.assertEqual("1.00000000 BTC", |
529 | report_store.default_json_serial(portfolio.Amount("BTC", 1))) | |
530 | ||
531 | def test_to_json(self): | |
532 | report_store = market.ReportStore(self.m) | |
533 | report_store.logs.append({"foo": "bar"}) | |
534 | self.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store.to_json()) | |
e7d7c0e5 | 535 | report_store.logs.append({"date": portfolio.datetime.datetime(2018, 2, 24)}) |
c682bdf4 IB |
536 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store.to_json()) |
537 | report_store.logs.append({"amount": portfolio.Amount("BTC", 1)}) | |
538 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n },\n {\n "amount": "1.00000000 BTC"\n }\n]', report_store.to_json()) | |
539 | ||
540 | def test_to_json_array(self): | |
541 | report_store = market.ReportStore(self.m) | |
542 | report_store.logs.append({ | |
543 | "date": "date1", "type": "type1", "foo": "bar", "bla": "bla" | |
544 | }) | |
545 | report_store.logs.append({ | |
546 | "date": "date2", "type": "type2", "foo": "bar", "bla": "bla" | |
547 | }) | |
548 | logs = list(report_store.to_json_array()) | |
549 | ||
550 | self.assertEqual(2, len(logs)) | |
551 | self.assertEqual(("date1", "type1", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[0]) | |
552 | self.assertEqual(("date2", "type2", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[1]) | |
553 | ||
1593c7a9 IB |
554 | def test_to_json_redis(self): |
555 | report_store = market.ReportStore(self.m) | |
556 | report_store.redis_status.append({ | |
557 | "type": "type1", "foo": "bar", "bla": "bla" | |
558 | }) | |
559 | report_store.redis_status.append({ | |
560 | "type": "type2", "foo": "bar", "bla": "bla" | |
561 | }) | |
562 | logs = list(report_store.to_json_redis()) | |
563 | ||
564 | self.assertEqual(2, len(logs)) | |
565 | self.assertEqual(("type1", '{"foo": "bar", "bla": "bla"}'), logs[0]) | |
566 | self.assertEqual(("type2", '{"foo": "bar", "bla": "bla"}'), logs[1]) | |
567 | ||
c682bdf4 IB |
568 | @mock.patch.object(market.ReportStore, "print_log") |
569 | @mock.patch.object(market.ReportStore, "add_log") | |
570 | def test_log_stage(self, add_log, print_log): | |
571 | report_store = market.ReportStore(self.m) | |
572 | c = lambda x: x | |
573 | report_store.log_stage("foo", bar="baz", c=c, d=portfolio.Amount("BTC", 1)) | |
574 | print_log.assert_has_calls([ | |
575 | mock.call("-----------"), | |
576 | mock.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"), | |
577 | ]) | |
578 | add_log.assert_called_once_with({ | |
579 | 'type': 'stage', | |
580 | 'stage': 'foo', | |
581 | 'args': { | |
582 | 'bar': 'baz', | |
583 | 'c': 'c = lambda x: x', | |
584 | 'd': { | |
585 | 'currency': 'BTC', | |
586 | 'value': D('1') | |
587 | } | |
588 | } | |
589 | }) | |
590 | ||
591 | @mock.patch.object(market.ReportStore, "print_log") | |
592 | @mock.patch.object(market.ReportStore, "add_log") | |
1593c7a9 IB |
593 | @mock.patch.object(market.ReportStore, "add_redis_status") |
594 | def test_log_balances(self, add_redis_status, add_log, print_log): | |
c682bdf4 IB |
595 | report_store = market.ReportStore(self.m) |
596 | self.m.balances.as_json.return_value = "json" | |
597 | self.m.balances.all = { "FOO": "bar", "BAR": "baz" } | |
598 | ||
2b1ee8f4 IB |
599 | with self.subTest(tickers=None): |
600 | report_store.log_balances(tag="tag") | |
601 | print_log.assert_has_calls([ | |
602 | mock.call("[Balance]"), | |
603 | mock.call("\tbar"), | |
604 | mock.call("\tbaz"), | |
605 | ]) | |
606 | add_log.assert_called_once_with({ | |
607 | 'type': 'balance', | |
608 | 'balances': 'json', | |
609 | 'tag': 'tag' | |
610 | }) | |
611 | add_redis_status.assert_called_once_with({ | |
612 | 'type': 'balance', | |
613 | 'balances': 'json', | |
614 | 'tag': 'tag' | |
615 | }) | |
616 | add_log.reset_mock() | |
617 | add_redis_status.reset_mock() | |
618 | with self.subTest(tickers="present"): | |
619 | amounts = { | |
620 | "BTC": portfolio.Amount("BTC", 10), | |
621 | "ETH": portfolio.Amount("BTC", D("0.3")) | |
622 | } | |
623 | amounts["ETH"].rate = D("0.1") | |
624 | ||
625 | report_store.log_balances(tag="tag", tickers=amounts, | |
626 | ticker_currency="BTC", compute_value="default", | |
627 | type="total") | |
628 | add_log.assert_called_once_with({ | |
629 | 'type': 'balance', | |
630 | 'balances': 'json', | |
631 | 'tag': 'tag', | |
632 | 'tickers': { | |
633 | 'compute_value': 'default', | |
634 | 'balance_type': 'total', | |
635 | 'currency': 'BTC', | |
636 | 'balances': { | |
637 | 'BTC': D('10'), | |
638 | 'ETH': D('0.3') | |
639 | }, | |
640 | 'rates': { | |
641 | 'BTC': None, | |
642 | 'ETH': D('0.1') | |
643 | }, | |
644 | 'total': D('10.3') | |
645 | }, | |
646 | }) | |
647 | add_redis_status.assert_called_once_with({ | |
648 | 'type': 'balance', | |
649 | 'balances': 'json', | |
650 | 'tag': 'tag', | |
651 | 'tickers': { | |
652 | 'compute_value': 'default', | |
653 | 'balance_type': 'total', | |
654 | 'currency': 'BTC', | |
655 | 'balances': { | |
656 | 'BTC': D('10'), | |
657 | 'ETH': D('0.3') | |
658 | }, | |
659 | 'rates': { | |
660 | 'BTC': None, | |
661 | 'ETH': D('0.1') | |
662 | }, | |
663 | 'total': D('10.3') | |
664 | }, | |
665 | }) | |
c682bdf4 IB |
666 | |
667 | @mock.patch.object(market.ReportStore, "print_log") | |
668 | @mock.patch.object(market.ReportStore, "add_log") | |
2b1ee8f4 | 669 | def test_log_tickers(self, add_log, print_log): |
c682bdf4 IB |
670 | report_store = market.ReportStore(self.m) |
671 | amounts = { | |
672 | "BTC": portfolio.Amount("BTC", 10), | |
673 | "ETH": portfolio.Amount("BTC", D("0.3")) | |
674 | } | |
675 | amounts["ETH"].rate = D("0.1") | |
676 | ||
677 | report_store.log_tickers(amounts, "BTC", "default", "total") | |
678 | print_log.assert_not_called() | |
679 | add_log.assert_called_once_with({ | |
680 | 'type': 'tickers', | |
681 | 'compute_value': 'default', | |
682 | 'balance_type': 'total', | |
683 | 'currency': 'BTC', | |
684 | 'balances': { | |
685 | 'BTC': D('10'), | |
686 | 'ETH': D('0.3') | |
687 | }, | |
688 | 'rates': { | |
689 | 'BTC': None, | |
690 | 'ETH': D('0.1') | |
691 | }, | |
692 | 'total': D('10.3') | |
693 | }) | |
694 | ||
695 | add_log.reset_mock() | |
696 | compute_value = lambda x: x["bid"] | |
697 | report_store.log_tickers(amounts, "BTC", compute_value, "total") | |
698 | add_log.assert_called_once_with({ | |
699 | 'type': 'tickers', | |
700 | 'compute_value': 'compute_value = lambda x: x["bid"]', | |
701 | 'balance_type': 'total', | |
702 | 'currency': 'BTC', | |
703 | 'balances': { | |
704 | 'BTC': D('10'), | |
705 | 'ETH': D('0.3') | |
706 | }, | |
707 | 'rates': { | |
708 | 'BTC': None, | |
709 | 'ETH': D('0.1') | |
710 | }, | |
711 | 'total': D('10.3') | |
712 | }) | |
713 | ||
714 | @mock.patch.object(market.ReportStore, "print_log") | |
715 | @mock.patch.object(market.ReportStore, "add_log") | |
716 | def test_log_dispatch(self, add_log, print_log): | |
717 | report_store = market.ReportStore(self.m) | |
718 | amount = portfolio.Amount("BTC", "10.3") | |
719 | amounts = { | |
720 | "BTC": portfolio.Amount("BTC", 10), | |
721 | "ETH": portfolio.Amount("BTC", D("0.3")) | |
722 | } | |
723 | report_store.log_dispatch(amount, amounts, "medium", "repartition") | |
724 | print_log.assert_not_called() | |
725 | add_log.assert_called_once_with({ | |
726 | 'type': 'dispatch', | |
727 | 'liquidity': 'medium', | |
728 | 'repartition_ratio': 'repartition', | |
729 | 'total_amount': { | |
730 | 'currency': 'BTC', | |
731 | 'value': D('10.3') | |
732 | }, | |
733 | 'repartition': { | |
734 | 'BTC': D('10'), | |
735 | 'ETH': D('0.3') | |
736 | } | |
737 | }) | |
738 | ||
739 | @mock.patch.object(market.ReportStore, "print_log") | |
740 | @mock.patch.object(market.ReportStore, "add_log") | |
741 | def test_log_trades(self, add_log, print_log): | |
742 | report_store = market.ReportStore(self.m) | |
743 | trade_mock1 = mock.Mock() | |
744 | trade_mock2 = mock.Mock() | |
745 | trade_mock1.as_json.return_value = { "trade": "1" } | |
746 | trade_mock2.as_json.return_value = { "trade": "2" } | |
747 | ||
748 | matching_and_trades = [ | |
749 | (True, trade_mock1), | |
750 | (False, trade_mock2), | |
751 | ] | |
752 | report_store.log_trades(matching_and_trades, "only") | |
753 | ||
754 | print_log.assert_not_called() | |
755 | add_log.assert_called_with({ | |
756 | 'type': 'trades', | |
757 | 'only': 'only', | |
758 | 'debug': False, | |
759 | 'trades': [ | |
760 | {'trade': '1', 'skipped': False}, | |
761 | {'trade': '2', 'skipped': True} | |
762 | ] | |
763 | }) | |
764 | ||
765 | @mock.patch.object(market.ReportStore, "print_log") | |
766 | @mock.patch.object(market.ReportStore, "add_log") | |
767 | def test_log_orders(self, add_log, print_log): | |
768 | report_store = market.ReportStore(self.m) | |
769 | ||
770 | order_mock1 = mock.Mock() | |
771 | order_mock2 = mock.Mock() | |
772 | ||
773 | order_mock1.as_json.return_value = "order1" | |
774 | order_mock2.as_json.return_value = "order2" | |
775 | ||
776 | orders = [order_mock1, order_mock2] | |
777 | ||
778 | report_store.log_orders(orders, tick="tick", | |
779 | only="only", compute_value="compute_value") | |
780 | ||
781 | print_log.assert_called_once_with("[Orders]") | |
782 | self.m.trades.print_all_with_order.assert_called_once_with(ind="\t") | |
783 | ||
784 | add_log.assert_called_with({ | |
785 | 'type': 'orders', | |
786 | 'only': 'only', | |
787 | 'compute_value': 'compute_value', | |
788 | 'tick': 'tick', | |
789 | 'orders': ['order1', 'order2'] | |
790 | }) | |
791 | ||
792 | add_log.reset_mock() | |
793 | def compute_value(x, y): | |
794 | return x[y] | |
795 | report_store.log_orders(orders, tick="tick", | |
796 | only="only", compute_value=compute_value) | |
797 | add_log.assert_called_with({ | |
798 | 'type': 'orders', | |
799 | 'only': 'only', | |
800 | 'compute_value': 'def compute_value(x, y):\n return x[y]', | |
801 | 'tick': 'tick', | |
802 | 'orders': ['order1', 'order2'] | |
803 | }) | |
804 | ||
805 | ||
806 | @mock.patch.object(market.ReportStore, "print_log") | |
807 | @mock.patch.object(market.ReportStore, "add_log") | |
808 | def test_log_order(self, add_log, print_log): | |
809 | report_store = market.ReportStore(self.m) | |
810 | order_mock = mock.Mock() | |
811 | order_mock.as_json.return_value = "order" | |
812 | new_order_mock = mock.Mock() | |
813 | new_order_mock.as_json.return_value = "new_order" | |
814 | order_mock.__repr__ = mock.Mock() | |
815 | order_mock.__repr__.return_value = "Order Mock" | |
816 | new_order_mock.__repr__ = mock.Mock() | |
817 | new_order_mock.__repr__.return_value = "New order Mock" | |
818 | ||
819 | with self.subTest(finished=True): | |
820 | report_store.log_order(order_mock, 1, finished=True) | |
821 | print_log.assert_called_once_with("[Order] Finished Order Mock") | |
822 | add_log.assert_called_once_with({ | |
823 | 'type': 'order', | |
824 | 'tick': 1, | |
825 | 'update': None, | |
826 | 'order': 'order', | |
827 | 'compute_value': None, | |
828 | 'new_order': None | |
829 | }) | |
830 | ||
831 | add_log.reset_mock() | |
832 | print_log.reset_mock() | |
833 | ||
834 | with self.subTest(update="waiting"): | |
835 | report_store.log_order(order_mock, 1, update="waiting") | |
836 | print_log.assert_called_once_with("[Order] Order Mock, tick 1, waiting") | |
837 | add_log.assert_called_once_with({ | |
838 | 'type': 'order', | |
839 | 'tick': 1, | |
840 | 'update': 'waiting', | |
841 | 'order': 'order', | |
842 | 'compute_value': None, | |
843 | 'new_order': None | |
844 | }) | |
845 | ||
846 | add_log.reset_mock() | |
847 | print_log.reset_mock() | |
848 | with self.subTest(update="adjusting"): | |
849 | compute_value = lambda x: (x["bid"] + x["ask"]*2)/3 | |
850 | report_store.log_order(order_mock, 3, | |
851 | update="adjusting", new_order=new_order_mock, | |
852 | compute_value=compute_value) | |
853 | print_log.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock") | |
854 | add_log.assert_called_once_with({ | |
855 | 'type': 'order', | |
856 | 'tick': 3, | |
857 | 'update': 'adjusting', | |
858 | 'order': 'order', | |
859 | 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3', | |
860 | 'new_order': 'new_order' | |
861 | }) | |
862 | ||
863 | add_log.reset_mock() | |
864 | print_log.reset_mock() | |
865 | with self.subTest(update="market_fallback"): | |
866 | report_store.log_order(order_mock, 7, | |
867 | update="market_fallback", new_order=new_order_mock) | |
868 | print_log.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value") | |
869 | add_log.assert_called_once_with({ | |
870 | 'type': 'order', | |
871 | 'tick': 7, | |
872 | 'update': 'market_fallback', | |
873 | 'order': 'order', | |
874 | 'compute_value': None, | |
875 | 'new_order': 'new_order' | |
876 | }) | |
877 | ||
878 | add_log.reset_mock() | |
879 | print_log.reset_mock() | |
880 | with self.subTest(update="market_adjusting"): | |
881 | report_store.log_order(order_mock, 17, | |
882 | update="market_adjust", new_order=new_order_mock) | |
883 | print_log.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock") | |
884 | add_log.assert_called_once_with({ | |
885 | 'type': 'order', | |
886 | 'tick': 17, | |
887 | 'update': 'market_adjust', | |
888 | 'order': 'order', | |
889 | 'compute_value': None, | |
890 | 'new_order': 'new_order' | |
891 | }) | |
892 | ||
893 | @mock.patch.object(market.ReportStore, "print_log") | |
894 | @mock.patch.object(market.ReportStore, "add_log") | |
895 | def test_log_move_balances(self, add_log, print_log): | |
896 | report_store = market.ReportStore(self.m) | |
897 | needed = { | |
898 | "BTC": portfolio.Amount("BTC", 10), | |
899 | "USDT": 1 | |
900 | } | |
901 | moving = { | |
902 | "BTC": portfolio.Amount("BTC", 3), | |
903 | "USDT": -2 | |
904 | } | |
905 | report_store.log_move_balances(needed, moving) | |
906 | print_log.assert_not_called() | |
907 | add_log.assert_called_once_with({ | |
908 | 'type': 'move_balances', | |
909 | 'debug': False, | |
910 | 'needed': { | |
911 | 'BTC': D('10'), | |
912 | 'USDT': 1 | |
913 | }, | |
914 | 'moving': { | |
915 | 'BTC': D('3'), | |
916 | 'USDT': -2 | |
917 | } | |
918 | }) | |
919 | ||
e7d7c0e5 IB |
920 | def test_log_http_request(self): |
921 | with mock.patch.object(market.ReportStore, "add_log") as add_log: | |
922 | report_store = market.ReportStore(self.m) | |
923 | response = mock.Mock() | |
924 | response.status_code = 200 | |
925 | response.text = "Hey" | |
9fe90554 | 926 | response.elapsed.total_seconds.return_value = 120 |
c682bdf4 | 927 | |
e7d7c0e5 IB |
928 | report_store.log_http_request("method", "url", "body", |
929 | "headers", response) | |
930 | add_log.assert_called_once_with({ | |
931 | 'type': 'http_request', | |
932 | 'method': 'method', | |
933 | 'url': 'url', | |
934 | 'body': 'body', | |
935 | 'headers': 'headers', | |
936 | 'status': 200, | |
9fe90554 | 937 | 'duration': 120, |
e7d7c0e5 IB |
938 | 'response': 'Hey', |
939 | 'response_same_as': None, | |
940 | }) | |
c682bdf4 | 941 | |
e7d7c0e5 IB |
942 | add_log.reset_mock() |
943 | report_store.log_http_request("method", "url", "body", | |
944 | "headers", ValueError("Foo")) | |
945 | add_log.assert_called_once_with({ | |
946 | 'type': 'http_request', | |
947 | 'method': 'method', | |
948 | 'url': 'url', | |
949 | 'body': 'body', | |
950 | 'headers': 'headers', | |
951 | 'status': -1, | |
952 | 'response': None, | |
953 | 'error': 'ValueError', | |
954 | 'error_message': 'Foo', | |
955 | }) | |
956 | ||
957 | with self.subTest(no_http_dup=True, duplicate=True): | |
958 | self.m.user_id = 1 | |
959 | self.m.market_id = 3 | |
960 | report_store = market.ReportStore(self.m, no_http_dup=True) | |
961 | original_add_log = report_store.add_log | |
962 | with mock.patch.object(report_store, "add_log", side_effect=original_add_log) as add_log: | |
963 | report_store.log_http_request("method", "url", "body", | |
964 | "headers", response) | |
965 | report_store.log_http_request("method", "url", "body", | |
966 | "headers", response) | |
967 | self.assertEqual(2, add_log.call_count) | |
968 | self.assertIsNone(add_log.mock_calls[0][1][0]["response_same_as"]) | |
969 | self.assertIsNone(add_log.mock_calls[1][1][0]["response"]) | |
970 | self.assertEqual(add_log.mock_calls[0][1][0]["date"], add_log.mock_calls[1][1][0]["response_same_as"]) | |
971 | with self.subTest(no_http_dup=True, duplicate=False, case="Different call"): | |
972 | self.m.user_id = 1 | |
973 | self.m.market_id = 3 | |
974 | report_store = market.ReportStore(self.m, no_http_dup=True) | |
975 | original_add_log = report_store.add_log | |
976 | with mock.patch.object(report_store, "add_log", side_effect=original_add_log) as add_log: | |
977 | report_store.log_http_request("method", "url", "body", | |
978 | "headers", response) | |
979 | report_store.log_http_request("method2", "url", "body", | |
980 | "headers", response) | |
981 | self.assertEqual(2, add_log.call_count) | |
982 | self.assertIsNone(add_log.mock_calls[0][1][0]["response_same_as"]) | |
983 | self.assertIsNone(add_log.mock_calls[1][1][0]["response_same_as"]) | |
984 | with self.subTest(no_http_dup=True, duplicate=False, case="Call inbetween"): | |
985 | self.m.user_id = 1 | |
986 | self.m.market_id = 3 | |
987 | report_store = market.ReportStore(self.m, no_http_dup=True) | |
988 | original_add_log = report_store.add_log | |
989 | ||
990 | response2 = mock.Mock() | |
991 | response2.status_code = 200 | |
992 | response2.text = "Hey there!" | |
993 | ||
994 | with mock.patch.object(report_store, "add_log", side_effect=original_add_log) as add_log: | |
995 | report_store.log_http_request("method", "url", "body", | |
996 | "headers", response) | |
997 | report_store.log_http_request("method", "url", "body", | |
998 | "headers", response2) | |
999 | report_store.log_http_request("method", "url", "body", | |
1000 | "headers", response) | |
1001 | self.assertEqual(3, add_log.call_count) | |
1002 | self.assertIsNone(add_log.mock_calls[0][1][0]["response_same_as"]) | |
1003 | self.assertIsNone(add_log.mock_calls[1][1][0]["response_same_as"]) | |
1004 | self.assertIsNone(add_log.mock_calls[2][1][0]["response_same_as"]) | |
c682bdf4 IB |
1005 | |
1006 | @mock.patch.object(market.ReportStore, "add_log") | |
1007 | def test_log_market(self, add_log): | |
1008 | report_store = market.ReportStore(self.m) | |
1009 | ||
e7d7c0e5 | 1010 | report_store.log_market(self.market_args(debug=True, quiet=False)) |
c682bdf4 IB |
1011 | add_log.assert_called_once_with({ |
1012 | "type": "market", | |
1013 | "commit": "$Format:%H$", | |
1014 | "args": { "report_path": None, "debug": True, "quiet": False }, | |
c682bdf4 IB |
1015 | }) |
1016 | ||
1017 | @mock.patch.object(market.ReportStore, "print_log") | |
1018 | @mock.patch.object(market.ReportStore, "add_log") | |
1019 | def test_log_error(self, add_log, print_log): | |
1020 | report_store = market.ReportStore(self.m) | |
1021 | with self.subTest(message=None, exception=None): | |
1022 | report_store.log_error("action") | |
1023 | print_log.assert_called_once_with("[Error] action") | |
1024 | add_log.assert_called_once_with({ | |
1025 | 'type': 'error', | |
1026 | 'action': 'action', | |
1027 | 'exception_class': None, | |
1028 | 'exception_message': None, | |
1029 | 'message': None | |
1030 | }) | |
1031 | ||
1032 | print_log.reset_mock() | |
1033 | add_log.reset_mock() | |
1034 | with self.subTest(message="Hey", exception=None): | |
1035 | report_store.log_error("action", message="Hey") | |
1036 | print_log.assert_has_calls([ | |
1037 | mock.call("[Error] action"), | |
1038 | mock.call("\tHey") | |
1039 | ]) | |
1040 | add_log.assert_called_once_with({ | |
1041 | 'type': 'error', | |
1042 | 'action': 'action', | |
1043 | 'exception_class': None, | |
1044 | 'exception_message': None, | |
1045 | 'message': "Hey" | |
1046 | }) | |
1047 | ||
1048 | print_log.reset_mock() | |
1049 | add_log.reset_mock() | |
1050 | with self.subTest(message=None, exception=Exception("bouh")): | |
1051 | report_store.log_error("action", exception=Exception("bouh")) | |
1052 | print_log.assert_has_calls([ | |
1053 | mock.call("[Error] action"), | |
1054 | mock.call("\tException: bouh") | |
1055 | ]) | |
1056 | add_log.assert_called_once_with({ | |
1057 | 'type': 'error', | |
1058 | 'action': 'action', | |
1059 | 'exception_class': "Exception", | |
1060 | 'exception_message': "bouh", | |
1061 | 'message': None | |
1062 | }) | |
1063 | ||
1064 | print_log.reset_mock() | |
1065 | add_log.reset_mock() | |
1066 | with self.subTest(message="Hey", exception=Exception("bouh")): | |
1067 | report_store.log_error("action", message="Hey", exception=Exception("bouh")) | |
1068 | print_log.assert_has_calls([ | |
1069 | mock.call("[Error] action"), | |
1070 | mock.call("\tException: bouh"), | |
1071 | mock.call("\tHey") | |
1072 | ]) | |
1073 | add_log.assert_called_once_with({ | |
1074 | 'type': 'error', | |
1075 | 'action': 'action', | |
1076 | 'exception_class': "Exception", | |
1077 | 'exception_message': "bouh", | |
1078 | 'message': "Hey" | |
1079 | }) | |
1080 | ||
1081 | @mock.patch.object(market.ReportStore, "print_log") | |
1082 | @mock.patch.object(market.ReportStore, "add_log") | |
1083 | def test_log_debug_action(self, add_log, print_log): | |
1084 | report_store = market.ReportStore(self.m) | |
1085 | report_store.log_debug_action("Hey") | |
1086 | ||
1087 | print_log.assert_called_once_with("[Debug] Hey") | |
1088 | add_log.assert_called_once_with({ | |
1089 | 'type': 'debug_action', | |
1090 | 'action': 'Hey' | |
1091 | }) | |
1092 | ||
3080f31d | 1093 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
c682bdf4 IB |
1094 | class PortfolioTest(WebMockTestCase): |
1095 | def setUp(self): | |
1096 | super().setUp() | |
1097 | ||
1098 | with open("test_samples/test_portfolio.json") as example: | |
1099 | self.json_response = example.read() | |
1100 | ||
1101 | self.wm.get(market.Portfolio.URL, text=self.json_response) | |
1102 | ||
1103 | @mock.patch.object(market.Portfolio, "parse_cryptoportfolio") | |
1104 | def test_get_cryptoportfolio(self, parse_cryptoportfolio): | |
1105 | with self.subTest(parallel=False): | |
1106 | self.wm.get(market.Portfolio.URL, [ | |
1107 | {"text":'{ "foo": "bar" }', "status_code": 200}, | |
1108 | {"text": "System Error", "status_code": 500}, | |
1109 | {"exc": requests.exceptions.ConnectTimeout}, | |
1110 | ]) | |
1111 | market.Portfolio.get_cryptoportfolio() | |
1112 | self.assertIn("foo", market.Portfolio.data.get()) | |
1113 | self.assertEqual("bar", market.Portfolio.data.get()["foo"]) | |
1114 | self.assertTrue(self.wm.called) | |
1115 | self.assertEqual(1, self.wm.call_count) | |
1116 | market.Portfolio.report.log_error.assert_not_called() | |
1117 | market.Portfolio.report.log_http_request.assert_called_once() | |
1118 | parse_cryptoportfolio.assert_called_once_with() | |
1119 | market.Portfolio.report.log_http_request.reset_mock() | |
1120 | parse_cryptoportfolio.reset_mock() | |
1121 | market.Portfolio.data = store.LockedVar(None) | |
1122 | ||
1123 | market.Portfolio.get_cryptoportfolio() | |
1124 | self.assertIsNone(market.Portfolio.data.get()) | |
1125 | self.assertEqual(2, self.wm.call_count) | |
1126 | parse_cryptoportfolio.assert_not_called() | |
1127 | market.Portfolio.report.log_error.assert_not_called() | |
1128 | market.Portfolio.report.log_http_request.assert_called_once() | |
1129 | market.Portfolio.report.log_http_request.reset_mock() | |
1130 | parse_cryptoportfolio.reset_mock() | |
1131 | ||
1132 | market.Portfolio.data = store.LockedVar("Foo") | |
1133 | market.Portfolio.get_cryptoportfolio() | |
1134 | self.assertEqual(2, self.wm.call_count) | |
1135 | parse_cryptoportfolio.assert_not_called() | |
1136 | ||
1137 | market.Portfolio.get_cryptoportfolio(refetch=True) | |
1138 | self.assertEqual("Foo", market.Portfolio.data.get()) | |
1139 | self.assertEqual(3, self.wm.call_count) | |
1140 | market.Portfolio.report.log_error.assert_called_once_with("get_cryptoportfolio", | |
1141 | exception=mock.ANY) | |
1142 | market.Portfolio.report.log_http_request.assert_not_called() | |
1143 | with self.subTest(parallel=True): | |
1144 | with mock.patch.object(market.Portfolio, "is_worker_thread") as is_worker,\ | |
1145 | mock.patch.object(market.Portfolio, "notify_and_wait") as notify: | |
1146 | with self.subTest(worker=True): | |
1147 | market.Portfolio.data = store.LockedVar(None) | |
1148 | market.Portfolio.worker = mock.Mock() | |
1149 | is_worker.return_value = True | |
1150 | self.wm.get(market.Portfolio.URL, [ | |
1151 | {"text":'{ "foo": "bar" }', "status_code": 200}, | |
1152 | ]) | |
1153 | market.Portfolio.get_cryptoportfolio() | |
1154 | self.assertIn("foo", market.Portfolio.data.get()) | |
1155 | parse_cryptoportfolio.reset_mock() | |
1156 | with self.subTest(worker=False): | |
1157 | market.Portfolio.data = store.LockedVar(None) | |
1158 | market.Portfolio.worker = mock.Mock() | |
1159 | is_worker.return_value = False | |
1160 | market.Portfolio.get_cryptoportfolio() | |
1161 | notify.assert_called_once_with() | |
1162 | parse_cryptoportfolio.assert_not_called() | |
1163 | ||
1164 | def test_parse_cryptoportfolio(self): | |
1165 | with self.subTest(description="Normal case"): | |
1166 | market.Portfolio.data = store.LockedVar(store.json.loads( | |
1167 | self.json_response, parse_int=D, parse_float=D)) | |
1168 | market.Portfolio.parse_cryptoportfolio() | |
1169 | ||
1170 | self.assertListEqual( | |
1171 | ["medium", "high"], | |
1172 | list(market.Portfolio.liquidities.get().keys())) | |
1173 | ||
1174 | liquidities = market.Portfolio.liquidities.get() | |
1175 | self.assertEqual(10, len(liquidities["medium"].keys())) | |
1176 | self.assertEqual(10, len(liquidities["high"].keys())) | |
1177 | ||
1178 | expected = { | |
1179 | 'BTC': (D("0.2857"), "long"), | |
1180 | 'DGB': (D("0.1015"), "long"), | |
1181 | 'DOGE': (D("0.1805"), "long"), | |
1182 | 'SC': (D("0.0623"), "long"), | |
1183 | 'ZEC': (D("0.3701"), "long"), | |
1184 | } | |
e7d7c0e5 | 1185 | date = portfolio.datetime.datetime(2018, 1, 8) |
c682bdf4 IB |
1186 | self.assertDictEqual(expected, liquidities["high"][date]) |
1187 | ||
1188 | expected = { | |
1189 | 'BTC': (D("1.1102e-16"), "long"), | |
1190 | 'ETC': (D("0.1"), "long"), | |
1191 | 'FCT': (D("0.1"), "long"), | |
1192 | 'GAS': (D("0.1"), "long"), | |
1193 | 'NAV': (D("0.1"), "long"), | |
1194 | 'OMG': (D("0.1"), "long"), | |
1195 | 'OMNI': (D("0.1"), "long"), | |
1196 | 'PPC': (D("0.1"), "long"), | |
1197 | 'RIC': (D("0.1"), "long"), | |
1198 | 'VIA': (D("0.1"), "long"), | |
1199 | 'XCP': (D("0.1"), "long"), | |
1200 | } | |
1201 | self.assertDictEqual(expected, liquidities["medium"][date]) | |
e7d7c0e5 | 1202 | self.assertEqual(portfolio.datetime.datetime(2018, 1, 15), market.Portfolio.last_date.get()) |
c682bdf4 IB |
1203 | |
1204 | with self.subTest(description="Missing weight"): | |
1205 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | |
1206 | del(data["portfolio_2"]["weights"]) | |
1207 | market.Portfolio.data = store.LockedVar(data) | |
1208 | ||
1209 | market.Portfolio.parse_cryptoportfolio() | |
1210 | self.assertListEqual( | |
1211 | ["medium", "high"], | |
1212 | list(market.Portfolio.liquidities.get().keys())) | |
1213 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | |
1214 | ||
1215 | with self.subTest(description="All missing weights"): | |
1216 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | |
1217 | del(data["portfolio_1"]["weights"]) | |
1218 | del(data["portfolio_2"]["weights"]) | |
1219 | market.Portfolio.data = store.LockedVar(data) | |
1220 | ||
1221 | market.Portfolio.parse_cryptoportfolio() | |
1222 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | |
1223 | self.assertEqual({}, market.Portfolio.liquidities.get("high")) | |
1224 | self.assertEqual(datetime.datetime(1,1,1), market.Portfolio.last_date.get()) | |
1225 | ||
1226 | ||
1227 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | |
1228 | def test_repartition(self, get_cryptoportfolio): | |
1229 | market.Portfolio.liquidities = store.LockedVar({ | |
1230 | "medium": { | |
1231 | "2018-03-01": "medium_2018-03-01", | |
1232 | "2018-03-08": "medium_2018-03-08", | |
1233 | }, | |
1234 | "high": { | |
1235 | "2018-03-01": "high_2018-03-01", | |
1236 | "2018-03-08": "high_2018-03-08", | |
1237 | } | |
1238 | }) | |
1239 | market.Portfolio.last_date = store.LockedVar("2018-03-08") | |
1240 | ||
1241 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition()) | |
1242 | get_cryptoportfolio.assert_called_once_with() | |
1243 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition(liquidity="medium")) | |
1244 | self.assertEqual("high_2018-03-08", market.Portfolio.repartition(liquidity="high")) | |
1245 | ||
1246 | @mock.patch.object(market.time, "sleep") | |
1247 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | |
1248 | def test_wait_for_recent(self, get_cryptoportfolio, sleep): | |
1249 | self.call_count = 0 | |
1250 | def _get(refetch=False): | |
1251 | if self.call_count != 0: | |
1252 | self.assertTrue(refetch) | |
1253 | else: | |
1254 | self.assertFalse(refetch) | |
1255 | self.call_count += 1 | |
e7d7c0e5 IB |
1256 | market.Portfolio.last_date = store.LockedVar(store.datetime.datetime.now()\ |
1257 | - store.datetime.timedelta(10)\ | |
1258 | + store.datetime.timedelta(self.call_count)) | |
c682bdf4 IB |
1259 | get_cryptoportfolio.side_effect = _get |
1260 | ||
1261 | market.Portfolio.wait_for_recent() | |
1262 | sleep.assert_called_with(30) | |
1263 | self.assertEqual(6, sleep.call_count) | |
1264 | self.assertEqual(7, get_cryptoportfolio.call_count) | |
1265 | market.Portfolio.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio") | |
1266 | ||
1267 | sleep.reset_mock() | |
1268 | get_cryptoportfolio.reset_mock() | |
1269 | market.Portfolio.last_date = store.LockedVar(None) | |
1270 | self.call_count = 0 | |
1271 | market.Portfolio.wait_for_recent(delta=15) | |
1272 | sleep.assert_not_called() | |
1273 | self.assertEqual(1, get_cryptoportfolio.call_count) | |
1274 | ||
1275 | sleep.reset_mock() | |
1276 | get_cryptoportfolio.reset_mock() | |
1277 | market.Portfolio.last_date = store.LockedVar(None) | |
1278 | self.call_count = 0 | |
1279 | market.Portfolio.wait_for_recent(delta=1) | |
1280 | sleep.assert_called_with(30) | |
1281 | self.assertEqual(9, sleep.call_count) | |
1282 | self.assertEqual(10, get_cryptoportfolio.call_count) | |
1283 | ||
1284 | def test_is_worker_thread(self): | |
1285 | with self.subTest(worker=None): | |
1286 | self.assertFalse(store.Portfolio.is_worker_thread()) | |
1287 | ||
1288 | with self.subTest(worker="not self"),\ | |
1289 | mock.patch("threading.current_thread") as current_thread: | |
1290 | current = mock.Mock() | |
1291 | current_thread.return_value = current | |
1292 | store.Portfolio.worker = mock.Mock() | |
1293 | self.assertFalse(store.Portfolio.is_worker_thread()) | |
1294 | ||
1295 | with self.subTest(worker="self"),\ | |
1296 | mock.patch("threading.current_thread") as current_thread: | |
1297 | current = mock.Mock() | |
1298 | current_thread.return_value = current | |
1299 | store.Portfolio.worker = current | |
1300 | self.assertTrue(store.Portfolio.is_worker_thread()) | |
1301 | ||
1302 | def test_start_worker(self): | |
1303 | with mock.patch.object(store.Portfolio, "wait_for_notification") as notification: | |
1304 | store.Portfolio.start_worker() | |
1305 | notification.assert_called_once_with(poll=30) | |
1306 | ||
1307 | self.assertEqual("lock", store.Portfolio.last_date.lock.__class__.__name__) | |
1308 | self.assertEqual("lock", store.Portfolio.liquidities.lock.__class__.__name__) | |
1309 | store.Portfolio.report.start_lock.assert_called_once_with() | |
1310 | ||
1311 | self.assertIsNotNone(store.Portfolio.worker) | |
1312 | self.assertIsNotNone(store.Portfolio.worker_notify) | |
1313 | self.assertIsNotNone(store.Portfolio.callback) | |
1314 | self.assertTrue(store.Portfolio.worker_started) | |
1315 | ||
1316 | self.assertFalse(store.Portfolio.worker.is_alive()) | |
e7d7c0e5 IB |
1317 | self.assertEqual(1, threading.active_count()) |
1318 | ||
1319 | def test_stop_worker(self): | |
1320 | with mock.patch.object(store.Portfolio, "get_cryptoportfolio") as get,\ | |
1321 | mock.patch.object(store.Portfolio, "report") as report,\ | |
1322 | mock.patch.object(store.time, "sleep") as sleep: | |
1323 | store.Portfolio.start_worker(poll=3) | |
1324 | store.Portfolio.stop_worker() | |
1325 | store.Portfolio.worker.join() | |
1326 | get.assert_not_called() | |
1327 | report.assert_not_called() | |
1328 | sleep.assert_not_called() | |
1329 | self.assertFalse(store.Portfolio.worker.is_alive()) | |
c682bdf4 IB |
1330 | |
1331 | def test_wait_for_notification(self): | |
1332 | with self.assertRaises(RuntimeError): | |
1333 | store.Portfolio.wait_for_notification() | |
1334 | ||
1335 | with mock.patch.object(store.Portfolio, "get_cryptoportfolio") as get,\ | |
1336 | mock.patch.object(store.Portfolio, "report") as report,\ | |
1337 | mock.patch.object(store.time, "sleep") as sleep: | |
1338 | store.Portfolio.start_worker(poll=3) | |
1339 | ||
1340 | store.Portfolio.worker_notify.set() | |
1341 | ||
1342 | store.Portfolio.callback.wait() | |
1343 | ||
a0dcf4e0 | 1344 | report.print_log.assert_called_once_with("[Worker] Fetching cryptoportfolio") |
c682bdf4 IB |
1345 | get.assert_called_once_with(refetch=True) |
1346 | sleep.assert_called_once_with(3) | |
1347 | self.assertFalse(store.Portfolio.worker_notify.is_set()) | |
1348 | self.assertTrue(store.Portfolio.worker.is_alive()) | |
1349 | ||
1350 | store.Portfolio.callback.clear() | |
1351 | store.Portfolio.worker_started = False | |
1352 | store.Portfolio.worker_notify.set() | |
e7d7c0e5 | 1353 | store.Portfolio.worker.join() |
c682bdf4 IB |
1354 | self.assertFalse(store.Portfolio.worker.is_alive()) |
1355 | ||
1356 | def test_notify_and_wait(self): | |
1357 | with mock.patch.object(store.Portfolio, "callback") as callback,\ | |
1358 | mock.patch.object(store.Portfolio, "worker_notify") as worker_notify: | |
1359 | store.Portfolio.notify_and_wait() | |
1360 | callback.clear.assert_called_once_with() | |
1361 | worker_notify.set.assert_called_once_with() | |
1362 | callback.wait.assert_called_once_with() | |
1363 | ||
1364 |