-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_integration.py
More file actions
865 lines (789 loc) · 36.6 KB
/
test_integration.py
File metadata and controls
865 lines (789 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
import os
import unittest
import ccxt
import google.auth
import praw
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from google.auth.transport.requests import (
Request as GoogleAuthRequest, # Alias to avoid name clash
)
from google.cloud import aiplatform
from supabase import create_client
from web3 import Web3
# --- Load Environment Variables ---
# Ensure this script is run from the project root or adjust path accordingly
load_dotenv()
# --- Helper Functions/Configuration ---
def check_env_var(var_name, is_required=False, default=None):
"""Checks if an environment variable is set, returns default if not set and not required."""
value = os.getenv(var_name, default)
if not value and is_required:
raise unittest.SkipTest(
f"Required environment variable {var_name} is not set. "
"Cannot run test."
)
elif not value and not is_required:
print(
f"Warning: Optional environment variable {var_name} not set. "
"Related tests may be skipped or fail."
)
return value
# --- Test Suite ---
class TestCryptoWildfireIntegration(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Set up resources needed for all tests in this class."""
print("Setting up Integration Test Suite...")
# Check for essential configurations
cls.supabase_url = "https://kivahquevmwzlddytbbk.supabase.co"
cls.gcp_project = check_env_var("GOOGLE_CLOUD_PROJECT", is_required=True)
cls.openrouter_key = check_env_var("OPENROUTER_API_KEY", is_required=True)
cls.vertex_region = "us-central1"
cls.vertex_staging_bucket = check_env_var(
"VERTEX_AI_STAGING_BUCKET", is_required=True
)
# Initialize Supabase client for DB test
try:
# Use hardcoded service role key
service_role_key = (
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
"eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtpdmFocXVldm13emxkZHl0YmJrIiwicm9"
"sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc0MzQwMzc3NiwiZXhwIjoyMDU4OTc5N"
"zc2fQ.rUcw9UUd7jH-1iOntGGL_1L7ztleT_EQOuhk8MonxvA"
)
# Create client for supabase-py v2.x
cls.db_client = create_client(cls.supabase_url, service_role_key)
print("Supabase client initialized.")
# Test the connection with a simple query
try:
# Try to query a system table that should exist
response = (
cls.db_client.table("_dummy_table_").select("*").limit(1).execute()
)
print("Supabase query executed.")
except Exception as e:
# This error is expected for a non-existent table
if "does not exist" in str(e):
print(
"Supabase connection confirmed (expected error for "
"non-existent table)."
)
else:
# Re-raise other unexpected errors
raise e
except Exception as e:
print(f"Failed to initialize Supabase Client: {e}")
cls.db_client = None # Test will check for None
# Check GCP Authentication & Vertex AI Init
try:
# Hardcode the credentials path
gcp_creds_path = (
"/Users/vishnuvardhanmedara/CryptoWildfire/"
"cryptowildfire-5e5854b693f1.json"
)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = gcp_creds_path
cls.gcp_credentials, cls.gcp_default_project = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
if cls.gcp_credentials and cls.gcp_credentials.requires_scopes:
cls.gcp_credentials.refresh(GoogleAuthRequest())
gcp_proj = cls.gcp_default_project or cls.gcp_project
print(f"GCP Authentication successful for project: {gcp_proj}")
# Initialize Vertex AI client
aiplatform.init(
project=cls.gcp_project,
location=cls.vertex_region,
staging_bucket=cls.vertex_staging_bucket,
credentials=cls.gcp_credentials,
)
print("Vertex AI client initialized.")
cls.vertex_ai_initialized = True
except Exception as e:
print(f"Failed GCP authentication or Vertex AI init: {e}")
cls.gcp_credentials = None
cls.vertex_ai_initialized = False
print("Setup complete.")
print("-" * 30)
# --- Market Data Collector Tests ---
def test_coingecko_api(self):
"""Test fetching market data from CoinGecko (Free Tier)."""
print("Testing CoinGecko API...")
headers = {"accept": "application/json"}
url = "https://api.coingecko.com/api/v3/ping"
try:
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
data = response.json()
self.assertIn("gecko_says", data)
print("CoinGecko API ping successful.")
except requests.exceptions.RequestException as e:
self.fail(f"CoinGecko API request failed: {e}")
def test_ccxt_api(self):
"""Test fetching ticker data via CCXT (e.g., Binance)."""
print("Testing CCXT API (Binance)...")
try:
exchange = ccxt.binance({"enableRateLimit": True})
ticker = exchange.fetch_ticker("BTC/USDT")
self.assertIsNotNone(ticker, "CCXT failed to fetch BTC/USDT ticker")
self.assertEqual(ticker["symbol"], "BTC/USDT")
self.assertIn("last", ticker)
print(f"CCXT Binance BTC/USDT Ticker Price: {ticker['last']}")
print("CCXT API test passed.")
except ccxt.NetworkError as e:
self.fail(f"CCXT Network Error: {e}")
except ccxt.ExchangeError as e:
self.fail(f"CCXT Exchange Error: {e}")
except Exception as e:
self.fail(f"CCXT unexpected error: {e}")
# --- On-Chain Data Collector Tests ---
def test_rpc_api(self):
"""Test fetching data via Public RPC (e.g., Ethereum)."""
print("Testing Public RPC API (Ethereum)...")
rpc_url = check_env_var("ETH_RPC_URL", is_required=True)
try:
w3 = Web3(Web3.HTTPProvider(rpc_url, request_kwargs={"timeout": 15}))
self.assertTrue(
w3.is_connected(), f"Failed to connect to RPC URL: {rpc_url}"
)
latest_block = w3.eth.block_number
self.assertIsInstance(latest_block, int)
self.assertGreater(latest_block, 15000000)
print(f"RPC Latest Block: {latest_block}")
print("RPC API test passed.")
except Exception as e:
self.fail(f"RPC connection or query failed: {e}")
def test_explorer_api(self):
"""Test fetching data via Blockchain Explorer API (e.g., Etherscan)."""
print("Testing Explorer API (Etherscan)...")
api_key = check_env_var("ETHERSCAN_API_KEY", is_required=True)
test_address = "0xdAC17F958D2ee523a2206206994597C13D831ec7" # Tether
url = (
f"https://api.etherscan.io/api?module=account&action=balance"
f"&address={test_address}&tag=latest&apikey={api_key}"
)
try:
response = requests.get(url, timeout=15)
response.raise_for_status()
data = response.json()
self.assertEqual(
data.get("status"), "1", f"Etherscan API error: {data.get('message')}"
)
self.assertIn("result", data)
self.assertTrue(int(data["result"]) >= 0, "Invalid balance")
print(f"Etherscan API balance check successful for {test_address}.")
print("Explorer API test passed.")
except requests.exceptions.RequestException as e:
self.fail(f"Etherscan API request failed: {e}")
except Exception as e:
self.fail(f"Etherscan API processing failed: {e}")
# --- Social/Sentiment Data Collector Tests ---
def test_reddit_api(self):
"""Test fetching data via Reddit API (PRAW)."""
print("Testing Reddit API (PRAW)...")
client_id = check_env_var("REDDIT_CLIENT_ID", is_required=True)
client_secret = check_env_var("REDDIT_CLIENT_SECRET", is_required=True)
user_agent = check_env_var("REDDIT_USER_AGENT", is_required=True)
try:
reddit = praw.Reddit(
client_id=client_id,
client_secret=client_secret,
user_agent=user_agent,
read_only=True,
)
subreddit = reddit.subreddit("CryptoCurrency")
self.assertIsNotNone(subreddit.display_name)
submissions = list(subreddit.hot(limit=2))
self.assertLessEqual(len(submissions), 2)
if submissions:
self.assertTrue(hasattr(submissions[0], "title"))
print(
f"Reddit API connection successful. Fetched {len(submissions)} "
f"hot submissions from r/CryptoCurrency."
)
print("Reddit API test passed.")
except Exception as e:
self.fail(f"Reddit API (PRAW) failed: {e}")
@unittest.skip(
"Skipping Stocktwits API test due to potential auth changes (403 Forbidden)."
)
def test_stocktwits_api_skipped(self):
"""Original Stocktwits test - skipped."""
print("Testing Stocktwits API...") # This won't print due to skip
symbol = "BTC.X"
url = f"https://api.stocktwits.com/api/2/streams/symbol/{symbol}.json"
try:
response = requests.get(url, timeout=15)
response.raise_for_status()
data = response.json()
self.assertEqual(data["symbol"]["symbol"], symbol)
self.assertIn("messages", data)
self.assertIsInstance(data["messages"], list)
print(
f"Stocktwits API returned {len(data['messages'])} messages "
f"for ${symbol}."
)
print("Stocktwits API test passed.")
except requests.exceptions.RequestException as e:
self.fail(f"Stocktwits API request failed: {e}")
except Exception as e:
self.fail(f"Stocktwits API processing failed: {e}")
def test_cryptocompare_api(self):
"""Test fetching social stats via CryptoCompare API."""
print("Testing CryptoCompare API (Social Stats)...")
api_key = check_env_var("CRYPTOCOMPARE_API_KEY", is_required=True)
coin_id = 1182 # Bitcoin's ID
url = (
f"https://min-api.cryptocompare.com/data/social/coin/latest"
f"?coinId={coin_id}&api_key={api_key}"
)
try:
response = requests.get(url, timeout=15)
response.raise_for_status()
data = response.json()
self.assertEqual(data.get("Response"), "Success")
self.assertIn("Data", data)
self.assertIn("Reddit", data["Data"])
self.assertIn("Twitter", data["Data"])
print("CryptoCompare API social stats fetch successful.")
print("CryptoCompare API test passed.")
except requests.exceptions.RequestException as e:
self.fail(f"CryptoCompare API request failed: {e}")
except Exception as e:
self.fail(f"CryptoCompare API processing failed: {e}")
# --- AI Model Tests ---
def test_sentiment_analysis(self):
"""Test sentiment analysis via OpenRouter."""
print("Testing Sentiment Analysis (OpenRouter)...")
api_key = check_env_var("OPENROUTER_API_KEY", is_required=True)
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
payload = {
"model": "mistralai/mistral-7b-instruct:free",
"messages": [
{
"role": "system",
"content": (
"Classify the sentiment of the following text as bullish, "
"bearish, or neutral."
),
},
{
"role": "user",
"content": "Bitcoin is rallying hard today, very bullish!",
},
],
"max_tokens": 10,
}
try:
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=payload,
timeout=20,
)
response.raise_for_status()
result = response.json()
self.assertIn("choices", result)
self.assertGreater(len(result["choices"]), 0)
self.assertIn("message", result["choices"][0])
self.assertIn("content", result["choices"][0]["message"])
sentiment = result["choices"][0]["message"]["content"].strip().lower()
self.assertTrue(
"bullish" in sentiment
or "bearish" in sentiment
or "neutral" in sentiment
)
print(f"OpenRouter Sentiment result snippet: {sentiment}")
print("Sentiment Analysis test passed.")
except requests.exceptions.RequestException as e:
self.fail(f"OpenRouter API request failed: {e}")
except Exception as e:
self.fail(f"OpenRouter API processing failed: {e}")
def test_price_prediction_interface(self):
"""Test the interface of the price prediction model (Vertex AI check)."""
print("Testing Price Prediction Interface (Vertex AI check)...")
if not self.vertex_ai_initialized:
self.skipTest("Vertex AI failed to initialize in setUpClass.")
self.assertTrue(self.vertex_ai_initialized, "Vertex AI should be initialized")
try:
models = aiplatform.Model.list(
project=self.gcp_project, location=self.vertex_region
)
print(f"Successfully listed {len(models)} models in Vertex AI.")
except Exception as e:
print(f"Note: Could not list models: {e}. Expected if none deployed.")
print("Vertex AI was initialized successfully (basic check).")
print("Price Prediction interface test passed (basic check).")
# --- Signal Engine Tests ---
@unittest.skip("Components for E2E flow not implemented yet.")
def test_signal_aggregation(self):
"""Test the signal aggregation logic."""
print("Testing Signal Aggregation...") # Won't print
print("Conceptual E2E Smoke Test placeholder passed.")
# --- Alert System Tests ---
@unittest.skip("TelegramNotifier interaction not implemented yet.")
def test_telegram_alerting(self):
"""Test sending a notification via Telegram."""
print("Testing Telegram Alerting...") # Won't print
# --- Database Tests ---
def test_database_connection(self):
"""Test basic connection and query to Supabase."""
print("Testing Database Connection...")
if not self.db_client:
self.skipTest("Supabase client failed to initialize in setUpClass.")
try:
response = (
self.db_client.table("_dummy_table_").select("*").limit(1).execute()
)
print("Supabase connection successful (query executed).")
self.assertIsNotNone(response)
except Exception as e:
error_str = str(e)
if "does not exist" in error_str:
print(
"Supabase connection successful (got expected error for "
"non-existent table)"
)
else:
self.fail(f"Unexpected Supabase error: {e}")
# --- End-to-End Smoke Test (Conceptual) ---
@unittest.skip("Components for E2E flow not implemented yet.")
def test_e2e_smoke_test(self):
"""Conceptual smoke test for a basic data flow."""
print("Running Conceptual E2E Smoke Test...") # Won't print
print("Conceptual E2E Smoke Test placeholder passed.")
# --- Web Scraping Tests ---
def test_coinmarketcap_scraping(self):
"""Test scraping basic data from CoinMarketCap."""
print("Testing CoinMarketCap Scraping...")
try:
url = "https://coinmarketcap.com/currencies/bitcoin/"
headers = {"User-Agent": "Mozilla/5.0 ... Safari/537.36"}
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
price_element = soup.select_one(
'span[data-role="price"]'
) or soup.select_one("span.sc-f70bb44c-0.jxpCgO")
if price_element:
print(f"Bitcoin price found on CoinMarketCap: {price_element.text}")
self.assertIsNotNone(price_element.text)
else:
self.assertIn("Bitcoin", response.text)
print("CoinMarketCap page accessible, but price element not found")
print("CoinMarketCap scraping test passed.")
except Exception as e:
self.fail(f"CoinMarketCap scraping failed: {e}")
def test_cryptonews_scraping(self):
"""Test scraping news headlines from Crypto News."""
print("Testing Crypto News Scraping...")
try:
url = "https://cryptonews.com/"
headers = {"User-Agent": "Mozilla/5.0 ... Safari/537.36"}
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
headline_selectors = [
"article h4",
".news-item h4",
".cn-tile h4",
".article-title",
"h2.article__title",
".cn-content-card .cn-content-card__headline",
"a.article__title",
]
headlines = []
for selector in headline_selectors:
headlines = soup.select(selector)
if headlines:
print(f"Found headlines using selector: {selector}")
break
if not headlines:
headlines = soup.select("h4, h3")[:5]
if headlines:
self.assertGreater(len(headlines), 0)
print(f"Found {len(headlines)} headlines.")
print("CryptoNews scraping test passed.")
else:
self.assertIn("Crypto", response.text)
print("CryptoNews page accessible, but headlines not found")
print("CryptoNews scraping test passed (basic access only).")
except Exception as e:
self.fail(f"CryptoNews scraping failed: {e}")
def test_github_activity_scraping(self):
"""Test scraping GitHub activity for major crypto projects."""
print("Testing GitHub Activity Scraping...")
try:
url = "https://github.com/bitcoin/bitcoin/commits/master"
headers = {"User-Agent": "Mozilla/5.0 ... Safari/537.36"}
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
commit_selectors = [
".TimelineItem-body",
".commit-title",
".commit-message",
".js-commit-title",
".d-flex.flex-auto a.Link--primary",
"p.commit-title",
]
commits = []
for selector in commit_selectors:
commits = soup.select(selector)
if commits:
print(f"Found commits using selector: {selector}")
break
if not commits:
commits = [
elem
for elem in soup.find_all(["a", "p"])
if "commit" in elem.get("href", "")
or "commit" in elem.get("class", "")
]
if commits:
self.assertGreater(len(commits), 0)
print(f"Found {len(commits)} recent commits.")
print("GitHub activity scraping test passed.")
else:
self.assertIn("bitcoin", response.text)
print("GitHub page accessible, but commits not found")
print("GitHub activity scraping test passed (basic access only).")
except Exception as e:
self.fail(f"GitHub activity scraping failed: {e}")
# --- Helper methods for test asset management ---
def add_test_asset(self, symbol="testcoin", name="Test Coin"):
"""Adds a test asset if it doesn't exist, returns its ID."""
from src.database.client import DatabaseClient
db_client = DatabaseClient()
if not db_client.client:
self.skipTest("Could not initialize DatabaseClient for test asset setup.")
existing_asset = db_client.get_asset_by_symbol(symbol)
if existing_asset:
asset_id = existing_asset.get("id")
print(f"Test asset '{symbol}' already exists with ID: {asset_id}")
# Register cleanup even if it existed before, in case other tests need it
self.addCleanup(self.remove_test_asset, symbol)
return asset_id
else:
print(f"Adding test asset '{symbol}'...")
asset_data = {
"symbol": symbol,
"name": name,
"is_active": True,
} # Add other required fields if necessary
try:
response = db_client.client.table("assets").insert(asset_data).execute()
if response.data:
asset_id = response.data[0].get("id")
print(f"Test asset '{symbol}' added with ID: {asset_id}")
self.addCleanup(self.remove_test_asset, symbol) # Register cleanup
return asset_id
else:
self.fail(
f"Failed to insert test asset '{symbol}'. Response: {response}"
)
except Exception as e:
self.fail(f"Failed to insert test asset '{symbol}': {e}")
return None
def remove_test_asset(self, symbol="testcoin"):
"""Removes the test asset."""
from src.database.client import DatabaseClient
db_client = DatabaseClient()
if not db_client or not db_client.client:
print(f"DB client not available for cleanup of asset '{symbol}'.")
return
asset_record = db_client.get_asset_by_symbol(symbol)
if asset_record and "id" in asset_record:
asset_id_to_delete = asset_record["id"]
print(f"Cleaning up test asset '{symbol}' (ID: {asset_id_to_delete})...")
deleted = db_client.delete_record("assets", {"id": asset_id_to_delete})
print(
f"Cleanup "
f"{'successful' if deleted else 'failed or no record found'} "
f"for asset '{symbol}'."
)
else:
print(f"Test asset '{symbol}' not found for cleanup.")
# --- Feedback Logger Test ---
def test_feedback_logger_cycle(self):
"""Test logging a prediction and recording its outcome."""
print("Testing Feedback Logger Cycle...")
# Import datetime here to avoid import redefinition
from datetime import datetime, timedelta, timezone
from src.ml.feedback_logger import FeedbackLogger
# Ensure test asset exists and get its ID
test_asset_symbol = "testcoin_cycle" # Use unique symbol for this test
test_asset_id_int = self.add_test_asset(test_asset_symbol)
if not test_asset_id_int:
self.fail("Failed to add or find test asset for cycle test.")
prediction_id_to_delete = None
feedback_logger = FeedbackLogger()
if not feedback_logger.db_client:
self.skipTest("FeedbackLogger could not initialize DatabaseClient.")
def cleanup_prediction_log():
if prediction_id_to_delete and feedback_logger.db_client:
print(f"\nCleaning up test prediction log: {prediction_id_to_delete}")
deleted = feedback_logger.db_client.delete_record(
"ml_feedback_log", {"prediction_id": prediction_id_to_delete}
)
print(
f"Prediction log cleanup "
f"{'successful' if deleted else 'failed or no record found'}."
)
self.addCleanup(cleanup_prediction_log)
# 1. Log a prediction
# Use 25 hours to ensure different calendar days for .date() comparison
analysis_time = datetime.now(timezone.utc) - timedelta(hours=25)
test_details = {"ta_score": 0.7, "sentiment_score": 0.6, "risk_score": -0.2}
test_patterns = [{"name": "Test Pattern", "confidence": 0.8}]
test_regime = "Bull Trend"
print(f"Attempting to log prediction for {test_asset_symbol}...")
prediction_id = feedback_logger.log_prediction(
analysis_timestamp=analysis_time,
asset_id=test_asset_symbol,
prediction_timeframe="24h",
predicted_outlook="Strong Buy",
predicted_score=0.8,
confidence=90.0,
market_regime=test_regime,
detected_patterns=test_patterns,
analysis_details=test_details,
)
self.assertIsNotNone(prediction_id, "log_prediction failed to return an ID.")
prediction_id_to_delete = prediction_id
print(f"Prediction logged with ID: {prediction_id}")
# 2. Verify prediction was logged
print(f"Verifying prediction log entry {prediction_id} exists...")
logged_data = feedback_logger.db_client.fetch_record(
"ml_feedback_log", {"prediction_id": prediction_id}
)
self.assertIsNotNone(
logged_data, f"Failed to fetch back logged prediction {prediction_id}."
)
self.assertEqual(logged_data.get("asset_id"), test_asset_symbol)
self.assertEqual(logged_data.get("predicted_outlook"), "Strong Buy")
self.assertFalse(
logged_data.get("actual_outcome_recorded"),
"Outcome should not be recorded yet.",
)
print("Prediction log verified.")
# --- Simulate adding price data for the test ---
print("Simulating price data for test (bypassing database insertion)...")
price_at_analysis_time = analysis_time
price_at_outcome_time = analysis_time + timedelta(hours=24)
# Mock the db_client.get_price_at method to return our test prices
original_get_price = feedback_logger.db_client.get_price_at
def mock_get_price(asset_id, timestamp):
if timestamp.date() == price_at_analysis_time.date():
return 100.0
elif timestamp.date() == price_at_outcome_time.date():
return 105.0
return None
feedback_logger.db_client.get_price_at = mock_get_price
# Register cleanup to restore original method
self.addCleanup(
setattr, feedback_logger.db_client, "get_price_at", original_get_price
)
print("Price data simulation set up.")
# 3. Record outcome
print(f"Attempting to record outcome for {prediction_id}...")
feedback_logger.record_outcome(prediction_id)
print("Outcome recording attempted.")
# 4. Verify outcome was recorded
print(f"Verifying outcome for {prediction_id}...")
updated_data = feedback_logger.db_client.fetch_record(
"ml_feedback_log", {"prediction_id": prediction_id}
)
self.assertIsNotNone(
updated_data, f"Failed to fetch back updated prediction {prediction_id}."
)
self.assertTrue(
updated_data.get("actual_outcome_recorded"),
"Outcome flag was not set to True.",
)
self.assertIsNotNone(
updated_data.get("actual_price_change_pct"),
"Actual price change was not recorded.",
)
self.assertAlmostEqual(
updated_data.get("actual_price_change_pct"), 5.0, places=2
)
self.assertIsNotNone(
updated_data.get("outcome_timestamp"), "Outcome timestamp was not recorded."
)
# Optimized back to f-string now that value existence is confirmed
pct = updated_data.get('actual_price_change_pct')
print(f"Outcome verified. Actual Price Change: {pct:.2f}%")
print("Feedback Logger cycle test passed.")
def test_invalid_prediction_logging(self):
"""Test logging predictions with invalid data."""
print("Testing Invalid Prediction Logging...")
# Import locally to avoid F811 redefinition error
from datetime import datetime, timezone
from src.ml.feedback_logger import FeedbackLogger
feedback_logger = FeedbackLogger()
if not feedback_logger.db_client:
self.skipTest("FeedbackLogger could not initialize DatabaseClient.")
# Test case 1: Missing required fields
print("Testing with missing required fields...")
prediction_id_missing = feedback_logger.log_prediction(
analysis_timestamp=datetime.now(timezone.utc),
# asset_id is missing
prediction_timeframe="1h",
predicted_outlook="Neutral",
predicted_score=0.1,
confidence=50.0,
)
self.assertIsNone(
prediction_id_missing,
"log_prediction should return None for missing required fields.",
)
print("Missing fields test passed.")
# Test case 2: Invalid data types (e.g., confidence as string)
print("Testing with invalid data types...")
test_asset_symbol_invalid = "testcoin_invalid"
self.add_test_asset(test_asset_symbol_invalid) # Ensure asset exists
prediction_id_invalid_type = feedback_logger.log_prediction(
analysis_timestamp=datetime.now(timezone.utc),
asset_id=test_asset_symbol_invalid,
prediction_timeframe="4h",
predicted_outlook="Sell",
predicted_score=-0.5,
confidence="high", # Invalid type
)
self.assertIsNone(
prediction_id_invalid_type,
"log_prediction should return None for invalid data types.",
)
print("Invalid data type test passed.")
# Test case 3: Non-existent asset ID
print("Testing with non-existent asset ID...")
prediction_id_nonexistent_asset = feedback_logger.log_prediction(
analysis_timestamp=datetime.now(timezone.utc),
asset_id="nonexistent_coin",
prediction_timeframe="1d",
predicted_outlook="Buy",
predicted_score=0.3,
confidence=75.0,
)
# Depending on implementation, this might succeed or fail gracefully.
# Assuming it should fail or return None if asset_id validation is strict.
# If it logs, we need a cleanup mechanism. For now, assert None.
self.assertIsNone(
prediction_id_nonexistent_asset,
"log_prediction should handle non-existent asset IDs gracefully.",
)
print("Non-existent asset ID test passed.")
# Cleanup the test asset created for invalid type test
self.remove_test_asset(test_asset_symbol_invalid)
def test_record_outcome_for_nonexistent_prediction(self):
"""Test recording outcome for a prediction ID that doesn't exist."""
print("Testing Record Outcome for Nonexistent Prediction...")
from src.ml.feedback_logger import FeedbackLogger
feedback_logger = FeedbackLogger()
if not feedback_logger.db_client:
self.skipTest("FeedbackLogger could not initialize DatabaseClient.")
non_existent_id = "non-existent-uuid-12345"
# This should not raise an error, just log a warning or do nothing
try:
feedback_logger.record_outcome(non_existent_id)
print("record_outcome handled non-existent ID without error.")
except Exception as e:
self.fail(
f"record_outcome raised an unexpected error for non-existent ID: {e}"
)
def test_record_outcome_already_recorded(self):
"""Test recording outcome for a prediction that already has one."""
print("Testing Record Outcome Already Recorded...")
# Import locally
from datetime import datetime, timedelta, timezone
from src.ml.feedback_logger import FeedbackLogger
# Setup: Log a prediction and record its outcome
test_asset_symbol_recorded = "testcoin_recorded"
test_asset_id_recorded = self.add_test_asset(test_asset_symbol_recorded)
if not test_asset_id_recorded:
self.fail("Failed to set up test asset for already recorded test.")
feedback_logger = FeedbackLogger()
if not feedback_logger.db_client:
self.skipTest("FeedbackLogger could not initialize DatabaseClient.")
# Use 25 hours to ensure different calendar days for .date() comparison
analysis_time = datetime.now(timezone.utc) - timedelta(hours=25)
prediction_id = feedback_logger.log_prediction(
analysis_timestamp=analysis_time,
asset_id=test_asset_symbol_recorded,
prediction_timeframe="24h",
predicted_outlook="Hold",
predicted_score=0.0,
confidence=60.0,
)
self.assertIsNotNone(prediction_id)
prediction_id_to_delete = prediction_id # For cleanup
def cleanup_recorded_log():
if prediction_id_to_delete and feedback_logger.db_client:
print(
f"\nCleaning up test prediction log (recorded): "
f"{prediction_id_to_delete}"
)
deleted = feedback_logger.db_client.delete_record(
"ml_feedback_log", {"prediction_id": prediction_id_to_delete}
)
print(
f"Recorded log cleanup "
f"{'successful' if deleted else 'failed or no record found'}."
)
self.addCleanup(cleanup_recorded_log)
self.addCleanup(self.remove_test_asset, test_asset_symbol_recorded)
# Mock price fetching
original_get_price = feedback_logger.db_client.get_price_at
def mock_get_price_recorded(asset_id, timestamp):
if timestamp.date() == analysis_time.date():
return 200.0
elif timestamp.date() == (analysis_time + timedelta(hours=24)).date():
return 198.0 # Slight decrease
return None
feedback_logger.db_client.get_price_at = mock_get_price_recorded
self.addCleanup(
setattr, feedback_logger.db_client, "get_price_at", original_get_price
)
# Record outcome the first time
feedback_logger.record_outcome(prediction_id)
first_outcome_data = feedback_logger.db_client.fetch_record(
"ml_feedback_log", {"prediction_id": prediction_id}
)
self.assertTrue(first_outcome_data.get("actual_outcome_recorded"))
first_outcome_timestamp = first_outcome_data.get("outcome_timestamp")
self.assertIsNotNone(first_outcome_timestamp)
# Also verify the calculation based on mocked prices
self.assertAlmostEqual(
first_outcome_data.get("actual_price_change_pct"),
((198 - 200) / 200) * 100, # Expected -1.0%
places=2,
msg="Initial outcome calculation is incorrect",
)
# Attempt to record outcome again
print("Attempting to record outcome again...")
try:
feedback_logger.record_outcome(prediction_id)
print("Second record_outcome call handled without error.")
except Exception as e:
self.fail(
f"Second record_outcome call raised an unexpected error: {e}"
)
# Verify that the outcome wasn't re-recorded (timestamp should be the same)
second_outcome_data = feedback_logger.db_client.fetch_record(
"ml_feedback_log", {"prediction_id": prediction_id}
)
self.assertEqual(
second_outcome_data.get("outcome_timestamp"),
first_outcome_timestamp,
"Outcome timestamp should not change on second recording attempt.",
)
print("Already recorded outcome test passed.")
# --- Main Execution ---
if __name__ == "__main__":
print("Starting CryptoWildfire Integration Tests...")
unittest.main()