saemstunes commited on
Commit
fe8cc5a
·
verified ·
1 Parent(s): 504a510

Update tests/test_supabase.py

Browse files
Files changed (1) hide show
  1. tests/test_supabase.py +307 -37
tests/test_supabase.py CHANGED
@@ -1,46 +1,316 @@
1
  import pytest
2
- import sys
3
  import os
 
 
 
4
 
5
- # Add src to path
6
  sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
7
 
8
- from src.supabase_integration import SupabaseIntegration
9
 
10
  class TestSupabaseIntegration:
11
- """Test Supabase integration"""
12
 
13
  def setup_method(self):
14
- """Setup test fixtures"""
15
- self.supabase = SupabaseIntegration("test_url", "test_key")
16
-
17
- def test_get_music_context(self):
18
- """Test music context retrieval"""
19
- context = self.supabase.get_music_context("test query")
20
-
21
- assert isinstance(context, dict)
22
- assert "songs" in context
23
- assert "artists" in context
24
- assert "stats" in context
25
- assert "summary" in context
26
-
27
- def test_generate_summary(self):
28
- """Test summary generation"""
29
- context = {
30
- "stats": {"song_count": 100, "artist_count": 10, "user_count": 1000},
31
- "songs": [{"title": "Test Song", "artist": "Test Artist"}],
32
- "artists": [{"name": "Test Artist"}]
33
- }
34
-
35
- summary = self.supabase.generate_summary(context, "test query")
36
- assert isinstance(summary, str)
37
- assert len(summary) > 0
38
-
39
- def test_fallback_context(self):
40
- """Test fallback context"""
41
- context = self.supabase.get_fallback_context()
42
- assert isinstance(context, dict)
43
- assert "summary" in context
44
-
45
- if __name__ == "__main__":
46
- pytest.main([__file__])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pytest
 
2
  import os
3
+ import sys
4
+ import time
5
+ from datetime import datetime, timedelta
6
 
 
7
  sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
8
 
9
+ from src.supabase_integration import AdvancedSupabaseIntegration
10
 
11
  class TestSupabaseIntegration:
12
+ """Production Supabase integration tests with real database connections"""
13
 
14
  def setup_method(self):
15
+ """Setup real Supabase connection"""
16
+ self.supabase_url = os.environ['SUPABASE_URL']
17
+ self.supabase_key = os.environ['SUPABASE_ANON_KEY']
18
+
19
+ self.supabase = AdvancedSupabaseIntegration(
20
+ supabase_url=self.supabase_url,
21
+ supabase_key=self.supabase_key
22
+ )
23
+
24
+ # Wait for connection to establish
25
+ time.sleep(1)
26
+
27
+ def test_production_connection_established(self):
28
+ """Test that we can establish real connection to production Supabase"""
29
+ assert self.supabase.is_connected() == True
30
+
31
+ # Test actual API endpoint connectivity
32
+ import requests
33
+ response = requests.get(
34
+ f"{self.supabase_url}/rest/v1/",
35
+ headers={"apikey": self.supabase_key},
36
+ timeout=10
37
+ )
38
+ assert response.status_code == 200
39
+
40
+ def test_real_database_schema_access(self):
41
+ """Test access to real database tables and schema"""
42
+ connection_test = self.supabase.test_connection()
43
+
44
+ # Verify we can access all critical tables
45
+ critical_tables = ['tracks', 'artists', 'profiles', 'courses', 'playlists']
46
+
47
+ for table in critical_tables:
48
+ assert table in connection_test['tables']
49
+ assert connection_test['tables'][table]['accessible'] == True
50
+ assert connection_test['tables'][table]['status_code'] == 200
51
+
52
+ def test_real_data_retrieval_performance(self):
53
+ """Test real data retrieval performance from production"""
54
+ start_time = time.time()
55
+
56
+ # Test multiple data retrieval operations
57
+ tracks = self.supabase.get_popular_tracks(limit=10)
58
+ artists = self.supabase.get_popular_artists(limit=10)
59
+ courses = self.supabase.get_recent_courses(limit=10)
60
+ stats = self.supabase.get_platform_stats()
61
+
62
+ end_time = time.time()
63
+ total_duration = end_time - start_time
64
+
65
+ # Performance check - should complete within reasonable time
66
+ assert total_duration < 10.0 # All operations within 10 seconds
67
+
68
+ # Data validation
69
+ assert len(tracks) <= 10
70
+ assert len(artists) <= 10
71
+ assert len(courses) <= 10
72
+ assert isinstance(stats, dict)
73
+
74
+ def test_real_context_generation_performance(self):
75
+ """Test real music context generation performance"""
76
+ test_queries = [
77
+ "guitar lessons",
78
+ "pop music",
79
+ "electronic music production",
80
+ "music theory basics",
81
+ "how to create a playlist"
82
+ ]
83
+
84
+ for query in test_queries:
85
+ start_time = time.time()
86
+ context = self.supabase.get_music_context(query, "test_user")
87
+ end_time = time.time()
88
+
89
+ duration = end_time - start_time
90
+
91
+ # Should generate context within 5 seconds
92
+ assert duration < 5.0
93
+
94
+ # Context should be relevant to query
95
+ assert isinstance(context, dict)
96
+ assert 'summary' in context
97
+ assert len(context['summary']) > 0
98
+
99
+ def test_real_user_context_retrieval(self):
100
+ """Test real user context retrieval with actual user data"""
101
+ # Test with a user that exists in your production database
102
+ # Replace with actual test user IDs from your system
103
+ test_users = [
104
+ "existing_user_1",
105
+ "existing_user_2",
106
+ "existing_user_3"
107
+ ]
108
+
109
+ for user_id in test_users:
110
+ user_context = self.supabase.get_user_context(user_id)
111
+
112
+ assert isinstance(user_context, dict)
113
+ assert 'is_premium' in user_context
114
+ assert 'favorite_genres' in user_context
115
+ assert 'recent_activity' in user_context
116
+ assert 'learning_progress' in user_context
117
+
118
+ # Validate data types
119
+ assert isinstance(user_context['is_premium'], bool)
120
+ assert isinstance(user_context['favorite_genres'], list)
121
+ assert isinstance(user_context['recent_activity'], list)
122
+ assert isinstance(user_context['learning_progress'], dict)
123
+
124
+ def test_real_cache_functionality(self):
125
+ """Test real caching functionality with production data"""
126
+ query = "test cache query"
127
+ user_id = "cache_test_user"
128
+
129
+ # First call - should fetch from database
130
+ start_time = time.time()
131
+ context1 = self.supabase.get_music_context(query, user_id)
132
+ first_duration = time.time() - start_time
133
+
134
+ # Second call - should be faster (cached)
135
+ start_time = time.time()
136
+ context2 = self.supabase.get_music_context(query, user_id)
137
+ second_duration = time.time() - start_time
138
+
139
+ # Contexts should be identical
140
+ assert context1 == context2
141
+
142
+ # Cached call should be faster
143
+ assert second_duration < first_duration
144
+
145
+ def test_real_error_handling_invalid_user(self):
146
+ """Test real error handling with invalid user data"""
147
+ invalid_user_id = "non_existent_user_999999"
148
+
149
+ # Should handle gracefully without crashing
150
+ user_context = self.supabase.get_user_context(invalid_user_id)
151
+
152
+ assert isinstance(user_context, dict)
153
+ assert user_context['is_premium'] == False
154
+ assert user_context['favorite_genres'] == []
155
+ assert user_context['recent_activity'] == []
156
+ assert user_context['learning_progress'] == {}
157
+
158
+ def test_real_data_consistency(self):
159
+ """Test real data consistency across multiple retrievals"""
160
+ # Test that multiple calls return consistent data
161
+ contexts = []
162
+
163
+ for i in range(3):
164
+ context = self.supabase.get_music_context("music courses", f"user_{i}")
165
+ contexts.append(context)
166
+
167
+ # All contexts should have the same structure
168
+ for context in contexts:
169
+ assert 'tracks' in context
170
+ assert 'artists' in context
171
+ assert 'courses' in context
172
+ assert 'stats' in context
173
+ assert 'summary' in context
174
+
175
+ # Stats should be consistent across calls
176
+ stats_values = [context['stats']['track_count'] for context in contexts]
177
+ assert len(set(stats_values)) == 1 # All should be the same
178
+
179
+ def test_real_concurrent_requests(self):
180
+ """Test real concurrent request handling"""
181
+ import threading
182
+
183
+ results = []
184
+ errors = []
185
+
186
+ def test_request(query, user_id):
187
+ try:
188
+ context = self.supabase.get_music_context(query, user_id)
189
+ results.append((query, user_id, context))
190
+ except Exception as e:
191
+ errors.append((query, user_id, str(e)))
192
+
193
+ # Create multiple concurrent requests
194
+ threads = []
195
+ test_cases = [
196
+ ("rock music", "user_1"),
197
+ ("jazz courses", "user_2"),
198
+ ("hip hop artists", "user_3"),
199
+ ("classical music", "user_4"),
200
+ ("music production", "user_5")
201
+ ]
202
+
203
+ for query, user_id in test_cases:
204
+ thread = threading.Thread(target=test_request, args=(query, user_id))
205
+ threads.append(thread)
206
+ thread.start()
207
+
208
+ # Wait for all threads to complete
209
+ for thread in threads:
210
+ thread.join()
211
+
212
+ # Verify all requests completed successfully
213
+ assert len(errors) == 0
214
+ assert len(results) == len(test_cases)
215
+
216
+ # Verify all results are valid
217
+ for query, user_id, context in results:
218
+ assert isinstance(context, dict)
219
+ assert 'summary' in context
220
+ assert len(context['summary']) > 0
221
+
222
+ def test_real_detailed_statistics(self):
223
+ """Test real detailed statistics retrieval"""
224
+ detailed_stats = self.supabase.get_detailed_stats()
225
+
226
+ assert isinstance(detailed_stats, dict)
227
+ assert 'basic' in detailed_stats
228
+ assert 'content_breakdown' in detailed_stats
229
+ assert 'performance' in detailed_stats
230
+
231
+ # Validate basic stats
232
+ basic_stats = detailed_stats['basic']
233
+ assert basic_stats['track_count'] > 0
234
+ assert basic_stats['artist_count'] > 0
235
+ assert basic_stats['user_count'] > 0
236
+
237
+ # Validate content breakdown
238
+ breakdown = detailed_stats['content_breakdown']
239
+ assert 'tracks_by_popularity' in breakdown
240
+ assert 'artists_by_followers' in breakdown
241
+ assert 'courses_by_rating' in breakdown
242
+
243
+ # These should be real distributions from your database
244
+ for distribution in breakdown.values():
245
+ assert isinstance(distribution, list)
246
+ if distribution: # Might be empty in some cases
247
+ for item in distribution:
248
+ assert 'range' in item
249
+ assert 'count' in item
250
+
251
+ def test_real_query_intent_analysis(self):
252
+ """Test real query intent analysis with production data"""
253
+ test_queries = [
254
+ ("How do I create a playlist?", "Instructional"),
255
+ ("What is music theory?", "Explanatory"),
256
+ ("I can't upload my track", "Support"),
257
+ ("Recommend some jazz music", "Discovery"),
258
+ ("How much does premium cost?", "Commercial"),
259
+ ("Tell me about Saem's Tunes", "General")
260
+ ]
261
+
262
+ for query, expected_intent in test_queries:
263
+ analyzed_intent = self.supabase.analyze_query_intent(query)
264
+
265
+ # Should correctly identify intent patterns
266
+ assert analyzed_intent in [
267
+ "Instructional - seeking how-to information",
268
+ "Explanatory - seeking information",
269
+ "Support - seeking technical help",
270
+ "Discovery - seeking recommendations",
271
+ "Commercial - seeking pricing information",
272
+ "General inquiry about platform features"
273
+ ]
274
+
275
+ def test_real_fallback_mechanisms(self):
276
+ """Test real fallback mechanisms when database is unavailable"""
277
+ # Note: We can't easily test database downtime in automated tests
278
+ # But we can verify fallback data structure
279
+
280
+ # Clear cache to force fresh data
281
+ self.supabase.clear_cache()
282
+
283
+ # This should use real data, but verify structure matches fallback expectations
284
+ context = self.supabase.get_music_context("test query", "test_user")
285
+
286
+ # Even with real data, structure should match expected format
287
+ assert 'tracks' in context
288
+ assert 'artists' in context
289
+ assert 'courses' in context
290
+ assert 'stats' in context
291
+ assert 'summary' in context
292
+ assert 'timestamp' in context
293
+
294
+ def test_real_security_integration(self):
295
+ """Test real security integration with production data"""
296
+ # Test that security measures don't interfere with legitimate data access
297
+ legitimate_queries = [
298
+ "music courses for beginners",
299
+ "how to play guitar",
300
+ "best pop songs 2024",
301
+ "music production tutorials",
302
+ "artist dashboard features"
303
+ ]
304
+
305
+ for query in legitimate_queries:
306
+ context = self.supabase.get_music_context(query, "legitimate_user")
307
+
308
+ # Should successfully retrieve context for legitimate queries
309
+ assert isinstance(context, dict)
310
+ assert 'summary' in context
311
+ assert len(context['summary']) > 0
312
+
313
+ def teardown_method(self):
314
+ """Cleanup after tests"""
315
+ if hasattr(self, 'supabase'):
316
+ self.supabase.clear_cache()