]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blobdiff - test.py
Move Portfolio to store and cleanup methods
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / test.py
diff --git a/test.py b/test.py
index feac62f7be7755cebac97c4ccdd4774285a3f457..d4432f6e7a87636efc8c94913382b385177a4841 100644 (file)
--- a/test.py
+++ b/test.py
@@ -7,7 +7,7 @@ from unittest import mock
 import requests
 import requests_mock
 from io import StringIO
-import portfolio, market, main
+import portfolio, market, main, store
 
 limits = ["acceptance", "unit"]
 for test_type in limits:
@@ -32,7 +32,11 @@ class WebMockTestCase(unittest.TestCase):
         self.m.debug = False
 
         self.patchers = [
-                mock.patch.multiple(portfolio.Portfolio, last_date=None, data=None, liquidities={}),
+                mock.patch.multiple(market.Portfolio,
+                    last_date=None,
+                    data=None,
+                    liquidities={},
+                    report=mock.Mock()),
                 mock.patch.multiple(portfolio.Computation,
                     computations=portfolio.Computation.computations),
                 ]
@@ -126,59 +130,377 @@ class poloniexETest(unittest.TestCase):
                     }
             self.assertEqual(expected, self.s.margin_summary())
 
+    def test_create_order(self):
+        with mock.patch.object(self.s, "create_exchange_order") as exchange,\
+                mock.patch.object(self.s, "create_margin_order") as margin:
+            with self.subTest(account="unspecified"):
+                self.s.create_order("symbol", "type", "side", "amount", price="price", lending_rate="lending_rate", params="params")
+                exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
+                margin.assert_not_called()
+                exchange.reset_mock()
+                margin.reset_mock()
+
+            with self.subTest(account="exchange"):
+                self.s.create_order("symbol", "type", "side", "amount", account="exchange", price="price", lending_rate="lending_rate", params="params")
+                exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
+                margin.assert_not_called()
+                exchange.reset_mock()
+                margin.reset_mock()
+
+            with self.subTest(account="margin"):
+                self.s.create_order("symbol", "type", "side", "amount", account="margin", price="price", lending_rate="lending_rate", params="params")
+                margin.assert_called_once_with("symbol", "type", "side", "amount", lending_rate="lending_rate", price="price", params="params")
+                exchange.assert_not_called()
+                exchange.reset_mock()
+                margin.reset_mock()
+
+            with self.subTest(account="unknown"), self.assertRaises(NotImplementedError):
+                self.s.create_order("symbol", "type", "side", "amount", account="unknown")
+
+    def test_parse_ticker(self):
+        ticker = {
+                "high24hr": "12",
+                "low24hr": "10",
+                "highestBid": "10.5",
+                "lowestAsk": "11.5",
+                "last": "11",
+                "percentChange": "0.1",
+                "quoteVolume": "10",
+                "baseVolume": "20"
+                }
+        market = {
+                "symbol": "BTC/ETC"
+                }
+        with mock.patch.object(self.s, "milliseconds") as ms:
+            ms.return_value = 1520292715123
+            result = self.s.parse_ticker(ticker, market)
+
+            expected = {
+                    "symbol": "BTC/ETC",
+                    "timestamp": 1520292715123,
+                    "datetime": "2018-03-05T23:31:55.123Z",
+                    "high": D("12"),
+                    "low": D("10"),
+                    "bid": D("10.5"),
+                    "ask": D("11.5"),
+                    "vwap": None,
+                    "open": None,
+                    "close": None,
+                    "first": None,
+                    "last": D("11"),
+                    "change": D("0.1"),
+                    "percentage": None,
+                    "average": None,
+                    "baseVolume": D("10"),
+                    "quoteVolume": D("20"),
+                    "info": ticker
+                    }
+            self.assertEqual(expected, result)
+
+    def test_fetch_margin_balance(self):
+        with mock.patch.object(self.s, "privatePostGetMarginPosition") as get_margin_position:
+            get_margin_position.return_value = {
+                    "BTC_DASH": {
+                        "amount": "-0.1",
+                        "basePrice": "0.06818560",
+                        "lendingFees": "0.00000001",
+                        "liquidationPrice": "0.15107132",
+                        "pl": "-0.00000371",
+                        "total": "0.00681856",
+                        "type": "short"
+                        },
+                    "BTC_ETC": {
+                        "amount": "-0.6",
+                        "basePrice": "0.1",
+                        "lendingFees": "0.00000001",
+                        "liquidationPrice": "0.6",
+                        "pl": "0.00000371",
+                        "total": "0.06",
+                        "type": "short"
+                        },
+                    "BTC_ETH": {
+                        "amount": "0",
+                        "basePrice": "0",
+                        "lendingFees": "0",
+                        "liquidationPrice": "-1",
+                        "pl": "0",
+                        "total": "0",
+                        "type": "none"
+                        }
+                    }
+            balances = self.s.fetch_margin_balance()
+            self.assertEqual(2, len(balances))
+            expected = {
+                "DASH": {
+                    "amount": D("-0.1"),
+                    "borrowedPrice": D("0.06818560"),
+                    "lendingFees": D("1E-8"),
+                    "pl": D("-0.00000371"),
+                    "liquidationPrice": D("0.15107132"),
+                    "type": "short",
+                    "total": D("0.00681856"),
+                    "baseCurrency": "BTC"
+                    },
+                "ETC": {
+                    "amount": D("-0.6"),
+                    "borrowedPrice": D("0.1"),
+                    "lendingFees": D("1E-8"),
+                    "pl": D("0.00000371"),
+                    "liquidationPrice": D("0.6"),
+                    "type": "short",
+                    "total": D("0.06"),
+                    "baseCurrency": "BTC"
+                    }
+                }
+            self.assertEqual(expected, balances)
+
+    def test_sum(self):
+        self.assertEqual(D("1.1"), self.s.sum(D("1"), D("0.1")))
+
+    def test_fetch_balance(self):
+        with mock.patch.object(self.s, "load_markets") as load_markets,\
+                mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balances,\
+                mock.patch.object(self.s, "common_currency_code") as ccc:
+            ccc.side_effect = ["ETH", "BTC", "DASH"]
+            balances.return_value = {
+                    "ETH": {
+                        "available": "10",
+                        "onOrders": "1",
+                        },
+                    "BTC": {
+                        "available": "1",
+                        "onOrders": "0",
+                        },
+                    "DASH": {
+                        "available": "0",
+                        "onOrders": "3"
+                        }
+                    }
+
+            expected = {
+                    "info": {
+                        "ETH": {"available": "10", "onOrders": "1"},
+                        "BTC": {"available": "1", "onOrders": "0"},
+                        "DASH": {"available": "0", "onOrders": "3"}
+                        },
+                    "ETH": {"free": D("10"), "used": D("1"), "total": D("11")},
+                    "BTC": {"free": D("1"), "used": D("0"), "total": D("1")},
+                    "DASH": {"free": D("0"), "used": D("3"), "total": D("3")},
+                    "free": {"ETH": D("10"), "BTC": D("1"), "DASH": D("0")},
+                    "used": {"ETH": D("1"), "BTC": D("0"), "DASH": D("3")},
+                    "total": {"ETH": D("11"), "BTC": D("1"), "DASH": D("3")}
+                    }
+            result = self.s.fetch_balance()
+            load_markets.assert_called_once()
+            self.assertEqual(expected, result)
+
+    def test_fetch_balance_per_type(self):
+        with mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balances:
+            balances.return_value = {
+                "exchange": {
+                    "BLK": "159.83673869",
+                    "BTC": "0.00005959",
+                    "USDT": "0.00002625",
+                    "XMR": "0.18719303"
+                    },
+                "margin": {
+                    "BTC": "0.03019227"
+                    }
+                }
+            expected = {
+                    "info": {
+                        "exchange": {
+                            "BLK": "159.83673869",
+                            "BTC": "0.00005959",
+                            "USDT": "0.00002625",
+                            "XMR": "0.18719303"
+                            },
+                        "margin": {
+                            "BTC": "0.03019227"
+                            }
+                        },
+                    "exchange": {
+                        "BLK": D("159.83673869"),
+                        "BTC": D("0.00005959"),
+                        "USDT": D("0.00002625"),
+                        "XMR": D("0.18719303")
+                        },
+                    "margin": {"BTC": D("0.03019227")},
+                    "BLK": {"exchange": D("159.83673869")},
+                    "BTC": {"exchange": D("0.00005959"), "margin": D("0.03019227")},
+                    "USDT": {"exchange": D("0.00002625")},
+                    "XMR": {"exchange": D("0.18719303")}
+                    } 
+            result = self.s.fetch_balance_per_type()
+            self.assertEqual(expected, result)
+
+    def test_fetch_all_balances(self):
+        import json
+        with mock.patch.object(self.s, "load_markets") as load_markets,\
+                mock.patch.object(self.s, "privatePostGetMarginPosition") as margin_balance,\
+                mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balance,\
+                mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balance_per_type:
+
+            with open("test_samples/poloniexETest.test_fetch_all_balances.1.json") as f:
+                balance.return_value = json.load(f)
+            with open("test_samples/poloniexETest.test_fetch_all_balances.2.json") as f:
+                margin_balance.return_value = json.load(f)
+            with open("test_samples/poloniexETest.test_fetch_all_balances.3.json") as f:
+                balance_per_type.return_value = json.load(f)
+
+            result = self.s.fetch_all_balances()
+            expected_doge = {
+                    "total": D("-12779.79821852"),
+                    "exchange_used": D("0E-8"),
+                    "exchange_total": D("0E-8"),
+                    "exchange_free": D("0E-8"),
+                    "margin_available": 0,
+                    "margin_in_position": 0,
+                    "margin_borrowed": D("12779.79821852"),
+                    "margin_total": D("-12779.79821852"),
+                    "margin_pending_gain": 0,
+                    "margin_lending_fees": D("-9E-8"),
+                    "margin_pending_base_gain": D("0.00024059"),
+                    "margin_position_type": "short",
+                    "margin_liquidation_price": D("0.00000246"),
+                    "margin_borrowed_base_price": D("0.00599149"),
+                    "margin_borrowed_base_currency": "BTC"
+                    } 
+            expected_btc = {"total": D("0.05432165"),
+                    "exchange_used": D("0E-8"),
+                    "exchange_total": D("0.00005959"),
+                    "exchange_free": D("0.00005959"),
+                    "margin_available": D("0.03019227"),
+                    "margin_in_position": D("0.02406979"),
+                    "margin_borrowed": 0,
+                    "margin_total": D("0.05426206"),
+                    "margin_pending_gain": D("0.00093955"),
+                    "margin_lending_fees": 0,
+                    "margin_pending_base_gain": 0,
+                    "margin_position_type": None,
+                    "margin_liquidation_price": 0,
+                    "margin_borrowed_base_price": 0,
+                    "margin_borrowed_base_currency": None
+                    }
+            expected_xmr = {"total": D("0.18719303"),
+                    "exchange_used": D("0E-8"),
+                    "exchange_total": D("0.18719303"),
+                    "exchange_free": D("0.18719303"),
+                    "margin_available": 0,
+                    "margin_in_position": 0,
+                    "margin_borrowed": 0,
+                    "margin_total": 0,
+                    "margin_pending_gain": 0,
+                    "margin_lending_fees": 0,
+                    "margin_pending_base_gain": 0,
+                    "margin_position_type": None,
+                    "margin_liquidation_price": 0,
+                    "margin_borrowed_base_price": 0,
+                    "margin_borrowed_base_currency": None
+                    } 
+            self.assertEqual(expected_xmr, result["XMR"])
+            self.assertEqual(expected_doge, result["DOGE"])
+            self.assertEqual(expected_btc, result["BTC"])
+
+    def test_create_margin_order(self):
+        with self.assertRaises(market.ExchangeError):
+            self.s.create_margin_order("FOO", "market", "buy", "10")
+
+        with mock.patch.object(self.s, "load_markets") as load_markets,\
+                mock.patch.object(self.s, "privatePostMarginBuy") as margin_buy,\
+                mock.patch.object(self.s, "privatePostMarginSell") as margin_sell,\
+                mock.patch.object(self.s, "market") as market_mock,\
+                mock.patch.object(self.s, "price_to_precision") as ptp,\
+                mock.patch.object(self.s, "amount_to_precision") as atp:
+
+            margin_buy.return_value = {
+                    "orderNumber": 123
+                    }
+            margin_sell.return_value = {
+                    "orderNumber": 456
+                    }
+            market_mock.return_value = { "id": "BTC_ETC", "symbol": "BTC_ETC" }
+            ptp.return_value = D("0.1")
+            atp.return_value = D("12")
+
+            order = self.s.create_margin_order("BTC_ETC", "margin", "buy", "12", price="0.1")
+            self.assertEqual(123, order["id"])
+            margin_buy.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")})
+            margin_sell.assert_not_called()
+            margin_buy.reset_mock()
+            margin_sell.reset_mock()
+
+            order = self.s.create_margin_order("BTC_ETC", "margin", "sell", "12", lending_rate="0.01", price="0.1")
+            self.assertEqual(456, order["id"])
+            margin_sell.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12"), "lendingRate": "0.01"})
+            margin_buy.assert_not_called()
+
+    def test_create_exchange_order(self):
+        with mock.patch.object(market.ccxt.poloniex, "create_order") as create_order:
+            self.s.create_order("symbol", "type", "side", "amount", price="price", params="params")
+
+            create_order.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
+
 @unittest.skipUnless("unit" in limits, "Unit skipped")
 class PortfolioTest(WebMockTestCase):
-    def fill_data(self):
-        if self.json_response is not None:
-            portfolio.Portfolio.data = self.json_response
-
     def setUp(self):
         super(PortfolioTest, self).setUp()
 
-        with open("test_portfolio.json") as example:
+        with open("test_samples/test_portfolio.json") as example:
             self.json_response = example.read()
 
-        self.wm.get(portfolio.Portfolio.URL, text=self.json_response)
+        self.wm.get(market.Portfolio.URL, text=self.json_response)
 
-    def test_get_cryptoportfolio(self):
-        self.wm.get(portfolio.Portfolio.URL, [
+    @mock.patch.object(market.Portfolio, "parse_cryptoportfolio")
+    def test_get_cryptoportfolio(self, parse_cryptoportfolio):
+        self.wm.get(market.Portfolio.URL, [
             {"text":'{ "foo": "bar" }', "status_code": 200},
             {"text": "System Error", "status_code": 500},
             {"exc": requests.exceptions.ConnectTimeout},
             ])
-        portfolio.Portfolio.get_cryptoportfolio(self.m)
-        self.assertIn("foo", portfolio.Portfolio.data)
-        self.assertEqual("bar", portfolio.Portfolio.data["foo"])
+        market.Portfolio.get_cryptoportfolio()
+        self.assertIn("foo", market.Portfolio.data)
+        self.assertEqual("bar", market.Portfolio.data["foo"])
         self.assertTrue(self.wm.called)
         self.assertEqual(1, self.wm.call_count)
-        self.m.report.log_error.assert_not_called()
-        self.m.report.log_http_request.assert_called_once()
-        self.m.report.log_http_request.reset_mock()
-
-        portfolio.Portfolio.get_cryptoportfolio(self.m)
-        self.assertIsNone(portfolio.Portfolio.data)
+        market.Portfolio.report.log_error.assert_not_called()
+        market.Portfolio.report.log_http_request.assert_called_once()
+        parse_cryptoportfolio.assert_called_once_with()
+        market.Portfolio.report.log_http_request.reset_mock()
+        parse_cryptoportfolio.reset_mock()
+        market.Portfolio.data = None
+
+        market.Portfolio.get_cryptoportfolio()
+        self.assertIsNone(market.Portfolio.data)
         self.assertEqual(2, self.wm.call_count)
-        self.m.report.log_error.assert_not_called()
-        self.m.report.log_http_request.assert_called_once()
-        self.m.report.log_http_request.reset_mock()
-
+        parse_cryptoportfolio.assert_not_called()
+        market.Portfolio.report.log_error.assert_not_called()
+        market.Portfolio.report.log_http_request.assert_called_once()
+        market.Portfolio.report.log_http_request.reset_mock()
+        parse_cryptoportfolio.reset_mock()
+
+        market.Portfolio.data = "Foo"
+        market.Portfolio.get_cryptoportfolio()
+        self.assertEqual(2, self.wm.call_count)
+        parse_cryptoportfolio.assert_not_called()
 
-        portfolio.Portfolio.data = "Foo"
-        portfolio.Portfolio.get_cryptoportfolio(self.m)
-        self.assertEqual("Foo", portfolio.Portfolio.data)
+        market.Portfolio.get_cryptoportfolio(refetch=True)
+        self.assertEqual("Foo", market.Portfolio.data)
         self.assertEqual(3, self.wm.call_count)
-        self.m.report.log_error.assert_called_once_with("get_cryptoportfolio",
+        market.Portfolio.report.log_error.assert_called_once_with("get_cryptoportfolio",
                 exception=mock.ANY)
-        self.m.report.log_http_request.assert_not_called()
+        market.Portfolio.report.log_http_request.assert_not_called()
 
     def test_parse_cryptoportfolio(self):
-        portfolio.Portfolio.parse_cryptoportfolio(self.m)
+        market.Portfolio.data = store.json.loads(self.json_response, parse_int=D,
+                parse_float=D)
+        market.Portfolio.parse_cryptoportfolio()
 
         self.assertListEqual(
                 ["medium", "high"],
-                list(portfolio.Portfolio.liquidities.keys()))
+                list(market.Portfolio.liquidities.keys()))
 
-        liquidities = portfolio.Portfolio.liquidities
+        liquidities = market.Portfolio.liquidities
         self.assertEqual(10, len(liquidities["medium"].keys()))
         self.assertEqual(10, len(liquidities["high"].keys()))
 
@@ -206,94 +528,64 @@ class PortfolioTest(WebMockTestCase):
                 'XCP':  (D("0.1"), "long"),
                 }
         self.assertDictEqual(expected, liquidities["medium"][date])
-        self.assertEqual(portfolio.datetime(2018, 1, 15), portfolio.Portfolio.last_date)
-
-        self.m.report.log_http_request.assert_called_once_with("GET",
-                portfolio.Portfolio.URL, None, mock.ANY, mock.ANY)
-        self.m.report.log_http_request.reset_mock()
-
-        # It doesn't refetch the data when available
-        portfolio.Portfolio.parse_cryptoportfolio(self.m)
-        self.m.report.log_http_request.assert_not_called()
-
-        self.assertEqual(1, self.wm.call_count)
-
-        portfolio.Portfolio.parse_cryptoportfolio(self.m, refetch=True)
-        self.assertEqual(2, self.wm.call_count)
-        self.m.report.log_http_request.assert_called_once()
-
-    def test_repartition(self):
-        expected_medium = {
-                'BTC':   (D("1.1102e-16"), "long"),
-                'USDT':  (D("0.1"), "long"),
-                'ETC':   (D("0.1"), "long"),
-                'FCT':   (D("0.1"), "long"),
-                'OMG':   (D("0.1"), "long"),
-                'STEEM': (D("0.1"), "long"),
-                'STRAT': (D("0.1"), "long"),
-                'XEM':   (D("0.1"), "long"),
-                'XMR':   (D("0.1"), "long"),
-                'XVC':   (D("0.1"), "long"),
-                'ZRX':   (D("0.1"), "long"),
-                }
-        expected_high = {
-                'USDT': (D("0.1226"), "long"),
-                'BTC':  (D("0.1429"), "long"),
-                'ETC':  (D("0.1127"), "long"),
-                'ETH':  (D("0.1569"), "long"),
-                'FCT':  (D("0.3341"), "long"),
-                'GAS':  (D("0.1308"), "long"),
+        self.assertEqual(portfolio.datetime(2018, 1, 15), market.Portfolio.last_date)
+
+    @mock.patch.object(market.Portfolio, "get_cryptoportfolio")
+    def test_repartition(self, get_cryptoportfolio):
+        market.Portfolio.liquidities = {
+                "medium": {
+                    "2018-03-01": "medium_2018-03-01",
+                    "2018-03-08": "medium_2018-03-08",
+                    },
+                "high": {
+                    "2018-03-01": "high_2018-03-01",
+                    "2018-03-08": "high_2018-03-08",
+                    }
                 }
+        market.Portfolio.last_date = "2018-03-08"
 
-        self.assertEqual(expected_medium, portfolio.Portfolio.repartition(self.m))
-        self.assertEqual(expected_medium, portfolio.Portfolio.repartition(self.m, liquidity="medium"))
-        self.assertEqual(expected_high, portfolio.Portfolio.repartition(self.m, liquidity="high"))
-
-        self.assertEqual(1, self.wm.call_count)
-
-        portfolio.Portfolio.repartition(self.m)
-        self.assertEqual(1, self.wm.call_count)
-
-        portfolio.Portfolio.repartition(self.m, refetch=True)
-        self.assertEqual(2, self.wm.call_count)
-        self.m.report.log_http_request.assert_called()
-        self.assertEqual(2, self.m.report.log_http_request.call_count)
+        self.assertEqual("medium_2018-03-08", market.Portfolio.repartition())
+        get_cryptoportfolio.assert_called_once_with()
+        self.assertEqual("medium_2018-03-08", market.Portfolio.repartition(liquidity="medium"))
+        self.assertEqual("high_2018-03-08", market.Portfolio.repartition(liquidity="high"))
 
-    @mock.patch.object(portfolio.time, "sleep")
-    @mock.patch.object(portfolio.Portfolio, "repartition")
-    def test_wait_for_recent(self, repartition, sleep):
+    @mock.patch.object(market.time, "sleep")
+    @mock.patch.object(market.Portfolio, "get_cryptoportfolio")
+    def test_wait_for_recent(self, get_cryptoportfolio, sleep):
         self.call_count = 0
-        def _repartition(market, refetch):
-            self.assertEqual(self.m, market)
-            self.assertTrue(refetch)
+        def _get(refetch=False):
+            if self.call_count != 0:
+                self.assertTrue(refetch)
+            else:
+                self.assertFalse(refetch)
             self.call_count += 1
-            portfolio.Portfolio.last_date = portfolio.datetime.now()\
-                - portfolio.timedelta(10)\
-                + portfolio.timedelta(self.call_count)
-        repartition.side_effect = _repartition
+            market.Portfolio.last_date = store.datetime.now()\
+                - store.timedelta(10)\
+                + store.timedelta(self.call_count)
+        get_cryptoportfolio.side_effect = _get
 
-        portfolio.Portfolio.wait_for_recent(self.m)
+        market.Portfolio.wait_for_recent()
         sleep.assert_called_with(30)
         self.assertEqual(6, sleep.call_count)
-        self.assertEqual(7, repartition.call_count)
-        self.m.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
+        self.assertEqual(7, get_cryptoportfolio.call_count)
+        market.Portfolio.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
 
         sleep.reset_mock()
-        repartition.reset_mock()
-        portfolio.Portfolio.last_date = None
+        get_cryptoportfolio.reset_mock()
+        market.Portfolio.last_date = None
         self.call_count = 0
-        portfolio.Portfolio.wait_for_recent(self.m, delta=15)
+        market.Portfolio.wait_for_recent(delta=15)
         sleep.assert_not_called()
-        self.assertEqual(1, repartition.call_count)
+        self.assertEqual(1, get_cryptoportfolio.call_count)
 
         sleep.reset_mock()
-        repartition.reset_mock()
-        portfolio.Portfolio.last_date = None
+        get_cryptoportfolio.reset_mock()
+        market.Portfolio.last_date = None
         self.call_count = 0
-        portfolio.Portfolio.wait_for_recent(self.m, delta=1)
+        market.Portfolio.wait_for_recent(delta=1)
         sleep.assert_called_with(30)
         self.assertEqual(9, sleep.call_count)
-        self.assertEqual(10, repartition.call_count)
+        self.assertEqual(10, get_cryptoportfolio.call_count)
 
 @unittest.skipUnless("unit" in limits, "Unit skipped")
 class AmountTest(WebMockTestCase):
@@ -736,7 +1028,7 @@ class MarketTest(WebMockTestCase):
         self.assertEqual("Foo", m.fetch_fees())
         self.ccxt.fetch_fees.assert_not_called()
 
-    @mock.patch.object(portfolio.Portfolio, "repartition")
+    @mock.patch.object(market.Portfolio, "repartition")
     @mock.patch.object(market.Market, "get_ticker")
     @mock.patch.object(market.TradeStore, "compute_trades")
     def test_prepare_trades(self, compute_trades, get_ticker, repartition):
@@ -787,7 +1079,7 @@ class MarketTest(WebMockTestCase):
             m.report.log_balances.assert_called_once_with(tag="tag")
 
 
-    @mock.patch.object(portfolio.time, "sleep")
+    @mock.patch.object(market.time, "sleep")
     @mock.patch.object(market.TradeStore, "all_orders")
     def test_follow_orders(self, all_orders, time_mock):
         for debug, sleep in [
@@ -1382,7 +1674,7 @@ class BalanceStoreTest(WebMockTestCase):
         self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store.currencies()))
         self.m.report.log_balances.assert_called_with(tag="foo")
 
-    @mock.patch.object(portfolio.Portfolio, "repartition")
+    @mock.patch.object(market.Portfolio, "repartition")
     def test_dispatch_assets(self, repartition):
         self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance
 
@@ -1399,7 +1691,7 @@ class BalanceStoreTest(WebMockTestCase):
         repartition.return_value = repartition_hash
 
         amounts = balance_store.dispatch_assets(portfolio.Amount("BTC", "11.1"))
-        repartition.assert_called_with(self.m, liquidity="medium")
+        repartition.assert_called_with(liquidity="medium")
         self.assertIn("XEM", balance_store.currencies())
         self.assertEqual(D("2.6"), amounts["BTC"].value)
         self.assertEqual(D("7.5"), amounts["XEM"].value)
@@ -3022,11 +3314,8 @@ class MainTest(WebMockTestCase):
                 self.assertIsInstance(m, market.Market)
                 self.assertTrue(m.debug)
 
-    def test_main(self):
-        with mock.patch("main.parse_args") as parse_args,\
-                mock.patch("main.parse_config") as parse_config,\
-                mock.patch("main.fetch_markets") as fetch_markets,\
-                mock.patch("market.Market") as market_mock,\
+    def test_process(self):
+        with mock.patch("market.Market") as market_mock,\
                 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
 
             args_mock = mock.Mock()
@@ -3036,6 +3325,29 @@ class MainTest(WebMockTestCase):
             args_mock.debug = "debug"
             args_mock.before = "before"
             args_mock.after = "after"
+            self.assertEqual("", stdout_mock.getvalue())
+
+            main.process("config", 1, "report_path", args_mock)
+
+            market_mock.from_config.assert_has_calls([
+                mock.call("config", debug="debug", user_id=1, report_path="report_path"),
+                mock.call().process("action", before="before", after="after"),
+                ])
+
+            with self.subTest(exception=True):
+                market_mock.from_config.side_effect = Exception("boo")
+                main.process("config", 1, "report_path", args_mock)
+                self.assertEqual("Exception: boo\n", stdout_mock.getvalue())
+
+    def test_main(self):
+        with mock.patch("main.parse_args") as parse_args,\
+                mock.patch("main.parse_config") as parse_config,\
+                mock.patch("main.fetch_markets") as fetch_markets,\
+                mock.patch("main.process") as process:
+
+            args_mock = mock.Mock()
+            args_mock.config = "config"
+            args_mock.user = "user"
             parse_args.return_value = args_mock
 
             parse_config.return_value = ["pg_config", "report_path"]
@@ -3048,21 +3360,12 @@ class MainTest(WebMockTestCase):
             parse_config.assert_called_with("config")
             fetch_markets.assert_called_with("pg_config", "user")
 
-            self.assertEqual(2, market_mock.from_config.call_count)
-            market_mock.from_config.assert_has_calls([
-                mock.call("config1", debug="debug", user_id=1, report_path="report_path"),
-                mock.call().process("action", before="before", after="after"),
-                mock.call("config2", debug="debug", user_id=2, report_path="report_path"),
-                mock.call().process("action", before="before", after="after")
+            self.assertEqual(2, process.call_count)
+            process.assert_has_calls([
+                mock.call("config1", 1, "report_path", args_mock),
+                mock.call("config2", 2, "report_path", args_mock),
                 ])
 
-            self.assertEqual("", stdout_mock.getvalue())
-
-            with self.subTest(exception=True):
-                market_mock.from_config.side_effect = Exception("boo")
-                main.main(["Foo", "Bar"])
-                self.assertEqual("Exception: boo\nException: boo\n", stdout_mock.getvalue())
-
     @mock.patch.object(main.sys, "exit")
     @mock.patch("main.configparser")
     @mock.patch("main.os")
@@ -3183,7 +3486,7 @@ class ProcessorTest(WebMockTestCase):
 
             processor.run_action("wait_for_recent", "bar", "baz")
 
-            method_mock.assert_called_with(self.m, foo="bar")
+            method_mock.assert_called_with(foo="bar")
 
     def test_select_step(self):
         processor = market.Processor(self.m)
@@ -3225,7 +3528,7 @@ class ProcessorTest(WebMockTestCase):
         processor = market.Processor(m)
 
         method, arguments = processor.method_arguments("wait_for_recent")
-        self.assertEqual(portfolio.Portfolio.wait_for_recent, method)
+        self.assertEqual(market.Portfolio.wait_for_recent, method)
         self.assertEqual(["delta"], arguments)
 
         method, arguments = processor.method_arguments("prepare_trades")
@@ -3408,7 +3711,7 @@ class AcceptanceTest(WebMockTestCase):
         market = mock.Mock()
         market.fetch_all_balances.return_value = fetch_balance
         market.fetch_ticker.side_effect = fetch_ticker
-        with mock.patch.object(portfolio.Portfolio, "repartition", return_value=repartition):
+        with mock.patch.object(market.Portfolio, "repartition", return_value=repartition):
             # Action 1
             helper.prepare_trades(market)
 
@@ -3487,7 +3790,7 @@ class AcceptanceTest(WebMockTestCase):
                     "amount": "10", "total": "1"
                     }
                 ]
-        with mock.patch.object(portfolio.time, "sleep") as sleep:
+        with mock.patch.object(market.time, "sleep") as sleep:
             # Action 4
             helper.follow_orders(verbose=False)
 
@@ -3528,7 +3831,7 @@ class AcceptanceTest(WebMockTestCase):
                 }
         market.fetch_all_balances.return_value = fetch_balance
 
-        with mock.patch.object(portfolio.Portfolio, "repartition", return_value=repartition):
+        with mock.patch.object(market.Portfolio, "repartition", return_value=repartition):
             # Action 5
             helper.prepare_trades(market, only="acquire", compute_value="average")
 
@@ -3600,7 +3903,7 @@ class AcceptanceTest(WebMockTestCase):
         # TODO
         # portfolio.TradeStore.run_orders()
 
-        with mock.patch.object(portfolio.time, "sleep") as sleep:
+        with mock.patch.object(market.time, "sleep") as sleep:
             # Action 8
             helper.follow_orders(verbose=False)