forked from icereed/paperless-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaperless_test.go
More file actions
621 lines (532 loc) · 17.6 KB
/
paperless_test.go
File metadata and controls
621 lines (532 loc) · 17.6 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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// Helper struct to hold common test data and methods
type testEnv struct {
t *testing.T
server *httptest.Server
client *PaperlessClient
requestCount int
mockResponses map[string]http.HandlerFunc
db *gorm.DB
}
// newTestEnv initializes a new test environment
func newTestEnv(t *testing.T) *testEnv {
env := &testEnv{
t: t,
mockResponses: make(map[string]http.HandlerFunc),
}
// Initialize test database
db, err := InitializeTestDB()
require.NoError(t, err)
env.db = db
// Create a mock server with a handler that dispatches based on URL path
env.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
env.requestCount++
handler, exists := env.mockResponses[r.URL.Path]
if !exists {
t.Fatalf("Unexpected request URL: %s", r.URL.Path)
}
// Set common headers and invoke the handler
assert.Equal(t, "Token test-token", r.Header.Get("Authorization"))
handler(w, r)
}))
// Initialize the PaperlessClient with the mock server URL
env.client = NewPaperlessClient(env.server.URL, "test-token")
env.client.HTTPClient = env.server.Client()
// Add mock response for /api/correspondents/
env.setMockResponse("/api/correspondents/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"results": [{"id": 1, "name": "Alpha"}, {"id": 2, "name": "Beta"}]}`))
})
// Add mock response for /api/document_types/
env.setMockResponse("/api/document_types/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"results": []}`))
})
// Add mock response for /api/custom_fields/
env.setMockResponse("/api/custom_fields/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"results": []}`))
})
return env
}
func InitializeTestDB() (*gorm.DB, error) {
// Use in-memory SQLite for testing
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
if err != nil {
return nil, err
}
// Migrate schema
err = db.AutoMigrate(&ModificationHistory{})
if err != nil {
return nil, err
}
return db, nil
}
// teardown closes the mock server
func (env *testEnv) teardown() {
env.server.Close()
}
// Helper method to set a mock response for a specific path
func (env *testEnv) setMockResponse(path string, handler http.HandlerFunc) {
env.mockResponses[path] = handler
}
// TestNewPaperlessClient tests the creation of a new PaperlessClient instance
func TestNewPaperlessClient(t *testing.T) {
baseURL := "http://example.com"
apiToken := "test-token"
client := NewPaperlessClient(baseURL, apiToken)
assert.Equal(t, "http://example.com", client.BaseURL)
assert.Equal(t, apiToken, client.APIToken)
assert.NotNil(t, client.HTTPClient)
}
// TestDo tests the Do method of PaperlessClient
func TestDo(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
// Set mock response for "/test-path"
env.setMockResponse("/test-path", func(w http.ResponseWriter, r *http.Request) {
// Verify the request method
assert.Equal(t, "GET", r.Method)
// Send a mock response
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message": "success"}`))
})
ctx := context.Background()
resp, err := env.client.Do(ctx, "GET", "/test-path", nil)
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, `{"message": "success"}`, string(body))
}
// TestGetAllTags tests the GetAllTags method, including pagination
func TestGetAllTags(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
// Mock data for paginated responses
page1 := map[string]interface{}{
"results": []map[string]interface{}{
{"id": 1, "name": "tag1"},
{"id": 2, "name": "tag2"},
},
"next": fmt.Sprintf("%s/api/tags/?page=2", env.server.URL),
}
page2 := map[string]interface{}{
"results": []map[string]interface{}{
{"id": 3, "name": "tag3"},
},
"next": nil,
}
// Set mock responses for pagination
env.setMockResponse("/api/tags/", func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("page")
if query == "2" {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(page2)
} else {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(page1)
}
})
ctx := context.Background()
tags, err := env.client.GetAllTags(ctx)
require.NoError(t, err)
expectedTags := map[string]int{
"tag1": 1,
"tag2": 2,
"tag3": 3,
}
assert.Equal(t, expectedTags, tags)
}
// TestGetDocumentsByTags tests the GetDocumentsByTags method
func TestGetDocumentsByTags(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
// Mock data for documents
documentsResponse := GetDocumentsApiResponse{
Results: []GetDocumentApiResponseResult{
{
ID: 1,
Title: "Document 1",
Content: "Content 1",
Tags: []int{1, 2},
Correspondent: 1,
CreatedDate: "1999-09-01",
},
{
ID: 2,
Title: "Document 2",
Content: "Content 2",
Tags: []int{2, 3},
Correspondent: 2,
CreatedDate: "1999-09-02",
},
},
}
// Mock data for tags
tagsResponse := map[string]interface{}{
"results": []map[string]interface{}{
{"id": 1, "name": "tag1"},
{"id": 2, "name": "tag2"},
{"id": 3, "name": "tag3"},
},
"next": nil,
}
// Set mock responses
env.setMockResponse("/api/documents/", func(w http.ResponseWriter, r *http.Request) {
// Verify query parameters
expectedQuery := "tags__name__iexact=tag1&tags__name__iexact=tag2&page_size=25"
assert.Equal(t, expectedQuery, r.URL.RawQuery)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(documentsResponse)
})
env.setMockResponse("/api/tags/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(tagsResponse)
})
ctx := context.Background()
tags := []string{"tag1", "tag2"}
documents, err := env.client.GetDocumentsByTags(ctx, tags, 25)
require.NoError(t, err)
expectedDocuments := []Document{
{
ID: 1,
Title: "Document 1",
Content: "Content 1",
Tags: []string{"tag1", "tag2"},
Correspondent: "Alpha",
CreatedDate: "1999-09-01",
},
{
ID: 2,
Title: "Document 2",
Content: "Content 2",
Tags: []string{"tag2", "tag3"},
Correspondent: "Beta",
CreatedDate: "1999-09-02",
},
}
assert.Equal(t, expectedDocuments, documents)
}
// TestDownloadPDF tests the DownloadPDF method
func TestDownloadPDF(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
document := Document{
ID: 123,
}
// Get sample PDF from tests/pdf/sample.pdf
pdfFile := "tests/pdf/sample.pdf"
pdfContent, err := os.ReadFile(pdfFile)
require.NoError(t, err)
// Set mock response
downloadPath := fmt.Sprintf("/api/documents/%d/download/", document.ID)
env.setMockResponse(downloadPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(pdfContent)
})
ctx := context.Background()
data, err := env.client.DownloadPDF(ctx, document)
require.NoError(t, err)
assert.Equal(t, pdfContent, data)
}
// TestUpdateDocuments tests the UpdateDocuments method
func TestUpdateDocuments(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
// Mock data for documents to update
documents := []DocumentSuggestion{
{
ID: 1,
OriginalDocument: Document{
ID: 1,
Title: "Old Title",
Tags: []string{"tag1", "tag3", "manual", "removeMe"},
CreatedDate: "1999-09-01",
},
SuggestedTitle: "New Title",
SuggestedTags: []string{"tag2", "tag3"},
RemoveTags: []string{"removeMe"},
SuggestedCreatedDate: "1999-09-02",
},
}
idTag1 := 1
idTag2 := 2
idTag3 := 4
// Mock data for tags
tagsResponse := map[string]interface{}{
"results": []map[string]interface{}{
{"id": idTag1, "name": "tag1"},
{"id": idTag2, "name": "tag2"},
{"id": 3, "name": "manual"},
{"id": idTag3, "name": "tag3"},
{"id": 5, "name": "removeMe"},
},
"next": nil,
}
// Set the manual tag
manualTag = "manual"
// Set mock responses
env.setMockResponse("/api/tags/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(tagsResponse)
})
updatePath := fmt.Sprintf("/api/documents/%d/", documents[0].ID)
env.setMockResponse(updatePath, func(w http.ResponseWriter, r *http.Request) {
// Verify the request method
assert.Equal(t, "PATCH", r.Method)
// Read and parse the request body
bodyBytes, err := io.ReadAll(r.Body)
require.NoError(t, err)
defer r.Body.Close()
var updatedFields map[string]interface{}
err = json.Unmarshal(bodyBytes, &updatedFields)
require.NoError(t, err)
// Expected updated fields
expectedFields := map[string]interface{}{
"title": "New Title",
// do not keep previous tags since the tag generation will already take care to include old ones:
"tags": []interface{}{float64(idTag2), float64(idTag3)},
"created_date": "1999-09-02",
}
assert.Equal(t, expectedFields, updatedFields)
w.WriteHeader(http.StatusOK)
})
ctx := context.Background()
err := env.client.UpdateDocuments(ctx, documents, env.db, false)
require.NoError(t, err)
}
// TestUpdateDocuments_RemovingLastTag tests the behavior when removing the last remaining tag
// from a document, which Paperless-NGX REST API does not allow (empty tags array is rejected).
// The test covers two scenarios:
// 1. Document has only the manual tag with other field changes (title) - should update title first,
// then remove the manual tag in a separate call
// 2. Document has only the manual tag with NO other changes - should skip the update entirely
func TestUpdateDocuments_RemovingLastTag(t *testing.T) {
// Set the manual tag for this test
manualTag = "paperless-gpt"
tests := []struct {
name string
document DocumentSuggestion
expectUpdateCalls int
validateCalls func(t *testing.T, calls []map[string]interface{})
}{
{
name: "with_other_field_changes",
document: DocumentSuggestion{
ID: 1,
OriginalDocument: Document{
ID: 1,
Title: "Old Title",
Tags: []string{"paperless-gpt"},
CreatedDate: "1999-09-01",
},
SuggestedTitle: "New Title",
SuggestedTags: []string{},
RemoveTags: []string{},
},
expectUpdateCalls: 2,
validateCalls: func(t *testing.T, calls []map[string]interface{}) {
// First call: should update title but NOT tags
assert.Equal(t, map[string]interface{}{"title": "New Title"}, calls[0],
"First call should only update title, not tags")
// Second call: should remove the manual tag with empty array
tagsValue, tagsPresent := calls[1]["tags"]
require.True(t, tagsPresent, "Second call must include tags field")
tagSlice, ok := tagsValue.([]interface{})
require.True(t, ok, "tags should be an array")
assert.Empty(t, tagSlice, "tags array should be empty to remove manual tag")
},
},
{
name: "no_other_changes",
document: DocumentSuggestion{
ID: 2,
OriginalDocument: Document{
ID: 2,
Title: "Same Title",
Tags: []string{"paperless-gpt"},
CreatedDate: "1999-09-01",
},
SuggestedTitle: "",
SuggestedTags: []string{},
RemoveTags: []string{},
},
expectUpdateCalls: 1,
validateCalls: func(t *testing.T, calls []map[string]interface{}) {
// Should make one call to remove the manual tag with empty array
// Even though there are no other field changes, the manual tag MUST be removed
tagsValue, tagsPresent := calls[0]["tags"]
require.True(t, tagsPresent, "Must include tags field to remove manual tag")
tagSlice, ok := tagsValue.([]interface{})
require.True(t, ok, "tags should be an array")
assert.Empty(t, tagSlice, "tags array should be empty to remove manual tag")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
// Mock tags response
env.setMockResponse("/api/tags/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]interface{}{
"results": []map[string]interface{}{
{"id": 1, "name": "paperless-gpt"},
},
"next": nil,
})
})
// Track update calls (PATCH only, not GET)
var updateCalls []map[string]interface{}
updatePath := fmt.Sprintf("/api/documents/%d/", tt.document.ID)
env.setMockResponse(updatePath, func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
// Return document state after first update (still has paperless-gpt tag)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]interface{}{
"id": tt.document.ID,
"title": "New Title", // Title was updated
"tags": []int{1}, // Still has paperless-gpt tag
"created_date": tt.document.OriginalDocument.CreatedDate,
"content": "",
"correspondent": nil,
"custom_fields": []interface{}{},
"original_file_name": "test.pdf",
"document_type": nil,
})
return
}
// Track PATCH calls
assert.Equal(t, "PATCH", r.Method)
bodyBytes, err := io.ReadAll(r.Body)
require.NoError(t, err)
defer r.Body.Close()
var updatedFields map[string]interface{}
err = json.Unmarshal(bodyBytes, &updatedFields)
require.NoError(t, err)
updateCalls = append(updateCalls, updatedFields)
w.WriteHeader(http.StatusOK)
})
ctx := context.Background()
err := env.client.UpdateDocuments(ctx, []DocumentSuggestion{tt.document}, env.db, false)
require.NoError(t, err)
assert.Len(t, updateCalls, tt.expectUpdateCalls,
"Expected %d update calls, got %d", tt.expectUpdateCalls, len(updateCalls))
if tt.expectUpdateCalls > 0 {
tt.validateCalls(t, updateCalls)
}
})
}
}
// TestUrlEncode tests the urlEncode function
func TestUrlEncode(t *testing.T) {
input := "tag:tag1 tag:tag2"
expected := "tag:tag1+tag:tag2"
result := urlEncode(input)
assert.Equal(t, expected, result)
}
// TestDownloadDocumentAsImages tests the DownloadDocumentAsImages method
func TestDownloadDocumentAsImages(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
document := Document{
ID: 123,
}
// Get sample PDF from tests/pdf/sample.pdf
pdfFile := "tests/pdf/sample.pdf"
pdfContent, err := os.ReadFile(pdfFile)
require.NoError(t, err)
// Set mock response
downloadPath := fmt.Sprintf("/api/documents/%d/download/", document.ID)
env.setMockResponse(downloadPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(pdfContent)
})
ctx := context.Background()
imagePaths, totalPages, err := env.client.DownloadDocumentAsImages(ctx, document.ID, 0)
require.NoError(t, err)
// Verify that exatly one page was extracted
assert.Len(t, imagePaths, 1)
// The path shall end with paperless-gpt/document-123/page000.jpg
assert.Contains(t, imagePaths[0], "paperless-gpt/document-123/page000.jpg")
for _, imagePath := range imagePaths {
_, err := os.Stat(imagePath)
assert.NoError(t, err)
}
// Verify total pages count
assert.Equal(t, 1, totalPages, "Total pages should be 1")
}
func TestDownloadDocumentAsImages_ManyPages(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
document := Document{
ID: 321,
}
// Get sample PDF from tests/pdf/many-pages.pdf
pdfFile := "tests/pdf/many-pages.pdf"
pdfContent, err := os.ReadFile(pdfFile)
require.NoError(t, err)
// Set mock response
downloadPath := fmt.Sprintf("/api/documents/%d/download/", document.ID)
env.setMockResponse(downloadPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(pdfContent)
})
ctx := context.Background()
env.client.CacheFolder = "tests/tmp"
// Clean the cache folder
os.RemoveAll(env.client.CacheFolder)
imagePaths, totalPages, err := env.client.DownloadDocumentAsImages(ctx, document.ID, 50)
require.NoError(t, err)
// Verify that exactly 50 pages were extracted - the original doc contains 52 pages
assert.Len(t, imagePaths, 50)
// The path shall end with tests/tmp/document-321/page000.jpg
for _, imagePath := range imagePaths {
_, err := os.Stat(imagePath)
assert.NoError(t, err)
assert.Contains(t, imagePath, "tests/tmp/document-321/page")
}
// Verify total pages count
assert.Equal(t, 52, totalPages, "Total pages should be 52")
}
// TestDownloadDocumentAsPDF tests the DownloadDocumentAsPDF method
func TestDownloadDocumentAsPDF(t *testing.T) {
env := newTestEnv(t)
defer env.teardown()
documentID := 123
// Get sample PDF from tests/pdf/sample.pdf
pdfFile := "tests/pdf/sample.pdf"
pdfContent, err := os.ReadFile(pdfFile)
require.NoError(t, err)
// Set mock response
downloadPath := fmt.Sprintf("/api/documents/%d/download/", documentID)
env.setMockResponse(downloadPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(pdfContent)
})
ctx := context.Background()
// Test without PDF splitting
pdfPaths, pdfData, totalPages, err := env.client.DownloadDocumentAsPDF(ctx, documentID, 0, false)
require.NoError(t, err)
assert.Empty(t, pdfPaths, "No paths should be returned when split=false")
assert.Equal(t, pdfContent, pdfData)
assert.Equal(t, 1, totalPages)
// Testing with splitting=true would be more complex so we'll skip that for simplicity
}