File size: 11,723 Bytes
d6d843f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test real providers to verify they actually work
بررسی واقعی پرووایدرها برای اطمینان از عملکرد
"""

import asyncio
import httpx
import json
from datetime import datetime


async def test_binance_direct():
    """Test Binance API directly"""
    print("\n" + "="*60)
    print("🧪 Testing Binance Provider")
    print("="*60)

    try:
        url = "https://api.binance.com/api/v3/klines"
        params = {
            "symbol": "BTCUSDT",
            "interval": "1h",
            "limit": 5
        }

        async with httpx.AsyncClient(timeout=10) as client:
            response = await client.get(url, params=params)

            print(f"✅ Status Code: {response.status_code}")
            print(f"✅ Response Time: {response.elapsed.total_seconds() * 1000:.0f}ms")

            if response.status_code == 200:
                data = response.json()
                print(f"✅ Data Received: {len(data)} candles")
                print(f"✅ First Candle: {data[0][:6]}")  # Show first 6 fields
                return True, "Binance works perfectly!"
            else:
                return False, f"Error: Status {response.status_code}"

    except Exception as e:
        return False, f"Error: {str(e)}"


async def test_coingecko_direct():
    """Test CoinGecko API directly"""
    print("\n" + "="*60)
    print("🧪 Testing CoinGecko Provider")
    print("="*60)

    try:
        url = "https://api.coingecko.com/api/v3/simple/price"
        params = {
            "ids": "bitcoin,ethereum,solana",
            "vs_currencies": "usd",
            "include_24hr_change": "true",
            "include_24hr_vol": "true"
        }

        async with httpx.AsyncClient(timeout=15) as client:
            response = await client.get(url, params=params)

            print(f"✅ Status Code: {response.status_code}")
            print(f"✅ Response Time: {response.elapsed.total_seconds() * 1000:.0f}ms")

            if response.status_code == 200:
                data = response.json()
                print(f"✅ Coins Received: {list(data.keys())}")
                print(f"✅ BTC Price: ${data['bitcoin']['usd']:,.2f}")
                print(f"✅ BTC 24h Change: {data['bitcoin'].get('usd_24h_change', 0):.2f}%")
                return True, "CoinGecko works perfectly!"
            else:
                return False, f"Error: Status {response.status_code}"

    except Exception as e:
        return False, f"Error: {str(e)}"


async def test_kraken_direct():
    """Test Kraken API directly"""
    print("\n" + "="*60)
    print("🧪 Testing Kraken Provider")
    print("="*60)

    try:
        url = "https://api.kraken.com/0/public/Ticker"
        params = {
            "pair": "XXBTZUSD"
        }

        async with httpx.AsyncClient(timeout=10) as client:
            response = await client.get(url, params=params)

            print(f"✅ Status Code: {response.status_code}")
            print(f"✅ Response Time: {response.elapsed.total_seconds() * 1000:.0f}ms")

            if response.status_code == 200:
                data = response.json()
                if "error" in data and data["error"]:
                    return False, f"Kraken Error: {data['error']}"

                result = data.get("result", {})
                if result:
                    pair_key = list(result.keys())[0]
                    ticker = result[pair_key]
                    print(f"✅ Pair: {pair_key}")
                    print(f"✅ Last Price: ${float(ticker['c'][0]):,.2f}")
                    print(f"✅ 24h Volume: {float(ticker['v'][1]):,.2f}")
                    return True, "Kraken works perfectly!"
                else:
                    return False, "No data in response"
            else:
                return False, f"Error: Status {response.status_code}"

    except Exception as e:
        return False, f"Error: {str(e)}"


async def test_coincap_direct():
    """Test CoinCap API directly"""
    print("\n" + "="*60)
    print("🧪 Testing CoinCap Provider")
    print("="*60)

    try:
        url = "https://api.coincap.io/v2/assets"
        params = {
            "limit": 3
        }

        async with httpx.AsyncClient(timeout=10) as client:
            response = await client.get(url, params=params)

            print(f"✅ Status Code: {response.status_code}")
            print(f"✅ Response Time: {response.elapsed.total_seconds() * 1000:.0f}ms")

            if response.status_code == 200:
                data = response.json()
                assets = data.get("data", [])
                print(f"✅ Assets Received: {len(assets)}")
                for asset in assets[:3]:
                    print(f"   - {asset['symbol']}: ${float(asset['priceUsd']):,.2f}")
                return True, "CoinCap works perfectly!"
            else:
                return False, f"Error: Status {response.status_code}"

    except Exception as e:
        return False, f"Error: {str(e)}"


async def test_fear_greed_index():
    """Test Fear & Greed Index"""
    print("\n" + "="*60)
    print("🧪 Testing Fear & Greed Index")
    print("="*60)

    try:
        url = "https://api.alternative.me/fng/"

        async with httpx.AsyncClient(timeout=10) as client:
            response = await client.get(url)

            print(f"✅ Status Code: {response.status_code}")
            print(f"✅ Response Time: {response.elapsed.total_seconds() * 1000:.0f}ms")

            if response.status_code == 200:
                data = response.json()
                fng = data.get("data", [{}])[0]
                print(f"✅ Value: {fng.get('value')}/100")
                print(f"✅ Classification: {fng.get('value_classification')}")
                print(f"✅ Timestamp: {fng.get('timestamp')}")
                return True, "Fear & Greed Index works!"
            else:
                return False, f"Error: Status {response.status_code}"

    except Exception as e:
        return False, f"Error: {str(e)}"


async def test_hf_data_engine():
    """Test HF Data Engine if running"""
    print("\n" + "="*60)
    print("🧪 Testing HF Data Engine")
    print("="*60)

    try:
        base_url = "http://localhost:8000"

        async with httpx.AsyncClient(timeout=30) as client:
            # Test health
            response = await client.get(f"{base_url}/api/health")

            if response.status_code == 200:
                print(f"✅ HF Engine is RUNNING")
                data = response.json()
                print(f"✅ Status: {data.get('status')}")
                print(f"✅ Uptime: {data.get('uptime')}s")
                print(f"✅ Providers: {len(data.get('providers', []))}")

                # Test prices endpoint
                try:
                    prices_response = await client.get(
                        f"{base_url}/api/prices",
                        params={"symbols": "BTC,ETH"}
                    )
                    if prices_response.status_code == 200:
                        prices_data = prices_response.json()
                        print(f"✅ Prices endpoint works: {len(prices_data.get('data', []))} coins")
                    else:
                        print(f"⚠️  Prices endpoint: Status {prices_response.status_code}")
                except:
                    print("⚠️  Prices endpoint not accessible")

                return True, "HF Data Engine works!"
            else:
                return False, f"HF Engine returned status {response.status_code}"

    except httpx.ConnectError:
        return False, "HF Engine is not running (Connection refused)"
    except Exception as e:
        return False, f"Error: {str(e)}"


async def test_fastapi_backend():
    """Test main FastAPI backend"""
    print("\n" + "="*60)
    print("🧪 Testing FastAPI Backend")
    print("="*60)

    try:
        base_url = "http://localhost:7860"

        async with httpx.AsyncClient(timeout=10) as client:
            response = await client.get(f"{base_url}/health")

            if response.status_code == 200:
                print(f"✅ FastAPI Backend is RUNNING")
                print(f"✅ Status Code: {response.status_code}")

                # Test a few endpoints
                endpoints = ["/api/status", "/api/providers"]
                for endpoint in endpoints:
                    try:
                        resp = await client.get(f"{base_url}{endpoint}")
                        status = "✅" if resp.status_code < 400 else "⚠️"
                        print(f"{status} {endpoint}: Status {resp.status_code}")
                    except:
                        print(f"❌ {endpoint}: Failed")

                return True, "FastAPI Backend works!"
            else:
                return False, f"Backend returned status {response.status_code}"

    except httpx.ConnectError:
        return False, "FastAPI Backend is not running"
    except Exception as e:
        return False, f"Error: {str(e)}"


async def main():
    """Run all tests"""
    print("\n" + "🚀"*30)
    print("تست واقعی همه پرووایدرها")
    print("REAL PROVIDER TESTING")
    print("🚀"*30)

    results = {}

    # Test external providers
    print("\n📡 Testing External API Providers...")
    results["Binance"] = await test_binance_direct()
    await asyncio.sleep(1)

    results["CoinGecko"] = await test_coingecko_direct()
    await asyncio.sleep(1)

    results["Kraken"] = await test_kraken_direct()
    await asyncio.sleep(1)

    results["CoinCap"] = await test_coincap_direct()
    await asyncio.sleep(1)

    results["Fear & Greed"] = await test_fear_greed_index()
    await asyncio.sleep(1)

    # Test internal services
    print("\n🏠 Testing Internal Services...")
    results["HF Data Engine"] = await test_hf_data_engine()
    results["FastAPI Backend"] = await test_fastapi_backend()

    # Summary
    print("\n" + "="*60)
    print("📊 TEST SUMMARY / خلاصه تست")
    print("="*60)

    working = 0
    failed = 0

    for name, (success, message) in results.items():
        status = "✅ WORKING" if success else "❌ FAILED"
        print(f"{status} - {name}")
        print(f"   └─ {message}")

        if success:
            working += 1
        else:
            failed += 1

    print("\n" + "="*60)
    print(f"✅ Working: {working}/{len(results)}")
    print(f"❌ Failed: {failed}/{len(results)}")
    print(f"📊 Success Rate: {(working/len(results)*100):.1f}%")
    print("="*60)

    # Recommendations
    print("\n💡 توصیه‌ها / RECOMMENDATIONS:")

    if results.get("HF Data Engine", (False, ""))[0]:
        print("✅ HF Data Engine is running - You can use it!")
    else:
        print("⚠️  HF Data Engine is not running. Start it with:")
        print("   cd hf-data-engine && python main.py")

    if results.get("FastAPI Backend", (False, ""))[0]:
        print("✅ FastAPI Backend is running - Dashboard ready!")
    else:
        print("⚠️  FastAPI Backend is not running. Start it with:")
        print("   python app.py")

    external_working = sum(1 for k, v in results.items()
                          if k not in ["HF Data Engine", "FastAPI Backend"] and v[0])

    if external_working >= 3:
        print(f"✅ {external_working} external APIs working - Good coverage!")
    else:
        print(f"⚠️  Only {external_working} external APIs working")
        print("   This might be due to IP restrictions or rate limits")

    print("\n✅ Test Complete!")
    return working, failed


if __name__ == "__main__":
    working, failed = asyncio.run(main())
    exit(0 if failed == 0 else 1)