Spaces:
Sleeping
Sleeping
Download tests/test_dhan_client.py from V1deh/PaperTrade: direct link, hf CLI and curl.
- Browser
- Download file 29.2 kB
-
https://huggingface.co/spaces/V1deh/PaperTrade/resolve/main/tests/test_dhan_client.py
- Command line
-
hf download hf://spaces/V1deh/PaperTrade/tests/test_dhan_client.py
-
curl -L -o test_dhan_client.py https://huggingface.co/spaces/V1deh/PaperTrade/resolve/main/tests/test_dhan_client.py
29.2 kB
| import asyncio | |
| import json | |
| import time | |
| import unittest | |
| import types | |
| from datetime import datetime, timezone | |
| from unittest.mock import Mock, MagicMock, patch | |
| import dhan_client | |
| from dhan_auth import DhanAuthError | |
| class DhanClientTests(unittest.TestCase): | |
| def setUp(self): | |
| self.session = Mock() | |
| self.client = dhan_client.DhanDataClient("test-client", "secret-token", enabled=True, session=self.session) | |
| self.client._instruments = {"RELIANCE.NS": "2885", "TCS.NS": "11536"} | |
| self.client._instruments_at = time.time() | |
| self.cache_get = patch.object(self.client, "_cache_get", return_value=None) | |
| self.cache_put = patch.object(self.client, "_cache_put") | |
| self.cache_get.start() | |
| self.cache_put.start() | |
| self.addCleanup(self.cache_get.stop) | |
| self.addCleanup(self.cache_put.stop) | |
| self.addCleanup(self.client.stop) | |
| def response(self, payload, status=200): | |
| response = Mock(status_code=status) | |
| response.json.return_value = payload | |
| self.session.request.return_value = response | |
| return response | |
| def tick(self, **updates): | |
| packet = {"security_id": "2885", "exchange_segment": 1, "LTP": "2500.25", | |
| "LTT": time.time(), "high": "2510", "low": "2490", "volume": 1000} | |
| packet.update(updates) | |
| return packet | |
| def test_disabled_client_does_not_use_network(self): | |
| self.client.enabled = False | |
| self.assertEqual(self.client.quotes(["RELIANCE.NS"]), {}) | |
| self.assertIsNone(self.client.history("RELIANCE.NS", "5d", "15m")) | |
| self.assertEqual(self.client.status()["state"], "disabled") | |
| self.session.request.assert_not_called() | |
| def auto_auth(self, token="automatic-token"): | |
| manager = Mock(configured=True) | |
| manager.get_token.return_value = token | |
| manager.status.return_value = {"automatic_auth": True, "auth_ready": True, | |
| "requires_daily_login": False, "automatic_token_expiry": None} | |
| self.client.auth_manager = manager | |
| return manager | |
| def test_automatic_auth_works_without_a_manual_access_token(self): | |
| manager = self.auto_auth() | |
| self.client.access_token = "" | |
| self.assertTrue(self.client.configured) | |
| self.response({"dataPlan": "Active"}) | |
| self.client._request("GET", "/profile") | |
| self.assertEqual(self.session.request.call_args.kwargs["headers"]["access-token"], "automatic-token") | |
| manager.get_token.assert_called_once() | |
| def test_automatic_token_generation_shares_the_request_deadline(self): | |
| manager = self.auto_auth() | |
| self.response({"dataPlan": "Active"}) | |
| self.client._request("GET", "/profile", timeout=4) | |
| self.assertLessEqual(manager.get_token.call_args.kwargs["timeout"], 4) | |
| self.assertLessEqual(self.session.request.call_args.kwargs["timeout"], 4) | |
| def test_rejected_automatic_token_is_invalidated_not_returned_to_browser(self): | |
| manager = self.auto_auth() | |
| self.response({}, status=401) | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client._request("POST", "/marketfeed/quote", {}) | |
| manager.invalidate.assert_called_once_with("automatic-token") | |
| self.assertNotIn("automatic-token", str(self.client.status())) | |
| def test_authentication_cooldown_does_not_consume_market_retries(self): | |
| manager = self.auto_auth() | |
| manager.get_token.side_effect = DhanAuthError("auth_cooldown", attempted=False) | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client._request("POST", "/marketfeed/quote", {}) | |
| self.assertEqual(self.client.status()["failed_attempts"], 0) | |
| self.session.request.assert_not_called() | |
| def test_failed_login_consumes_one_attempt_and_preserves_two_retry_limit(self): | |
| manager = self.auto_auth() | |
| manager.get_token.side_effect = DhanAuthError("auth_rejected", attempted=True) | |
| for attempt in range(3): | |
| self.client._cooldown_until = 0 | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client._request("POST", "/marketfeed/quote", {}) | |
| self.assertTrue(self.client.yahoo_fallback_active) | |
| self.client.quotes(["RELIANCE.NS"]) | |
| self.assertEqual(manager.get_token.call_count, 3) | |
| self.session.request.assert_not_called() | |
| def test_status_polling_does_not_trigger_automatic_login(self): | |
| manager = self.auto_auth() | |
| status = self.client.status() | |
| self.assertTrue(status["automatic_auth"]) | |
| self.assertFalse(status["requires_daily_login"]) | |
| manager.get_token.assert_not_called() | |
| def test_disabled_automatic_auth_is_not_started_by_profile_probe(self): | |
| manager = self.auto_auth() | |
| self.client.enabled = False | |
| self.assertEqual(self.client.status(probe=True)["state"], "disabled") | |
| manager.get_token.assert_not_called() | |
| self.session.request.assert_not_called() | |
| def test_json_invalid_token_response_invalidates_automatic_token(self): | |
| manager = self.auto_auth() | |
| self.response({"errorType": "Invalid_Authentication", "errorCode": "DH-901"}) | |
| with self.assertRaises(dhan_client.DhanError) as failure: | |
| self.client._request("POST", "/marketfeed/quote", {}) | |
| self.assertEqual(failure.exception.code, "token_expired") | |
| manager.invalidate.assert_called_once_with("automatic-token") | |
| def test_profile_probe_during_daily_pause_does_not_auto_login(self): | |
| manager = self.auto_auth() | |
| for attempt in range(3): | |
| self.client._record_failure("unavailable") | |
| self.assertEqual(self.client.status(probe=True)["state"], "yahoo_fallback") | |
| manager.get_token.assert_not_called() | |
| def test_websocket_reconnect_uses_latest_automatic_token(self): | |
| manager = self.auto_auth("fresh-feed-token") | |
| client = self.client | |
| class Feed: | |
| def __init__(self, context, instruments, version): | |
| self.loop = asyncio.new_event_loop() | |
| async def connect(self): | |
| return None | |
| async def get_instrument_data(self): | |
| client.stop() | |
| return None | |
| async def disconnect(self): | |
| return None | |
| context = Mock() | |
| self.client._consumers["first"] = {"RELIANCE.NS"} | |
| with patch.dict("sys.modules", {"dhanhq": types.SimpleNamespace(MarketFeed=Feed, DhanContext=context)}): | |
| self.client._run_feed() | |
| context.assert_called_once_with("test-client", "fresh-feed-token") | |
| manager.get_token.assert_called_once() | |
| def test_stream_refresh_due_disconnects_without_consuming_retries(self): | |
| manager = self.auto_auth() | |
| manager.needs_refresh = True | |
| feed = Mock() | |
| async def connect(): | |
| return None | |
| async def disconnect(): | |
| return None | |
| feed.connect.side_effect = connect | |
| feed.disconnect.side_effect = disconnect | |
| self.client._consumers["first"] = {"RELIANCE.NS"} | |
| asyncio.run(self.client._consume(feed)) | |
| feed.get_instrument_data.assert_not_called() | |
| feed.disconnect.assert_called_once() | |
| self.assertEqual(self.client.status()["failed_attempts"], 0) | |
| def test_instrument_master_filters_cash_equities_and_ambiguous_symbols(self): | |
| master = "SEM_EXM_EXCH_ID,SEM_SEGMENT,SEM_SMST_SECURITY_ID,SEM_INSTRUMENT_NAME,SEM_TRADING_SYMBOL,SEM_SERIES\n" | |
| master += "NSE,E,2885,EQUITY,RELIANCE,EQ\nNSE,D,99,FUTSTK,RELIANCE,\nBSE,E,123,EQUITY,TCS,EQ\n" | |
| self.assertEqual(dhan_client.parse_instruments(master), {"RELIANCE.NS": "2885"}) | |
| self.assertEqual(dhan_client.parse_instruments(master + "NSE,E,88,EQUITY,RELIANCE,EQ\n"), {}) | |
| def test_unknown_symbol_never_guesses_security_id(self): | |
| with self.assertRaisesRegex(dhan_client.DhanError, "instrument"): | |
| self.client.resolve("MISSING.NS") | |
| def test_detailed_instruments_use_exchange_symbol_not_company_name(self): | |
| master = "EXCH_ID,SEGMENT,SECURITY_ID,INSTRUMENT,UNDERLYING_SYMBOL,SYMBOL_NAME,SERIES\n" | |
| master += "NSE,E,2885,EQUITY,RELIANCE,RELIANCE INDUSTRIES LTD,EQ\n" | |
| master += "NSE,E,11536,EQUITY,TCS,TATA CONSULTANCY SERV LT,EQ\n" | |
| self.assertEqual(dhan_client.parse_instruments(master), {"RELIANCE.NS": "2885", "TCS.NS": "11536"}) | |
| def test_profile_only_returns_sanitized_entitlement(self): | |
| self.response({"dhanClientId": "private-id", "dhanClientName": "Private Name", | |
| "tokenValidity": "12/10/2099 15:30", "dataPlan": "Active", "dataValidity": "2099-10-12"}) | |
| status = self.client.status(probe=True) | |
| self.assertTrue(status["token_valid"]) | |
| self.assertEqual(status["data_plan"], "Active") | |
| self.assertNotIn("private-id", str(status)) | |
| self.assertNotIn("secret-token", str(status)) | |
| self.assertNotIn("Private Name", str(status)) | |
| def test_http_failures_are_safe_and_classified(self): | |
| for http_status, expected in ((401, "token_expired"), (403, "access_denied"), (429, "rate_limited")): | |
| with self.subTest(http_status=http_status): | |
| self.client._cooldown_until = 0 | |
| self.client._last_request.clear() | |
| self.response({"errorMessage": "secret-token private account"}, http_status) | |
| with self.assertRaises(dhan_client.DhanError) as failure: | |
| self.client._request("GET", "/profile") | |
| self.assertEqual(failure.exception.code, expected) | |
| self.assertNotIn("secret-token", str(failure.exception)) | |
| def test_request_allowlist_rejects_real_order_endpoints(self): | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client._request("POST", "/orders", {}) | |
| self.session.request.assert_not_called() | |
| def test_json_error_body_cannot_be_mistaken_for_success(self): | |
| self.response({"errorType": "Permission_Error", "errorCode": "unknown", "errorMessage": "secret-token"}) | |
| with self.assertRaises(dhan_client.DhanError) as failure: | |
| self.client._request("GET", "/profile") | |
| self.assertNotIn("secret-token", str(failure.exception)) | |
| def fail_market_request(self): | |
| self.client._cooldown_until = 0 | |
| self.client._last_request.clear() | |
| self.response({}, status=503) | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client._request("POST", "/marketfeed/quote", {"NSE_EQ": [2885]}) | |
| def test_initial_failure_and_two_retries_pause_dhan_for_ist_day(self): | |
| for attempt in range(3): | |
| self.fail_market_request() | |
| self.assertEqual(self.client.yahoo_fallback_active, attempt == 2) | |
| self.assertEqual(self.session.request.call_count, 3) | |
| self.assertEqual(self.client.quotes(["RELIANCE.NS"]), {}) | |
| self.assertIsNone(self.client.history("RELIANCE.NS", "5d", "15m")) | |
| self.assertEqual(self.session.request.call_count, 3) | |
| status = self.client.status() | |
| self.assertEqual(status["state"], "yahoo_fallback") | |
| self.assertEqual(status["active_provider"], "yahoo") | |
| self.assertEqual(status["retries_remaining"], 0) | |
| def test_daily_dhan_pause_survives_backend_restart(self): | |
| saved = {} | |
| self.client._cache_get.side_effect = lambda key: saved.get(key) | |
| self.client._cache_put.side_effect = lambda key, payload: saved.update({key: (dict(payload), time.time())}) | |
| for attempt in range(3): | |
| self.fail_market_request() | |
| restarted = dhan_client.DhanDataClient("test-client", "secret-token", enabled=True, session=self.session) | |
| with patch.object(restarted, "_cache_get", side_effect=lambda key: saved.get(key)): | |
| self.assertTrue(restarted.yahoo_fallback_active) | |
| self.assertEqual(restarted.quotes(["RELIANCE.NS"]), {}) | |
| self.assertEqual(self.session.request.call_count, 3) | |
| def test_failed_websocket_stops_after_initial_attempt_and_two_retries(self): | |
| created = [] | |
| class Feed: | |
| def __init__(self, *args, **kwargs): | |
| self.loop = asyncio.new_event_loop() | |
| created.append(self) | |
| async def connect(self): | |
| raise dhan_client.DhanError("unavailable") | |
| async def disconnect(self): | |
| return None | |
| self.client._consumers["first"] = {"RELIANCE.NS"} | |
| with patch.dict("sys.modules", {"dhanhq": types.SimpleNamespace(MarketFeed=Feed, DhanContext=Mock())}), patch.object( | |
| self.client._stop, "wait", side_effect=lambda timeout: len(created) >= 5 | |
| ): | |
| self.client._run_feed() | |
| self.assertEqual(len(created), 3) | |
| self.assertTrue(self.client.yahoo_fallback_active) | |
| self.assertTrue(all(feed.loop.is_closed() for feed in created)) | |
| def test_subscribing_when_paused_never_starts_dhan_worker(self): | |
| for attempt in range(3): | |
| self.fail_market_request() | |
| with patch("dhan_client.threading.Thread") as worker: | |
| consumer = self.client.subscribe(["RELIANCE.NS"]) | |
| self.client.unsubscribe(consumer) | |
| worker.assert_not_called() | |
| def test_invalid_candles_consume_retry_budget(self): | |
| with patch.object(self.client, "_request", return_value={"timestamp": [1]}): | |
| for attempt in range(3): | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client.history("RELIANCE.NS", "5d", "15m") | |
| self.assertTrue(self.client.yahoo_fallback_active) | |
| def test_unusable_quotes_during_market_hours_consume_retry_budget(self): | |
| self.response({"status": "success", "data": {"NSE_EQ": {}}}) | |
| with patch("market_calendar.market_status", return_value={"status": "OPEN"}): | |
| for attempt in range(3): | |
| self.client._last_request.clear() | |
| self.assertEqual(self.client.quotes(["RELIANCE.NS"]), {}) | |
| self.assertTrue(self.client.yahoo_fallback_active) | |
| self.assertEqual(self.session.request.call_count, 3) | |
| def test_off_hours_missing_ticks_do_not_disable_dhan(self): | |
| self.response({"status": "success", "data": {"NSE_EQ": {}}}) | |
| with patch("market_calendar.market_status", return_value={"status": "POST_MARKET"}): | |
| for attempt in range(3): | |
| self.client._last_request.clear() | |
| self.client.quotes(["RELIANCE.NS"]) | |
| self.assertFalse(self.client.yahoo_fallback_active) | |
| def test_retry_cooldown_does_not_consume_an_extra_attempt(self): | |
| self.fail_market_request() | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client._request("POST", "/marketfeed/quote", {"NSE_EQ": [2885]}) | |
| self.assertEqual(self.session.request.call_count, 1) | |
| self.assertEqual(self.client.status()["failed_attempts"], 1) | |
| def test_daily_pause_resets_at_ist_midnight_not_utc_midnight(self): | |
| before_midnight = datetime(2026, 10, 12, 18, 29, tzinfo=timezone.utc).timestamp() | |
| after_midnight = datetime(2026, 10, 12, 18, 31, tzinfo=timezone.utc).timestamp() | |
| with patch("dhan_client.time.time", return_value=before_midnight): | |
| for attempt in range(3): | |
| self.fail_market_request() | |
| self.assertTrue(self.client.yahoo_fallback_active) | |
| with patch("dhan_client.time.time", return_value=after_midnight): | |
| self.assertFalse(self.client.yahoo_fallback_active) | |
| self.assertEqual(self.client.status()["retries_remaining"], 2) | |
| def test_profile_probes_cannot_reenable_dhan_after_daily_pause(self): | |
| for attempt in range(3): | |
| self.fail_market_request() | |
| self.client._cooldown_until = 0 | |
| self.response({"tokenValidity": "12/10/2099 15:30", "dataPlan": "Active"}) | |
| self.assertEqual(self.client.status(probe=True)["state"], "yahoo_fallback") | |
| def test_successful_market_request_resets_consecutive_failures(self): | |
| self.fail_market_request() | |
| self.client._cooldown_until = 0 | |
| self.client._last_request.clear() | |
| traded = datetime.now(dhan_client.IST).strftime("%d/%m/%Y %H:%M:%S") | |
| self.response({"status": "success", "data": {"NSE_EQ": {"2885": { | |
| "last_price": 2500, "last_trade_time": traded, | |
| }}}}) | |
| self.client.quotes(["RELIANCE.NS"]) | |
| self.fail_market_request() | |
| self.fail_market_request() | |
| self.assertFalse(self.client.yahoo_fallback_active) | |
| def test_network_exception_does_not_leak_credentials(self): | |
| self.session.request.side_effect = dhan_client.requests.RequestException("secret-token") | |
| with self.assertRaises(dhan_client.DhanError) as failure: | |
| self.client._request("GET", "/profile") | |
| self.assertNotIn("secret-token", str(failure.exception)) | |
| def test_tick_retains_exchange_timestamp_and_source(self): | |
| packet = self.tick() | |
| self.client.record_tick(packet) | |
| quotes = self.client.cached_quotes(["RELIANCE.NS"]) | |
| self.assertEqual(quotes["RELIANCE.NS"]["price"], 2500.25) | |
| self.assertEqual(quotes["RELIANCE.NS"]["trade_time"], packet["LTT"]) | |
| self.assertEqual(quotes["RELIANCE.NS"]["source"], "dhan") | |
| self.assertFalse(quotes["RELIANCE.NS"]["stale"]) | |
| def test_old_future_nonfinite_or_wrong_exchange_ticks_are_not_live(self): | |
| packets = [self.tick(LTT=time.time() - 300), self.tick(LTT=time.time() + 600), | |
| self.tick(LTP="nan"), self.tick(LTP=-1), self.tick(exchange_segment=4), self.tick(LTP=True)] | |
| for packet in packets: | |
| with self.subTest(packet=packet): | |
| self.client.record_tick(packet) | |
| self.assertEqual(self.client.cached_quotes(["RELIANCE.NS"]), {}) | |
| def test_out_of_order_ticks_do_not_replace_newer_quote(self): | |
| current = self.tick() | |
| self.client.record_tick(current) | |
| self.client.record_tick(self.tick(LTT=current["LTT"] - 1, LTP="2000")) | |
| self.assertEqual(self.client.cached_quotes(["RELIANCE.NS"])["RELIANCE.NS"]["price"], 2500.25) | |
| def test_stale_quote_is_only_returned_when_requested(self): | |
| self.client.record_tick(self.tick()) | |
| with patch("dhan_client.time.time", return_value=time.time() + 300): | |
| self.assertEqual(self.client.cached_quotes(["RELIANCE.NS"]), {}) | |
| self.assertTrue(self.client.cached_quotes(["RELIANCE.NS"], include_stale=True)["RELIANCE.NS"]["stale"]) | |
| def test_rest_quotes_are_batched_and_reused(self): | |
| traded = datetime.now(dhan_client.IST).strftime("%d/%m/%Y %H:%M:%S") | |
| self.response({"status": "success", "data": {"NSE_EQ": { | |
| "2885": {"last_price": 2500, "last_trade_time": traded}, | |
| "11536": {"last_price": 3500, "last_trade_time": traded}, | |
| }}}) | |
| self.assertEqual(len(self.client.quotes(["RELIANCE.NS", "TCS.NS"])), 2) | |
| self.client.quotes(["RELIANCE.NS", "TCS.NS"]) | |
| self.session.request.assert_called_once() | |
| self.assertEqual(self.session.request.call_args.kwargs["json"], {"NSE_EQ": [2885, 11536]}) | |
| def test_candles_normalize_ist_and_reject_invalid_ohlc(self): | |
| epoch = datetime(2026, 10, 12, 4, tzinfo=timezone.utc).timestamp() | |
| payload = {"timestamp": [epoch, epoch + 900], "open": [100, 100], "high": [102, 99], | |
| "low": [99, 98], "close": [101, 100], "volume": [100, 100]} | |
| bars = dhan_client.normalize_candles(payload) | |
| self.assertEqual(len(bars), 1) | |
| self.assertEqual(bars.index[0].hour, 9) | |
| self.assertEqual(bars.index[0].minute, 30) | |
| self.assertEqual(bars.attrs["source"], "dhan") | |
| with self.assertRaises(dhan_client.DhanError): | |
| dhan_client.normalize_candles({**payload, "close": [100]}) | |
| def test_history_requests_correct_segment_interval_and_exclusive_end(self): | |
| epoch = time.time() - 86400 | |
| self.response({"timestamp": [epoch], "open": [100], "high": [102], "low": [99], | |
| "close": [101], "volume": [100]}) | |
| self.assertEqual(len(self.client.history("RELIANCE.NS", "5d", "15m")), 1) | |
| request_body = self.session.request.call_args.kwargs["json"] | |
| self.assertEqual(request_body["securityId"], "2885") | |
| self.assertEqual(request_body["exchangeSegment"], "NSE_EQ") | |
| self.assertEqual(request_body["interval"], "15") | |
| self.assertEqual(request_body["instrument"], "EQUITY") | |
| def test_history_never_uses_unadjusted_cache_for_daily_model_features(self): | |
| self.assertFalse(self.client.history_adjusted) | |
| def test_subscriptions_share_worker_and_cleanup(self): | |
| with patch("dhan_client.threading.Thread") as thread: | |
| first = self.client.subscribe(["RELIANCE.NS"]) | |
| second = self.client.subscribe(["TCS.NS"]) | |
| thread.assert_called_once() | |
| self.client.unsubscribe(first) | |
| self.assertEqual(self.client.stream_tickers(), {"TCS.NS"}) | |
| self.client.unsubscribe(second) | |
| self.assertEqual(self.client.stream_tickers(), set()) | |
| def test_stream_connect_and_receive_use_sdk_and_close(self): | |
| feed = Mock() | |
| async def connect(): | |
| return None | |
| async def receive(): | |
| self.client._stop.set() | |
| return self.tick() | |
| async def disconnect(): | |
| return None | |
| feed.connect.side_effect = connect | |
| feed.get_instrument_data.side_effect = receive | |
| feed.disconnect.side_effect = disconnect | |
| self.client._consumers["test"] = {"RELIANCE.NS"} | |
| asyncio.run(self.client._consume(feed)) | |
| feed.connect.assert_called_once() | |
| feed.disconnect.assert_called_once() | |
| self.assertEqual(self.client.cached_quotes(["RELIANCE.NS"])["RELIANCE.NS"]["price"], 2500.25) | |
| def test_quote_lock_wait_has_a_caller_budget(self): | |
| self.client._quote_lock.acquire() | |
| try: | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client.quotes(["RELIANCE.NS"], timeout=0.01) | |
| finally: | |
| self.client._quote_lock.release() | |
| self.session.request.assert_not_called() | |
| def test_notifications_are_coalesced_until_the_update_deadline(self): | |
| with patch.object(self.client, "_changed") as changed, patch( | |
| "dhan_client.time.monotonic", side_effect=[0, 0, 0.1, 1.1] | |
| ): | |
| self.client.wait_for_update(timeout=1) | |
| self.assertEqual(changed.wait.call_count, 2) | |
| def test_expired_instrument_mapping_is_not_reused_after_fetch_failure(self): | |
| self.client._instruments_at = time.time() - 8 * 86400 | |
| self.session.get.side_effect = dhan_client.requests.RequestException("offline") | |
| with self.assertRaises(dhan_client.DhanError): | |
| self.client.resolve("RELIANCE.NS") | |
| def test_new_subscriber_during_connect_is_sent_to_the_feed(self): | |
| feed = Mock() | |
| async def connect(): | |
| self.client._consumers["second"] = {"TCS.NS"} | |
| async def subscribe(): | |
| return None | |
| async def receive(): | |
| self.client.stop() | |
| return self.tick() | |
| async def disconnect(): | |
| return None | |
| feed.connect.side_effect = connect | |
| feed.subscribe_instruments.side_effect = subscribe | |
| feed.get_instrument_data.side_effect = receive | |
| feed.disconnect.side_effect = disconnect | |
| self.client._consumers["first"] = {"RELIANCE.NS"} | |
| asyncio.run(self.client._consume(feed, {"RELIANCE.NS"})) | |
| feed.subscribe_instruments.assert_called_once() | |
| self.assertEqual(set(feed.instruments), {(1, "2885", 17), (1, "11536", 17)}) | |
| def test_sdk_worker_retains_epoch_and_maps_disconnect_codes(self): | |
| created = [] | |
| client = self.client | |
| packet = self.tick() | |
| class Feed: | |
| def __init__(self, context, instruments, version): | |
| self.loop = asyncio.new_event_loop() | |
| self.instruments = instruments | |
| created.append(self) | |
| async def connect(self): | |
| return None | |
| async def get_instrument_data(self): | |
| client.stop() | |
| return {**packet, "LTT": self.utc_time(packet["LTT"])} | |
| async def disconnect(self): | |
| return None | |
| sdk = types.SimpleNamespace(MarketFeed=Feed, DhanContext=Mock()) | |
| self.client._consumers["first"] = {"RELIANCE.NS"} | |
| with patch.dict("sys.modules", {"dhanhq": sdk}): | |
| self.client._run_feed() | |
| self.assertEqual(len(created), 1) | |
| self.assertTrue(created[0].loop.is_closed()) | |
| for code, expected in ((806, "subscription_required"), (807, "token_expired"), (808, "access_denied")): | |
| with self.subTest(code=code), self.assertRaises(dhan_client.DhanError) as failure: | |
| created[0].server_disconnection(bytes(8) + code.to_bytes(2, "little")) | |
| self.assertEqual(failure.exception.code, expected) | |
| def test_sdk_worker_sanitizes_connection_failure_and_stops_backoff(self): | |
| class Feed: | |
| def __init__(self, *args, **kwargs): | |
| self.loop = asyncio.new_event_loop() | |
| async def connect(self): | |
| raise dhan_client.DhanError("token_expired") | |
| async def disconnect(self): | |
| return None | |
| self.client._consumers["first"] = {"RELIANCE.NS"} | |
| with patch.dict("sys.modules", {"dhanhq": types.SimpleNamespace(MarketFeed=Feed, DhanContext=Mock())}), patch.object( | |
| self.client._stop, "wait", return_value=True | |
| ) as wait: | |
| self.client._run_feed() | |
| self.assertEqual(self.client.status()["state"], "token_expired") | |
| wait.assert_called_once_with(60) | |
| def test_instrument_mapping_loads_from_recent_persistent_cache(self): | |
| self.client._instruments = {} | |
| self.client._instruments_at = 0 | |
| self.client._cache_get.return_value = ({"RELIANCE.NS": "2885"}, time.time()) | |
| self.assertEqual(self.client.resolve("RELIANCE.NS"), "2885") | |
| self.session.get.assert_not_called() | |
| def test_instrument_mapping_is_fetched_and_saved_when_missing(self): | |
| self.client._instruments = {} | |
| self.client._instruments_at = 0 | |
| response = Mock(text="SEM_EXM_EXCH_ID,SEM_SEGMENT,SEM_SMST_SECURITY_ID,SEM_INSTRUMENT_NAME,SEM_TRADING_SYMBOL,SEM_SERIES\nNSE,E,2885,EQUITY,RELIANCE,EQ\n") | |
| self.session.get.return_value = response | |
| self.assertEqual(self.client.resolve("RELIANCE.NS"), "2885") | |
| self.client._cache_put.assert_called_once() | |
| def test_history_cache_preserves_metadata_and_refresh_bypasses_it(self): | |
| payload = {"timestamp": [time.time() - 86400], "open": [100], "high": [102], "low": [99], "close": [101], "volume": [100]} | |
| self.client._cache_get.return_value = (payload, time.time()) | |
| self.assertEqual(self.client.history("RELIANCE.NS", "5d", "15m").attrs["source"], "dhan") | |
| self.session.request.assert_not_called() | |
| self.response(payload) | |
| self.client.history("RELIANCE.NS", "5d", "15m", refresh=True) | |
| self.session.request.assert_called_once() | |
| def test_long_intraday_history_splits_at_ninety_days_and_deduplicates(self): | |
| payload = {"timestamp": [time.time() - 86400], "open": [100], "high": [102], "low": [99], "close": [101], "volume": [100]} | |
| with patch.object(self.client, "_request", return_value=payload) as request: | |
| bars = self.client.history("RELIANCE.NS", "91d", "15m") | |
| self.assertEqual(request.call_count, 2) | |
| self.assertEqual(len(bars), 1) | |
| def test_daily_history_uses_noninclusive_next_day_end(self): | |
| payload = {"timestamp": [time.time() - 86400], "open": [100], "high": [102], "low": [99], "close": [101], "volume": [100]} | |
| with patch.object(self.client, "_request", return_value=payload) as request: | |
| self.client.history("RELIANCE.NS", "2y", "1d") | |
| self.assertEqual(request.call_args.args[1], "/charts/historical") | |
| self.assertEqual(request.call_args.args[2]["toDate"], (datetime.now(dhan_client.IST) + dhan_client.timedelta(days=1)).strftime("%Y-%m-%d")) | |
| def test_sqlite_cache_connections_are_closed(self): | |
| connection = MagicMock() | |
| connection.__enter__.return_value = connection | |
| connection.execute.return_value.fetchone.return_value = (json.dumps({"RELIANCE.NS": "2885"}), 1000) | |
| with patch("dhan_client.sqlite3.connect", return_value=connection): | |
| cached = dhan_client.DhanDataClient._cache_get(self.client, "instruments") | |
| self.assertEqual(cached, ({"RELIANCE.NS": "2885"}, 1000)) | |
| connection.close.assert_called_once() | |
| connection.reset_mock() | |
| with patch("dhan_client.sqlite3.connect", return_value=connection): | |
| dhan_client.DhanDataClient._cache_put(self.client, "instruments", {"RELIANCE.NS": "2885"}) | |
| connection.commit.assert_called_once() | |
| connection.close.assert_called_once() | |
| if __name__ == "__main__": | |
| unittest.main() |