Spaces:
Sleeping
Sleeping
Commit ·
7e2356c
1
Parent(s): 926decc
test(core): Complete and fix the unit test suite
Browse filesFiles changed (3)
4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768694 unmodified linesimport sysimport os# Add project root to the Python path so we can import from 'core'sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from core.analytics import calculate_technical_indicators, detect_arbitragedef test_calculate_technical_indicators_happy_path():"""Tests that the indicator calculation function works with valid data."""# 1. Arrange: Create a sample DataFrame with enough datadata = {'close': np.linspace(100, 150, 40)} # 40 data points from 100 to 150sample_df = pd.DataFrame(data)# 2. Act: Call the function we are testingresult = calculate_technical_indicators(sample_df)# 3. Assert: Check if the output is correctassert isinstance(result, dict)assert 'SMA_10' in resultassert 'SMA_30' in resultassert 'EMA_14' in resultassert 'RSI_14' in result# Check a specific value: the SMA_10 of the last 10 points# Last 10 values are from 137.17 to 150. Their average should be ~143.59expected_sma10 = sample_df['close'].tail(10).mean()assert np.isclose(result['SMA_10'], expected_sma10)def test_calculate_technical_indicators_not_enough_data():"""Tests that the function returns an empty dict if there isn't enough data."""# 1. Arrange: Create a DataFrame with only 5 data pointsdata = {'close': [100, 101, 102, 103, 104]}sample_df = pd.DataFrame(data)# 2. Actresult = calculate_technical_indicators(sample_df)# 3. Assertassert result == {}def test_detect_arbitrage_opportunity():"""Tests that a clear arbitrage opportunity is correctly identified."""# 1. Arrange: Create data with a significant price differencedata = {'timestamp': pd.to_datetime(['2025-01-01 12:00', '2025-01-01 12:01']),'source': ['Binance', 'UniswapV3'],'price_usd': [100.0, 105.0] # A 5% difference}sample_df = pd.DataFrame(data)# 2. Actopportunities = detect_arbitrage(sample_df)# 3. Assertassert len(opportunities) == 1opportunity = opportunities[0]assert opportunity['source_a'] == 'Buy at Binance'assert opportunity['source_b'] == 'Sell at UniswapV3'assert np.isclose(opportunity['percent_diff'], 5.0)4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191204 unmodified linesimport sysimport os# Add project root to the Python pathsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from core.analytics import calculate_technical_indicators, detect_arbitrage, detect_anomaliesfrom config import SOURCES # Import sources for arbitrage testdef test_calculate_technical_indicators_happy_path():"""Tests that the indicator calculation function works with valid data."""# 1. Arrange: Create a sample DataFrame with enough datadata = {'timestamp': pd.to_datetime(pd.date_range(end=pd.Timestamp.now(), periods=40, freq='h')),'close': np.linspace(100, 150, 40),'volume_24h': np.random.uniform(1e6, 5e6, 40)}sample_df = pd.DataFrame(data)# 2. Act: Call the function we are testingresult_df = calculate_technical_indicators(sample_df.copy())result = result_df.iloc[-1].to_dict() # Get the latest indicators# 3. Assert: Check if the main indicators are presentassert isinstance(result, dict)assert 'SMA_10' in resultassert 'SMA_30' in resultassert 'EMA_14' in resultassert 'RSI_14' in resultassert 'VWAP_24h' in resultassert 'Realized_Vol_30D' in result# Check a specific value for SMA10expected_sma10 = sample_df['close'].tail(10).mean()assert np.isclose(result['SMA_10'], expected_sma10)def test_calculate_technical_indicators_not_enough_data():"""Tests that the function returns an empty DataFrame if there isn't enough data."""data = {'close': [100, 101, 102, 103, 104]}sample_df = pd.DataFrame(data)result = calculate_technical_indicators(sample_df)assert result.emptydef test_detect_arbitrage_opportunity():"""Tests that a clear arbitrage opportunity is correctly identified."""data = {'timestamp': pd.to_datetime(['2025-01-01 12:00', '2025-01-01 12:01']),'source': ['Binance', 'UniswapV3'],'price_usd': [100.0, 105.0] # A 5% difference}sample_df = pd.DataFrame(data)opportunities = detect_arbitrage(sample_df)assert len(opportunities) == 1opportunity = opportunities[0]assert opportunity['source_a'] == 'Buy at Binance'assert opportunity['source_b'] == 'Sell at UniswapV3'assert np.isclose(opportunity['percent_diff'], 5.0)def test_detect_anomalies_volume_spike():"""Tests that a volume spike anomaly is detected."""# Arrange: 30 days of normal volume, with one huge spike at the endnormal_volume = np.full(30, 100)spiked_volume = np.append(normal_volume, 1000) # 10x the averageprices = np.linspace(100, 101, 31)timestamps = pd.to_datetime(pd.date_range(end=pd.Timestamp.now(), periods=31, freq='h'))df = pd.DataFrame({'timestamp': timestamps, 'close': prices, 'volume_24h': spiked_volume})# Actanomalies = detect_anomalies(df)# Assertassert len(anomalies) == 1assert anomalies[0]['anomaly_type'] == "Volume Spike"assert "exceeds threshold" in anomalies[0]['description']def test_detect_anomalies_price_jump():"""Tests that a price jump anomaly is detected."""# Arrange: A series of prices with a sudden >5% jump at the endprices = [100] * 30prices.append(106) # A 6% jumptimestamps = pd.to_datetime(pd.date_range(end=pd.Timestamp.now(), periods=31, freq='h'))df = pd.DataFrame({'timestamp': timestamps, 'close': prices, 'volume_24h': [100]*31})# Actanomalies = detect_anomalies(df)# Assertassert len(anomalies) == 1assert anomalies[0]['anomaly_type'] == "Price Jump"assert "Price changed by 6.00%" in anomalies[0]['description']def test_detect_anomalies_no_anomaly():"""Tests that no anomaly is detected with stable data."""# Arrange: Stable price and volume dataprices = np.linspace(100, 101, 30)volumes = np.full(30, 100)timestamps = pd.to_datetime(pd.date_range(end=pd.Timestamp.now(), periods=30, freq='h'))df = pd.DataFrame({'timestamp': timestamps, 'close': prices, 'volume_24h': volumes})# Actanomalies = detect_anomalies(df)# Assertassert len(anomalies) == 0
1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566671 unmodified lineimport pytestimport asyncioimport httpx # <--- IMPORT HTTPROXYimport sysimport os# Add project root to the Python pathsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from core.data_fetcher import fetch_binance# Mark the test as an asyncio test@pytest.mark.asyncioasync def test_fetch_binance_with_mocking(monkeypatch):"""Tests the fetch_binance function by mocking the API call and DB write.`monkeypatch` is a pytest fixture for safely modifying code during tests."""# 1. Arrange: Define what our fake API call will returnmock_api_response = {"symbol": "BTCUSDT","lastPrice": "50000.00","quoteVolume": "1000000.00"}# Create a mock async function to replace httpx.getclass MockAsyncResponse:def json(self):return mock_api_responsedef raise_for_status(self):pass # Do nothing, assume successasync def mock_get(*args, **kwargs):return MockAsyncResponse()# Use monkeypatch to replace the real httpx GET with our fake onemonkeypatch.setattr("httpx.AsyncClient.get", mock_get)# Arrange: Keep track of what gets sent to the databasedb_call_args = {}def mock_insert_price(conn, token_id, source, price_usd, volume_24h, raw_data):db_call_args['token_id'] = token_iddb_call_args['source'] = sourcedb_call_args['price_usd'] = price_usddb_call_args['volume_24h'] = volume_24h# Replace the real database insert function with our trackermonkeypatch.setattr("core.data_fetcher.insert_price", mock_insert_price)monkeypatch.setattr("core.data_fetcher.log_api_health", lambda *args, **kwargs: None) # Ignore health loggingmonkeypatch.setattr("core.data_fetcher.get_token_id", lambda conn, symbol: 1) # Assume token_id is 1# 2. Act: Call the function we are testing# --- FIX IS HERE ---await fetch_binance(client=httpx.AsyncClient(), # Pass a REAL client instancetoken={"symbol": "BTC", "binance_id": "BTCUSDT"},conn=None,semaphore=asyncio.Semaphore(1))# --- END OF FIX ---# 3. Assert: Check if the database function was called with the correct dataassert db_call_args['token_id'] == 1assert db_call_args['source'] == "Binance"assert db_call_args['price_usd'] == 50000.00assert db_call_args['volume_24h'] == 1000000.001 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271 unmodified lineimport pytestimport asyncioimport httpximport sysimport os# Add project root to the Python pathsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from core.data_fetcher import fetch_binance, fetch_coingecko, fetch_uniswap_v3# --- Mock Response Class ---class MockAsyncResponse:def __init__(self, json_data, status_code=200):self._json_data = json_dataself.status_code = status_codeself.request = httpx.Request("GET", "https://test.com")def json(self):return self._json_datadef raise_for_status(self):if self.status_code != 200:raise httpx.HTTPStatusError(message=f"Error: {self.status_code}",request=self.request,response=httpx.Response(self.status_code, json=self._json_data))# --- Binance Tests ---@pytest.mark.asyncioasync def test_fetch_binance_success(monkeypatch):""" Tests the fetch_binance function for a successful API call. """mock_api_response = {"lastPrice": "50000.00", "quoteVolume": "1000000.00"}async def mock_get(*args, **kwargs):return MockAsyncResponse(mock_api_response)monkeypatch.setattr("httpx.AsyncClient.get", mock_get)db_call_args = {}def mock_insert_price(conn, token_id, source, price_usd, volume_24h, raw_data):db_call_args.update(locals())monkeypatch.setattr("core.data_fetcher.insert_price", mock_insert_price)monkeypatch.setattr("core.data_fetcher.log_api_health", lambda *args, **kwargs: None)monkeypatch.setattr("core.data_fetcher.get_token_id", lambda conn, symbol: 1)await fetch_binance(httpx.AsyncClient(), {"symbol": "BTC", "binance_id": "BTCUSDT"}, None, asyncio.Semaphore(1))assert db_call_args['source'] == "Binance"assert db_call_args['price_usd'] == 50000.00@pytest.mark.asyncioasync def test_fetch_binance_api_error(monkeypatch):""" Tests the fetch_binance function when the API returns an error. """async def mock_get(*args, **kwargs):# Simulate a failed API call after retriesreturn {"error": "HTTP Error: 500 for URL: https://test.com", "raw_response": "{}"}, 50.0# FIX: We now mock fetch_with_retry directly as it's the source of the error tuplemonkeypatch.setattr("core.data_fetcher.fetch_with_retry", mock_get)health_log_args = {}# FIX: The mock signature now accepts all possible argumentsdef mock_log_health(conn, source, status, response_time_ms=None, error_message=None, raw_data=None):health_log_args.update(locals())monkeypatch.setattr("core.data_fetcher.log_api_health", mock_log_health)monkeypatch.setattr("core.data_fetcher.get_token_id", lambda conn, symbol: 1)await fetch_binance(httpx.AsyncClient(), {"symbol": "BTC", "binance_id": "BTCUSDT"}, None, asyncio.Semaphore(1))assert health_log_args['source'] == "Binance"assert health_log_args['status'] == "error"assert "HTTP Error: 500" in health_log_args['error_message']# --- CoinGecko Tests ---@pytest.mark.asyncioasync def test_fetch_coingecko_success(monkeypatch):""" Tests the fetch_coingecko function for a successful API call. """mock_api_response = {"bitcoin": {"usd": 51000.00, "usd_24h_vol": 1200000.00}}async def mock_get(*args, **kwargs):return MockAsyncResponse(mock_api_response)monkeypatch.setattr("httpx.AsyncClient.get", mock_get)db_call_args = {}def mock_insert_price(conn, token_id, source, price_usd, volume_24h, raw_data):db_call_args.update(locals())monkeypatch.setattr("core.data_fetcher.insert_price", mock_insert_price)monkeypatch.setattr("core.data_fetcher.log_api_health", lambda *args, **kwargs: None)monkeypatch.setattr("core.data_fetcher.get_token_id", lambda conn, symbol: 1)await fetch_coingecko(httpx.AsyncClient(), {"symbol": "BTC", "coingecko_id": "bitcoin"}, None, asyncio.Semaphore(1))assert db_call_args['source'] == "CoinGecko"assert db_call_args['price_usd'] == 51000.00# --- Uniswap Tests ---@pytest.mark.asyncioasync def test_fetch_uniswap_v3_success(monkeypatch):""" Tests the fetch_uniswap_v3 function for a successful GraphQL call. """mock_api_response = {"data": {"pools": [{"token0": {"symbol": "WBTC", "derivedETH": "25.0"}, "token1": {"symbol": "WETH"}, "volumeUSD": "3000000.00"}]}}async def mock_post(*args, **kwargs):return MockAsyncResponse(mock_api_response)monkeypatch.setattr("httpx.AsyncClient.post", mock_post)db_call_args = {}def mock_insert_price(conn, token_id, source, price_usd, volume_24h, raw_data):db_call_args.update(locals())monkeypatch.setattr("core.data_fetcher.insert_price", mock_insert_price)monkeypatch.setattr("core.data_fetcher.log_api_health", lambda *args, **kwargs: None)monkeypatch.setattr("core.data_fetcher.get_token_id", lambda conn, symbol: 1)await fetch_uniswap_v3(httpx.AsyncClient(), {"symbol": "BTC", "uniswap_id": "0x..."}, None, eth_usd=2000.0, semaphore=asyncio.Semaphore(1))assert db_call_args['source'] == "UniswapV3"assert db_call_args['price_usd'] == 50000.00 # 25.0 * 2000.0
9 unmodified lines1011121314151617181920212223242526272829303132333435363738399 unmodified linesfrom core.feature_simulator import simulate_fee_change_impactfrom config import SIMULATION_BASE_FEE_PERCENT, SIMULATION_ELASTICITY_CONSTANTdef test_simulate_fee_change_impact():"""Tests the fee simulation with a predictable dataset."""# 1. Arrange: Create sample volume data and a proposed fee changesample_volume = pd.Series([1000, 1000, 1000, 1000]) # Consistent volume for easy mathproposed_change = 0.02 # A 0.02% increase# 2. Act: Run the simulationresult = simulate_fee_change_impact(sample_volume, proposed_change)# 3. Assert: Manually calculate the expected results and verify# Baseline calculationsbase_fee = SIMULATION_BASE_FEE_PERCENT / 100 # 0.1% -> 0.001expected_baseline_revenue = 1000 * base_fee # 1000 * 0.001 = 1.0assert np.isclose(result['baseline_revenue'], expected_baseline_revenue)# Simulated calculationsnew_fee = (SIMULATION_BASE_FEE_PERCENT + proposed_change) / 100 # 0.12% -> 0.0012percent_change_in_fee = proposed_change / SIMULATION_BASE_FEE_PERCENT # 0.02 / 0.1 = 0.2 (20%)percent_change_in_volume = -SIMULATION_ELASTICITY_CONSTANT * percent_change_in_fee # -0.5 * 0.2 = -0.1 (-10%)simulated_volume = 1000 * (1 + percent_change_in_volume) # 1000 * 0.9 = 900expected_simulated_revenue = simulated_volume * new_fee # 900 * 0.0012 = 1.08assert np.isclose(result['simulated_revenue'], expected_simulated_revenue)assert np.isclose(result['delta'], expected_simulated_revenue - expected_baseline_revenue)assert "Positive Impact" in result['recommendation']9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253549 unmodified linesfrom core.feature_simulator import simulate_fee_change_impactfrom config import SIMULATION_BASE_FEE_PERCENT, SIMULATION_ELASTICITY_CONSTANTdef test_simulate_fee_change_impact_positive():"""Tests the fee simulation with a proposed fee INCREASE."""# 1. Arrange: Create sample volume data and a proposed fee changesample_volume = pd.Series([1000] * 10)proposed_change = 0.02 # A 0.02% increase# 2. Act: Run the simulationresult = simulate_fee_change_impact(sample_volume, proposed_change)# 3. Assert# Baseline calculationsbase_fee = SIMULATION_BASE_FEE_PERCENT / 100expected_baseline_revenue = 1000 * base_feeassert np.isclose(result['baseline_revenue'], expected_baseline_revenue)# Simulated calculationsnew_fee = (SIMULATION_BASE_FEE_PERCENT + proposed_change) / 100percent_change_in_fee = proposed_change / SIMULATION_BASE_FEE_PERCENTpercent_change_in_volume = -SIMULATION_ELASTICITY_CONSTANT * percent_change_in_feesimulated_volume = 1000 * (1 + percent_change_in_volume)expected_simulated_revenue = simulated_volume * new_feeassert np.isclose(result['simulated_revenue'], expected_simulated_revenue)assert np.isclose(result['delta'], expected_simulated_revenue - expected_baseline_revenue)assert "Positive Impact" in result['recommendation']def test_simulate_fee_change_impact_negative():"""Tests the fee simulation with a proposed fee DECREASE."""# 1. Arrangesample_volume = pd.Series([1000] * 10)proposed_change = -0.02 # A 0.02% decrease# 2. Actresult = simulate_fee_change_impact(sample_volume, proposed_change)# 3. Assertassert "Negative Impact" in result['recommendation']assert result['delta'] < 0
tests/test_analytics.py+70-19
tests/test_data_fetcher.py+105-45
tests/test_feature_simulator.py+27-12