File size: 8,526 Bytes
9853396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { GoogleGenAI } = require('@google/genai');
const { TestConfig } = require('./config');

// Test helper class
class TestHelper {
  constructor() {
    this.config = new TestConfig();
    
    try {
      this.config.validateConfig();
      this.client = new GoogleGenAI({
        apiKey: this.config.apiKey,
        httpOptions:{
            baseUrl: this.config.baseUrl,
            headers: this.config.getHeaders()
        }
      });
    } catch (error) {
      console.log(`Skipping tests due to configuration error: ${error.message}`);
      process.exit(0);
    }
  }
  
  printHeaders() {
    console.log(`Using headers: ${JSON.stringify(this.config.getHeaders())}`);
  }
  
  createTestContext() {
    // In Node.js, we'll pass headers through request options
    return {
      headers: this.config.getHeaders()
    };
  }
  
  assertNoError(error, message) {
    if (error) {
      throw new Error(`${message}: ${error.message}`);
    }
  }
  
  validateChatResponse(response, description) {
    if (!response) {
      throw new Error(`Response is null for ${description}`);
    }
    
    if (!response.candidates || response.candidates.length === 0) {
      throw new Error(`No candidates in response for ${description}`);
    }
    
    const candidate = response.candidates[0];
    if (!candidate.content || !candidate.content.parts || candidate.content.parts.length === 0) {
      throw new Error(`Empty content in response for ${description}`);
    }
    
    console.log(`${description} - Response validated successfully: ${response.candidates.length} candidates`);
  }
  
  getModel() {
    return this.config.model;
  }
}

// Utility functions
function containsCaseInsensitive(text, substring) {
  return text.toLowerCase().includes(substring.toLowerCase());
}

function containsAnyCaseInsensitive(text, ...substrings) {
  return substrings.some(substring => containsCaseInsensitive(text, substring));
}

function extractTextFromResponse(response) {
  if (!response || !response.candidates || response.candidates.length === 0) {
    return '';
  }
  
  const candidate = response.candidates[0];
  if (!candidate.content || !candidate.content.parts || candidate.content.parts.length === 0) {
    return '';
  }
  
  return candidate.content.parts
    .filter(part => part.text)
    .map(part => part.text)
    .join('');
}

function containsNumber(text) {
  const numbers = ['4', 'four', 'Four'];
  return numbers.some(num => containsCaseInsensitive(text, num));
}

// Test functions
async function testSimpleQA() {
  console.log('Running TestSimpleQA...');
  
  const helper = new TestHelper();
  helper.printHeaders();
  
  const context = helper.createTestContext();
  const question = 'What is 2 + 2?';
  
  console.log(`Sending question: ${question}`);
  
  const modelName = helper.getModel();
  
  try {
    const response = await helper.client.models.generateContent({
      model: modelName,
      contents: question,
      ...context
    });
    
    helper.validateChatResponse(response, 'Simple Q&A');
    
    const responseText = extractTextFromResponse(response);
    console.log(`Response: ${responseText}`);
    
    if (!containsNumber(responseText)) {
      throw new Error(`Expected response to contain a number, got: ${responseText}`);
    }
    
    console.log('✅ TestSimpleQA passed');
  } catch (error) {
    console.error('❌ TestSimpleQA failed:', error.message);
    throw error;
  }
}

async function testSimpleQAWithDifferentQuestion() {
  console.log('Running TestSimpleQAWithDifferentQuestion...');
  
  const helper = new TestHelper();
  const context = helper.createTestContext();
  const question = 'What is the capital of France?';
  
  console.log(`Sending question: ${question}`);
  
  const modelName = helper.getModel();
  
  try {
    const response = await helper.client.models.generateContent({
      model: modelName,
      contents: question,
      ...context
    });
    
    helper.validateChatResponse(response, 'Simple Q&A with capital question');
    
    const responseText = extractTextFromResponse(response);
    console.log(`Response: ${responseText}`);
    
    if (!containsCaseInsensitive(responseText, 'Paris')) {
      throw new Error(`Expected response to contain 'Paris', got: ${responseText}`);
    }
    
    console.log('✅ TestSimpleQAWithDifferentQuestion passed');
  } catch (error) {
    console.error('❌ TestSimpleQAWithDifferentQuestion failed:', error.message);
    throw error;
  }
}

async function testMultipleQuestions() {
  console.log('Running TestMultipleQuestions...');
  
  const helper = new TestHelper();
  const context = helper.createTestContext();
  
  const questions = [
    'What is the largest planet in our solar system?',
    'Who wrote Romeo and Juliet?',
    'What is the chemical symbol for gold?'
  ];
  
  const modelName = helper.getModel();
  
  try {
    for (let i = 0; i < questions.length; i++) {
      const question = questions[i];
      console.log(`Question ${i + 1}: ${question}`);
      
      const response = await helper.client.models.generateContent({
        model: modelName,
        contents: question,
        ...context
      });
      
      helper.validateChatResponse(response, `Question ${i + 1}`);
      
      const responseText = extractTextFromResponse(response);
      console.log(`Answer ${i + 1}: ${responseText}`);
    }
    
    console.log('✅ TestMultipleQuestions passed');
  } catch (error) {
    console.error('❌ TestMultipleQuestions failed:', error.message);
    throw error;
  }
}

async function testConversationHistory() {
  console.log('Running TestConversationHistory...');
  
  const helper = new TestHelper();
  const context = helper.createTestContext();
  const modelName = helper.getModel();
  
  try {
    // Start a chat session
    const chat = helper.client.chats.create({
      model: modelName,
      history: [],
      config: {
        temperature: 0.5
      }
    });
    
    // First question
    const question1 = "My name is Alice. What's your name?";
    console.log(`Question 1: ${question1}`);
    
    const response1 = await chat.sendMessage(question1);
    helper.validateChatResponse(response1, 'First message');
    
    const responseText1 = extractTextFromResponse(response1);
    console.log(`Response 1: ${responseText1}`);
    
    // Follow-up question that references the previous context
    const question2 = 'What did I just tell you my name is?';
    console.log(`Question 2: ${question2}`);
    
    const response2 = await chat.sendMessage(question2);
    helper.validateChatResponse(response2, 'Second message');
    
    const responseText2 = extractTextFromResponse(response2);
    console.log(`Response 2: ${responseText2}`);
    
    // Verify the model remembers the name
    if (!containsAnyCaseInsensitive(responseText2, 'Alice', 'alice')) {
      throw new Error(`Expected response to contain 'Alice', got: ${responseText2}`);
    }
    
    console.log('✅ TestConversationHistory passed');
  } catch (error) {
    console.error('❌ TestConversationHistory failed:', error.message);
    throw error;
  }
}

// Main test runner
async function runTests() {
  console.log('🚀 Starting Gemini Node.js Integration Tests\n');
  
  const tests = [
    testSimpleQA,
    testSimpleQAWithDifferentQuestion,
    testMultipleQuestions,
    testConversationHistory
  ];
  
  let passed = 0;
  let failed = 0;
  
  for (const test of tests) {
    try {
      await test();
      passed++;
    } catch (error) {
      failed++;
      console.error(`Test failed: ${error.message}`);
    }
    console.log(''); // Empty line for readability
  }
  
  console.log(`\n📊 Test Results: ${passed} passed, ${failed} failed`);
  
  if (failed > 0) {
    process.exit(1);
  } else {
    console.log('🎉 All tests passed!');
    process.exit(0);
  }
}

// Run tests if this file is executed directly
if (require.main === module) {
  runTests().catch(error => {
    console.error('❌ Test runner failed:', error.message);
    process.exit(1);
  });
}

module.exports = {
  TestConfig,
  TestHelper,
  testSimpleQA,
  testSimpleQAWithDifferentQuestion,
  testMultipleQuestions,
  testConversationHistory,
  runTests
};