import json import time from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timezone from threading import Event from unittest.mock import Mock, patch, mock_open import pytest import fo import fo_quotes @pytest.fixture(autouse=True) def isolate_snapshot_downloads(monkeypatch): import database histories = {} get_cached = database.get_app_result_cache save_cached = database.save_app_result_cache def get_history(key): return histories.get(key) if key.startswith("fo_chart:") else get_cached(key) def save_history(key, result, saved_at=None): if key.startswith("fo_chart:"): histories[key] = {"result": result, "saved_at": saved_at} else: save_cached(key, result, saved_at) monkeypatch.setattr(database, "get_app_result_cache", get_history) monkeypatch.setattr(database, "save_app_result_cache", save_history) fo_quotes._payloads.clear() yield fo_quotes._payloads.clear() def contract(**updates): return {"exchange": "NSE", "underlying": "NIFTY", "underlying_type": "INDEX", "expiry": "2099-10-29", "strike": 25000, "option_type": "PE", "lot_size": 25, "tick_size": 0.05, **updates} def payload(**updates): return {"instrument_type": "OPTION", "contract": contract(), "lots": 2, "direction": "LONG", "entry_price": 100, "price_source": "manual", **updates} def test_put_buy_is_long_premium_and_uses_lots_not_client_shares(): result = fo.validate_trade(payload(shares=9999)) assert result["direction"] == "LONG" assert result["shares"] == 50 assert json.loads(result["contract_data"])["option_type"] == "PE" @pytest.mark.parametrize("updates", [ {"lots": 0}, {"lots": 1.5}, {"lots": True}, {"entry_price": "nan"}, {"entry_price": "inf"}, {"entry_price": -1}, {"entry_price": 100.01}, {"direction": "BEARISH"}, {"stop_loss": 101}, {"target": 99}, {"margin_estimate": "nan"}, {"contract": None}, ]) def test_manual_trade_rejects_invalid_inputs(updates): with pytest.raises(ValueError): fo.validate_trade(payload(**updates)) @pytest.mark.parametrize("updates", [ {"underlying": "