tradingSystem/scripts/test_batch49_units.py

221 lines
12 KiB
Python

"""持仓、批次及交易指令页面的策略隔离。"""
import unit_test_guard # noqa: F401
import copy
import unittest
from unittest.mock import patch
from test_wiring import install_fakes
from app.core import strategy_book as books
from app.services import portfolio
from config.settings import settings
class PositionGroupsTests(unittest.TestCase):
def setUp(self):
install_fakes(prices={'600000.SH': 12}, positions=[
{'ts_code': '600000.SH', 'total_qty': 100, 'avail_qty': 100, 'avg_cost': 10}])
self.original = portfolio.positions_view()
lots = patch.object(portfolio.pms_repo, 'list_lots', side_effect=lambda *a, **k:
[{'qty': 100, 'open_price': 10, 'realized_pnl': 0}] if books.CURRENT.get() == 'original'
else [{'qty': 300, 'open_price': 11, 'realized_pnl': 0}])
lots.start(); self.addCleanup(lots.stop)
def test_unmigrated_micro_is_empty_without_query(self):
before = copy.deepcopy(self.original)
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
patch.object(portfolio, 'positions_view') as read:
groups = portfolio.position_groups(self.original)
read.assert_not_called()
self.assertEqual(groups[0]['totals']['market_value'], 1200)
self.assertEqual(groups[1]['held'], [])
self.assertTrue(groups[1]['ready'])
self.assertEqual(self.original, before)
def test_same_stock_keeps_separate_quantity_cost_and_profit(self):
def read(**kwargs):
self.assertEqual(books.CURRENT.get(), 'micro30')
return [{'ts_code': '600000.SH', 'total_qty': 300, 'avg_cost': 11}]
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(portfolio.pms_repo, 'list_positions', side_effect=read):
groups = portfolio.position_groups(self.original)
self.assertEqual([g['held'][0]['total_qty'] for g in groups], [100, 300])
self.assertEqual([g['held'][0]['avg_cost'] for g in groups], [10, 11])
self.assertEqual([g['totals']['pnl'] for g in groups], [200, 300])
self.assertEqual([g['held'][0]['book_id'] for g in groups], ['original', 'micro30'])
self.assertEqual(books.CURRENT.get(), 'original')
def test_missing_quote_does_not_claim_zero_profit(self):
self.original['price_missing'] = ['600000.SH']
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False):
groups = portfolio.position_groups(self.original)
self.assertIsNone(groups[0]['totals']['pnl'])
self.assertEqual(groups[0]['price_missing'], ['600000.SH'])
def test_query_failure_is_not_empty_position(self):
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(portfolio, 'positions_view', side_effect=RuntimeError('offline')):
groups = portfolio.position_groups(self.original)
self.assertTrue(groups[0]['ready'])
self.assertFalse(groups[1]['ready'])
self.assertIsNone(groups[1]['totals']['market_value'])
self.assertIsNone(groups[1]['totals']['pnl'])
self.assertEqual(books.CURRENT.get(), 'original')
def test_lots_same_code_follow_selected_book(self):
def read(code, status):
return [{'ts_code': code, 'book_id': books.CURRENT.get(), 'status': status}]
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(portfolio.pms_repo, 'list_lots', side_effect=read):
for book in ('original', 'micro30'):
rows = portfolio.position_lots('600000.SH', book, None)
self.assertEqual(rows[0]['book_id'], book)
self.assertIsNone(rows[0]['status'])
self.assertEqual(books.CURRENT.get(), 'original')
def test_unmigrated_micro_lots_never_read_original(self):
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
patch.object(portfolio.pms_repo, 'list_lots') as read:
self.assertEqual(portfolio.position_lots('600000.SH', 'micro30', None), [])
read.assert_not_called()
def test_unknown_book_is_rejected(self):
with self.assertRaises(ValueError):
portfolio.position_lots('600000.SH', 'all', None)
def test_api_passes_selected_book_and_all_statuses(self):
from app.web.main import api_lots
with patch.object(portfolio, 'position_lots', return_value=[]) as read:
api_lots('600000.SH', status='', book_id='micro30')
read.assert_called_once_with('600000.SH', 'micro30', status=None)
class InstructionBooksTests(unittest.TestCase):
def setUp(self):
from app.web import main
self.api = main
def test_list_scopes_both_books_and_restores_caller(self):
from app.services import dispatcher
def read(**kw):
self.assertEqual(kw, {'statuses': ['DISPATCHED', 'CONFIRMED'],
'limit': 200, 'include_archived': False})
return [{'instruction_id': 'same-stock-'+books.CURRENT.get(),
'ts_code': '600000.SH', 'book_id': books.CURRENT.get(),
'status': 'CONFIRMED', 'qty': 100 if books.CURRENT.get()=='original' else 300}]
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(self.api.pms_repo, 'list_instructions', side_effect=read), \
patch.object(dispatcher, 'mode', return_value='ws'):
with books.scope('micro30'):
rows = [self.api.api_instructions(status='DISPATCHED,CONFIRMED', limit=200,
include_archived=False, book_id=b)['data'][0] for b in ('original','micro30')]
self.assertEqual(books.CURRENT.get(), 'micro30')
self.assertEqual([r['qty'] for r in rows], [100,300])
self.assertEqual([r['book_id'] for r in rows], ['original','micro30'])
def test_unmigrated_micro_never_lists_original(self):
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
patch.object(self.api.pms_repo, 'list_instructions') as read:
result = self.api.api_instructions(status=None, include_archived=False, book_id='micro30')
self.assertEqual(result, {'ok': True, 'data': []})
read.assert_not_called()
def test_read_failure_is_not_successful_empty_and_restores_scope(self):
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(self.api.pms_repo, 'list_instructions', side_effect=RuntimeError('offline')):
result = self.api.api_instructions(status=None, include_archived=False, book_id='micro30')
self.assertFalse(result['ok'])
self.assertEqual(books.CURRENT.get(), 'original')
def test_cancel_uses_selected_book_and_existing_cancel_flow(self):
from app.services import executor
def cancel(iid, reason):
self.assertEqual(iid, 'ROT_test')
self.assertEqual(reason, '页面人工撤销')
return {'ok': True, 'book': books.CURRENT.get(), 'cancel_pending': True}
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(executor, 'cancel_instruction', side_effect=cancel), \
patch.object(self.api.pms_repo, 'insert_op_log') as log:
for book in ('original','micro30'):
result = self.api.api_cancel_instruction('ROT_test', payload={}, book_id=book)
self.assertEqual(result['book'], book)
self.assertTrue(result['cancel_pending'])
self.assertEqual(log.call_args.kwargs['params']['book_id'], book)
self.assertEqual(books.CURRENT.get(), 'original')
def test_wrong_book_does_not_fall_back_or_cancel_other_book(self):
from app.services import dispatcher, execution_orders
from contextlib import nullcontext
seen = []
def read(iid):
seen.append(books.CURRENT.get())
return None # 指令在另一个账本,本范围内不存在。
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(self.api.pms_repo, 'get_instruction', side_effect=read), \
patch.object(execution_orders, 'account_guard', side_effect=nullcontext), \
patch.object(self.api.pms_repo, 'insert_op_log'), \
patch.object(dispatcher, 'cancel') as cancel:
result = self.api.api_cancel_instruction('ROT_test', payload={}, book_id='micro30')
self.assertFalse(result['ok'])
self.assertEqual(seen, ['micro30'])
cancel.assert_not_called()
def test_unmigrated_micro_cannot_cancel_original(self):
from app.services import executor
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
patch.object(executor, 'cancel_instruction') as cancel, \
patch.object(self.api.pms_repo, 'insert_op_log'):
result = self.api.api_cancel_instruction('ROT_test', payload={}, book_id='micro30')
self.assertFalse(result['ok'])
cancel.assert_not_called()
class PositionCurrentTechTests(unittest.TestCase):
def setUp(self):
install_fakes()
from app.web import main
from app.services import tech_service, consensus_service, logic_state_service, command_service, risk_exit
self.main = main
self.row = {'ts_code': '601126.SH', 'total_qty': 2700, 'tech': {'stance': '看多', 'data_date': 20261112}}
self.enterContext(patch.object(portfolio, 'positions_view', return_value={'positions': [self.row]}))
self.enterContext(patch.object(portfolio, 'position_groups', return_value=[]))
self.enterContext(patch.object(risk_exit, 'decorate_positions'))
self.enterContext(patch.object(command_service, 'effective_stock_params', return_value={}))
self.enterContext(patch.object(command_service, 'attach_user_prices'))
self.enterContext(patch.object(logic_state_service, 'decorate_positions'))
self.enterContext(patch.object(logic_state_service, 'state_map', return_value={}))
self.read = self.enterContext(patch.object(tech_service, 'read_states_for'))
def decorate(rows, **kwargs):
self.seen = kwargs['tech_states']
for row in rows:
row['consensus_blocks'] = {'tech': self.seen.get(row['ts_code']) or {'stance': '无读数'}}
self.enterContext(patch.object(consensus_service, 'decorate_positions', side_effect=decorate))
self.old = self.enterContext(patch.object(tech_service, 'state_map', side_effect=AssertionError('不能回退旧映射')))
def test_current_date_replaces_older_bullish_map_in_list_and_detail_fields(self):
latest = {'stance': '中性', 'phase': '分歧', 'data_date': 20261113}
self.read.return_value = {'601126.SH': latest}
result = self.main.api_positions()
self.assertTrue(result['ok'])
self.assertEqual(result['positions'][0]['tech'], latest)
self.assertEqual(result['positions'][0]['dims']['tech'], '中性')
self.assertEqual(self.seen['601126.SH'], latest)
self.old.assert_not_called()
def test_read_failure_does_not_restore_old_bullish_map(self):
self.read.side_effect = ValueError('isolated read failed')
result = self.main.api_positions()
self.assertTrue(result['ok'])
self.assertIsNone(result['positions'][0]['tech'])
self.assertEqual(result['positions'][0]['dims']['tech'], '无读数')
self.assertEqual(self.seen, {})
self.old.assert_not_called()
def test_expired_current_data_does_not_restore_old_bullish_map(self):
self.read.return_value = {}
result = self.main.api_positions()
self.assertEqual(result['positions'][0]['dims']['tech'], '无读数')
self.old.assert_not_called()
if __name__ == '__main__':
unittest.main()