from decimal import Decimal import time from grid_trading.domain.models import Instrument def test_formatters_render_money_percent_and_empty_values(): from grid_trading.ui.formatters import format_money, format_percent, format_price, format_quantity assert format_money(Decimal("1234.5")) == "1,234.50" assert format_price(Decimal("3.956")) == "3.96" assert format_percent(Decimal("0.1234")) == "12.34%" assert format_quantity(1200) == "1,200" assert format_money(None) == "-" def test_main_window_can_be_constructed_offscreen(tmp_path, monkeypatch): monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") from PySide6.QtWidgets import QApplication, QPushButton from grid_trading.services.trading_service import TradingService from grid_trading.ui.main_window import MainWindow app = QApplication.instance() or QApplication([]) service = TradingService(tmp_path / "grid.db") window = MainWindow(service) assert window.windowTitle() == "Grid Trading Manager" assert window.holdings_table.columnCount() > 0 assert any(button.text() == "刷新行情" for button in window.findChildren(QPushButton)) window.close() service.close() app.processEvents() def test_quote_refresh_does_not_block_main_window(tmp_path, monkeypatch): monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") from PySide6.QtWidgets import QApplication from grid_trading.services.trading_service import TradingService from grid_trading.ui.main_window import MainWindow class SlowQuoteProvider: def fetch_quotes(self, instruments): time.sleep(0.3) return {} app = QApplication.instance() or QApplication([]) service = TradingService(tmp_path / "grid.db", quote_provider=SlowQuoteProvider()) service.ensure_defaults() service.add_instrument(Instrument(id=None, code="000001", name="Ping An Bank")) window = MainWindow(service) started_at = time.perf_counter() window._refresh_quotes() elapsed = time.perf_counter() - started_at assert elapsed < 0.15 deadline = time.perf_counter() + 2 while getattr(window, "_quote_thread", None) is not None and time.perf_counter() < deadline: app.processEvents() time.sleep(0.01) assert getattr(window, "_quote_thread", None) is None window.close() service.close() app.processEvents()