-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcomprehensive_test.lua
More file actions
394 lines (327 loc) · 12.5 KB
/
Copy pathcomprehensive_test.lua
File metadata and controls
394 lines (327 loc) · 12.5 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
#!/usr/bin/env lua
-- Comprehensive test for OpenAI integration in Lightroom plugin
-- This test validates the complete integration without requiring actual API calls
print("🧪 Comprehensive OpenAI Integration Test")
print("==========================================")
-- Mock Lightroom SDK environment
local function setupMockEnvironment()
-- Mock LrPrefs
local mockPrefs = {
aiProvider = "openai",
openaiModel = "gpt-4o",
openaiTimeout = 30000,
openaiMaxTokens = 1000,
openaiTemperature = 0.7,
openaiSalt = "test_salt_123",
useHierarchicalKeywords = true,
responseLanguage = "English",
includeGpsExifData = false,
useCustomPrompt = false,
customPrompt = ""
}
_G.import = function(module)
if module == "LrPrefs" then
return {
prefsForPlugin = function() return mockPrefs end
}
elseif module == "LrPasswords" then
return {
store = function(key, value, salt)
print(" 📝 Storing API key with salt: " .. (salt or "none"))
end,
retrieve = function(key, salt)
return "sk-test-key-1234567890"
end
}
elseif module == "LrDate" then
return {
currentTime = function() return os.time() end
}
elseif module == "LrStringUtils" then
return {
encodeBase64 = function(data)
return "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
end,
trimWhitespace = function(str)
return str:match("^%s*(.-)%s*$")
end
}
elseif module == "LrHttp" then
return {
post = function(url, body, headers, method, timeout)
print(" 🌐 HTTP POST to: " .. url)
print(" ⏱️ Timeout: " .. (timeout or "default"))
-- Mock successful OpenAI response
local mockResponse = '{"choices":[{"message":{"content":"{\\"title\\":\\"Test Image\\",\\"caption\\":\\"A test image for validation\\",\\"headline\\":\\"This is a test image used for validating the OpenAI integration\\",\\"keywords\\":\\"test, validation, image, openai\\",\\"instructions\\":\\"No special editing needed\\",\\"location\\":\\"Test Environment\\"}"}}]}'
return mockResponse, {status = 200}
end
}
else
return {}
end
end
-- Mock other required modules
_G.JSON = {
encode = function(obj)
return '{"model":"gpt-4o","messages":[{"role":"user","content":[{"type":"text","text":"test"},{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,test"}}]}]}'
end,
decode = function(str)
if string.find(str, "choices") then
return {
choices = {
{
message = {
content = '{"title":"Test Image","caption":"A test image for validation","headline":"This is a test image used for validating the OpenAI integration","keywords":"test, validation, image, openai","instructions":"No special editing needed","location":"Test Environment"}'
}
}
}
}
else
return {title="Test Image", caption="A test image", keywords="test, image"}
end
end
}
_G.logger = {
infof = function(fmt, ...)
print(" ℹ️ " .. string.format(fmt, ...))
end,
errorf = function(fmt, ...)
print(" ❌ " .. string.format(fmt, ...))
end,
warnf = function(fmt, ...)
print(" ⚠️ " .. string.format(fmt, ...))
end,
tracef = function(fmt, ...)
-- Suppress trace logs in test
end
}
_G.PromptPresets = {
getPresets = function() return {} end,
getPresetNames = function() return {"Default", "Detailed"} end,
getPreset = function(name) return "Test preset for " .. name end
}
end
-- Test 1: Module Loading and Interface Compliance
local function testModuleLoading()
print("\n1️⃣ Testing Module Loading...")
setupMockEnvironment()
-- Load OpenAI module
local success, err = pcall(function()
dofile("src/OpenAIAPI.lua")
end)
if not success then
print(" ❌ Failed to load OpenAIAPI.lua: " .. tostring(err))
return false
end
print(" ✅ OpenAIAPI.lua loaded successfully")
-- Check all required methods exist
local required_methods = {
"getVersions", "storeApiKey", "clearApiKey", "getApiKey", "hasApiKey",
"testConnection", "analyze", "analyzeBatch", "getDefaultPrompt",
"loadPromptFromFile", "getPromptPresets", "getPresetNames", "getPreset"
}
for _, method in ipairs(required_methods) do
if type(OpenAIAPI[method]) ~= "function" then
print(" ❌ Missing method: " .. method)
return false
end
end
print(" ✅ All required methods present")
return true
end
-- Test 2: Provider Factory Integration
local function testProviderFactory()
print("\n2️⃣ Testing Provider Factory Integration...")
local success, err = pcall(function()
dofile("src/AIProviderFactory.lua")
end)
if not success then
print(" ❌ Failed to load AIProviderFactory.lua: " .. tostring(err))
return false
end
print(" ✅ AIProviderFactory.lua loaded successfully")
-- Test provider constants
if not AIProviderFactory.PROVIDERS.OPENAI then
print(" ❌ OpenAI provider constant not found")
return false
end
print(" ✅ OpenAI provider constant found: " .. AIProviderFactory.PROVIDERS.OPENAI)
-- Test provider availability
local providers = AIProviderFactory.getAvailableProviders()
local openai_found = false
for _, provider in ipairs(providers) do
if provider.id == "openai" then
openai_found = true
print(" ✅ OpenAI provider found: " .. provider.name)
print(" 📝 Description: " .. provider.description)
break
end
end
if not openai_found then
print(" ❌ OpenAI provider not found in available providers")
return false
end
return true
end
-- Test 3: API Key Management
local function testApiKeyManagement()
print("\n3️⃣ Testing API Key Management...")
-- Test storing API key
local success = pcall(function()
OpenAIAPI.storeApiKey("sk-test-key-1234567890")
end)
if not success then
print(" ❌ Failed to store API key")
return false
end
print(" ✅ API key stored successfully")
-- Test retrieving API key
local apiKey = OpenAIAPI.getApiKey()
if not apiKey or apiKey == "" then
print(" ❌ Failed to retrieve API key")
return false
end
print(" ✅ API key retrieved: " .. string.sub(apiKey, 1, 10) .. "...")
-- Test hasApiKey
if not OpenAIAPI.hasApiKey() then
print(" ❌ hasApiKey() returned false")
return false
end
print(" ✅ hasApiKey() returned true")
return true
end
-- Test 4: Connection Testing
local function testConnection()
print("\n4️⃣ Testing Connection...")
local result = OpenAIAPI.testConnection()
if not result then
print(" ❌ testConnection() returned nil")
return false
end
if result.status then
print(" ✅ Connection test passed: " .. (result.message or "no message"))
else
print(" ⚠️ Connection test failed: " .. (result.message or "no message"))
print(" (This is expected without real API key)")
end
return true
end
-- Test 5: Image Analysis
local function testImageAnalysis()
print("\n5️⃣ Testing Image Analysis...")
-- Mock image data (small PNG)
local mockImageData = "test_image_data_here"
local mockPhotoObject = {
getFormattedMetadata = function(field)
if field == "fileName" then return "test_image.jpg"
elseif field == "gps" then return "37.7749,-122.4194"
elseif field == "cameraMake" then return "Canon"
elseif field == "cameraModel" then return "EOS R5"
else return nil
end
end
}
local result = OpenAIAPI.analyze("test_image.jpg", mockImageData, mockPhotoObject)
if not result then
print(" ❌ analyze() returned nil")
return false
end
if result.status then
print(" ✅ Analysis completed successfully")
print(" 📝 Title: " .. (result.title or "none"))
print(" 📝 Caption: " .. (result.caption or "none"))
print(" 📝 Keywords: " .. (#result.keywords or 0) .. " found")
else
print(" ⚠️ Analysis failed: " .. (result.message or "no message"))
print(" (This might be expected without real API)")
end
return true
end
-- Test 6: Prompt Management
local function testPromptManagement()
print("\n6️⃣ Testing Prompt Management...")
local defaultPrompt = OpenAIAPI.getDefaultPrompt()
if not defaultPrompt or defaultPrompt == "" then
print(" ❌ getDefaultPrompt() returned empty")
return false
end
print(" ✅ Default prompt generated (" .. string.len(defaultPrompt) .. " chars)")
local presets = OpenAIAPI.getPromptPresets()
if type(presets) ~= "table" then
print(" ❌ getPromptPresets() did not return table")
return false
end
print(" ✅ Prompt presets accessible")
local presetNames = OpenAIAPI.getPresetNames()
if type(presetNames) ~= "table" then
print(" ❌ getPresetNames() did not return table")
return false
end
print(" ✅ Preset names: " .. table.concat(presetNames, ", "))
return true
end
-- Test 7: Configuration Integration
local function testConfiguration()
print("\n7️⃣ Testing Configuration Integration...")
-- Load init file to test preference setup
local success, err = pcall(function()
dofile("src/AiTaggerInit.lua")
end)
if not success then
print(" ❌ Failed to load AiTaggerInit.lua: " .. tostring(err))
return false
end
print(" ✅ Configuration loaded successfully")
-- Check if OpenAI preferences are set
local prefs = import("LrPrefs").prefsForPlugin()
local expectedPrefs = {
"openaiModel", "openaiTimeout", "openaiMaxTokens", "openaiTemperature"
}
for _, pref in ipairs(expectedPrefs) do
if prefs[pref] == nil then
print(" ❌ Missing preference: " .. pref)
return false
else
print(" ✅ " .. pref .. ": " .. tostring(prefs[pref]))
end
end
return true
end
-- Run all tests
local function runAllTests()
local tests = {
{"Module Loading", testModuleLoading},
{"Provider Factory", testProviderFactory},
{"API Key Management", testApiKeyManagement},
{"Connection Testing", testConnection},
{"Image Analysis", testImageAnalysis},
{"Prompt Management", testPromptManagement},
{"Configuration", testConfiguration}
}
local passed = 0
local total = #tests
for i, test in ipairs(tests) do
local name, func = test[1], test[2]
local success = func()
if success then
passed = passed + 1
end
end
print("\n📊 Test Results")
print("================")
print(string.format("✅ Passed: %d/%d tests", passed, total))
if passed == total then
print("🎉 ALL TESTS PASSED - OpenAI integration is ready!")
print("\n📋 Next Steps:")
print("1. Install plugin in Lightroom: build/ai-lr-tagimg.lrplugin/")
print("2. Add your OpenAI API key in plugin settings")
print("3. Select 'OpenAI GPT-4V' as provider")
print("4. Test with real images")
return true
else
print("❌ Some tests failed - review implementation")
return false
end
end
-- Execute tests
return runAllTests()