-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-twitter-elonmusk.ts
More file actions
241 lines (199 loc) Β· 8.09 KB
/
Copy pathtest-twitter-elonmusk.ts
File metadata and controls
241 lines (199 loc) Β· 8.09 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
import { NestFactory } from '@nestjs/core';
import { AppModule } from './src/app.module';
import { TwitterService } from './src/modules/social-media/services/twitter.service';
async function testTwitterService() {
console.log('π Starting Twitter Service Test for Multiple Accounts');
console.log('β'.repeat(60));
try {
// Create NestJS application
const app = await NestFactory.createApplicationContext(AppModule);
const twitterService = app.get(TwitterService);
console.log('β
NestJS application context created');
console.log('π± Twitter service initialized');
// Check authentication status first
console.log('\nπ Checking authentication status...');
const authStatus = await twitterService.getAuthStatus();
console.log('Authentication Details:');
console.log(` β’ Is Authenticated: ${authStatus.isAuthenticated}`);
console.log(` β’ Is Logged In: ${authStatus.isLoggedIn}`);
console.log(` β’ Credentials Provided: ${authStatus.credentialsProvided}`);
console.log(` β’ Cookies File Exists: ${authStatus.cookiesFileExists}`);
// Run health check
console.log('\nπ₯ Running health check...');
const isHealthy = await twitterService.healthCheck();
console.log(`Health Status: ${isHealthy ? 'β
HEALTHY' : 'β UNHEALTHY'}`);
// Test single handle (existing test)
console.log('\nπ¦ Testing Single Handle: @davidasinclair...');
console.log('β'.repeat(40));
const startTimeSingle = Date.now();
const singleTweets = await twitterService.getRecentTweets('davidasinclair');
const endTimeSingle = Date.now();
console.log(
`β±οΈ Single handle request completed in ${endTimeSingle - startTimeSingle}ms`,
);
console.log(`π Found ${singleTweets.length} tweets for @davidasinclair`);
// Test batch fetching with multiple handles (NEW TEST)
console.log('\nπ Testing Batch Fetching: Multiple Handles...');
console.log('β'.repeat(60));
const testHandles = [
'elonmusk', // Tech entrepreneur
'davidasinclair', // Scientist
'naval', // Tech investor/philosopher
];
console.log(
`π Testing with ${testHandles.length} handles: ${testHandles.join(', ')}`,
);
const startTimeBatch = Date.now();
const batchResults =
await twitterService.getRecentTweetsForHandles(testHandles);
const endTimeBatch = Date.now();
console.log(
`β±οΈ Batch request completed in ${endTimeBatch - startTimeBatch}ms`,
);
// Display batch summary
const summary = twitterService.getBatchSummary(batchResults);
console.log('\nπ Batch Operation Summary:');
console.log('β'.repeat(40));
console.log(` β’ Total Handles: ${summary.total}`);
console.log(` β’ Successful: ${summary.successful}`);
console.log(` β’ Failed: ${summary.failed}`);
console.log(` β’ Success Rate: ${summary.successRate.toFixed(1)}%`);
console.log(` β’ Total Posts Retrieved: ${summary.totalPosts}`);
if (summary.failedHandles.length > 0) {
console.log(` β’ Failed Handles: ${summary.failedHandles.join(', ')}`);
}
// Display detailed results for each handle
console.log('\nπ Detailed Results by Handle:');
console.log('β'.repeat(60));
batchResults.forEach((result, index) => {
console.log(`\n${index + 1}. Handle: @${result.handle}`);
console.log(` Status: ${result.success ? 'β
SUCCESS' : 'β FAILED'}`);
if (result.success) {
console.log(` Posts Found: ${result.posts.length}`);
if (result.posts.length > 0) {
console.log(' Recent Posts:');
result.posts.slice(0, 3).forEach((post, postIndex) => {
console.log(
` ${postIndex + 1}. ${post.createdAt.toISOString().split('T')[0]} - ${post.text.substring(0, 80)}${post.text.length > 80 ? '...' : ''}`,
);
});
if (result.posts.length > 3) {
console.log(` ... and ${result.posts.length - 3} more posts`);
}
} else {
console.log(' No recent posts found (within last 90 days)');
}
} else {
console.log(` Error: ${result.error}`);
}
console.log(` ${'β'.repeat(50)}`);
});
// Get only successful results
const successfulResults = twitterService.getSuccessfulResults(batchResults);
console.log(
`\nβ
Successfully processed ${successfulResults.length} out of ${testHandles.length} handles`,
);
// Performance comparison
console.log('\nβ‘ Performance Comparison:');
console.log('β'.repeat(40));
console.log(
` β’ Single Handle (davidasinclair): ${endTimeSingle - startTimeSingle}ms`,
);
console.log(
` β’ Batch (${testHandles.length} handles): ${endTimeBatch - startTimeBatch}ms`,
);
if (summary.successful > 0) {
const avgTimePerHandle =
(endTimeBatch - startTimeBatch) / summary.successful;
console.log(
` β’ Average per successful handle: ${avgTimePerHandle.toFixed(0)}ms`,
);
}
// Test different handle formats
console.log('\nπ§ͺ Testing different handle formats...');
console.log('β'.repeat(40));
const formatTests = [
'elonmusk', // Plain username
'@elonmusk', // With @ symbol
'https://twitter.com/elonmusk', // Twitter URL
'https://x.com/elonmusk', // X.com URL
];
console.log('Testing format variations for same user:');
formatTests.forEach(format => {
console.log(` β’ Input: "${format}"`);
});
await app.close();
console.log('\nβ
All tests completed successfully!');
} catch (error) {
console.error('\nβ Test failed with error:');
console.error('Error:', error.message);
if (error.stack) {
console.error('Stack:', error.stack);
}
console.log('\nπ§ Troubleshooting Tips:');
console.log('1. Make sure you have a .env file with Twitter credentials:');
console.log(' TWITTER_USERNAME=your_username');
console.log(' TWITTER_PASSWORD=your_password');
console.log(' TWITTER_EMAIL=your_email@example.com');
console.log(
'2. Or set TWITTER_COOKIES environment variable with valid cookies',
);
console.log(
'3. Check if twitter_cookies.json file exists with valid session cookies',
);
console.log('4. Ensure your Twitter account is not locked or suspended');
console.log('5. Check your internet connection');
console.log(
'6. Rate limiting might be causing failures - this is normal behavior',
);
}
}
// Check for required environment variables
function checkEnvironmentSetup() {
console.log('π Checking environment setup...');
const requiredVars = [
'TWITTER_USERNAME',
'TWITTER_PASSWORD',
'TWITTER_EMAIL',
];
const optionalVars = ['TWITTER_COOKIES', 'CACHE_TTL_SOCIAL_MEDIA'];
console.log('\nRequired Environment Variables:');
requiredVars.forEach(varName => {
const value = process.env[varName];
console.log(` ${varName}: ${value ? 'β
Set' : 'β Missing'}`);
});
console.log('\nOptional Environment Variables:');
optionalVars.forEach(varName => {
const value = process.env[varName];
console.log(` ${varName}: ${value ? 'β
Set' : 'βͺ Not set'}`);
});
const hasRequiredVars = requiredVars.every(varName => process.env[varName]);
const hasCookies = process.env.TWITTER_COOKIES;
if (!hasRequiredVars && !hasCookies) {
console.log('\nβ οΈ Warning: No Twitter credentials found!');
console.log('Either set username/password/email OR provide cookies.');
return false;
}
return true;
}
// Main execution
if (require.main === module) {
console.log('π§ͺ Twitter Service Test - Multiple Accounts Batch Testing');
console.log('β'.repeat(60));
const envOk = checkEnvironmentSetup();
console.log('\n');
if (!envOk) {
console.log(
'β οΈ Continuing anyway - service should handle missing credentials gracefully\n',
);
}
testTwitterService()
.then(() => {
console.log('\nπ All done!');
process.exit(0);
})
.catch(error => {
console.error('\nπ₯ Unhandled error:', error);
process.exit(1);
});
}