-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebinfo_test.go
More file actions
1084 lines (977 loc) · 33.7 KB
/
webinfo_test.go
File metadata and controls
1084 lines (977 loc) · 33.7 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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package webinfo
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/gif"
"image/jpeg"
"image/png"
"io"
"mime"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// makeImageBytes creates a solid-color image and encodes it as PNG or JPEG.
func makeImageBytes(w, h int, format string, r, g, b uint8) []byte {
img := image.NewRGBA(image.Rect(0, 0, w, h))
fill := color.RGBA{R: r, G: g, B: b, A: 0xff}
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
img.SetRGBA(x, y, fill)
}
}
var buf bytes.Buffer
switch format {
case "jpeg":
_ = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
case "png":
_ = png.Encode(&buf, img)
}
return buf.Bytes()
}
func TestDownloadThumbnail_Temporary(t *testing.T) {
pngData := makeImageBytes(200, 100, "png", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/img.png" {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngData)
return
}
http.NotFound(w, r)
})
srv := httptest.NewServer(handler)
defer srv.Close()
info := &Webinfo{ImageURL: srv.URL + "/img.png"}
ctx := context.Background()
out, err := info.DownloadThumbnail(ctx, "", 100, true)
if err != nil {
t.Fatalf("DownloadThumbnail returned error: %v", err)
}
defer func() { _ = os.Remove(out) }()
f, ferr := os.Open(filepath.Clean(out))
if ferr != nil {
t.Fatalf("failed to open thumbnail: %v", ferr)
}
defer func() { _ = f.Close() }()
img, _, derr := image.Decode(f)
if derr != nil {
t.Fatalf("failed to decode thumbnail: %v", derr)
}
if img.Bounds().Dx() != 100 {
t.Fatalf("thumbnail width: want %d, got %d", 100, img.Bounds().Dx())
}
}
func TestDownloadThumbnail_Permanent(t *testing.T) {
jpgData := makeImageBytes(300, 150, "jpeg", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/images/pic.jpg" {
w.Header().Set("Content-Type", "image/jpeg")
_, _ = w.Write(jpgData)
return
}
http.NotFound(w, r)
})
srv := httptest.NewServer(handler)
defer srv.Close()
destDir := t.TempDir()
info := &Webinfo{ImageURL: srv.URL + "/images/pic.jpg"}
ctx := context.Background()
out, err := info.DownloadThumbnail(ctx, destDir, 50, false)
if err != nil {
t.Fatalf("DownloadThumbnail returned error: %v", err)
}
defer func() { _ = os.Remove(out) }()
// ensure file is in destDir and contains -thumb
if filepath.Dir(out) != filepath.Clean(destDir) {
t.Fatalf("thumbnail path dir: want %q, got %q", destDir, filepath.Dir(out))
}
if !strings.Contains(filepath.Base(out), "-thumb") {
t.Fatalf("thumbnail filename should contain -thumb: %q", out)
}
f, ferr := os.Open(filepath.Clean(out))
if ferr != nil {
t.Fatalf("failed to open thumbnail: %v", ferr)
}
defer func() { _ = f.Close() }()
img, _, derr := image.Decode(f)
if derr != nil {
t.Fatalf("failed to decode thumbnail: %v", derr)
}
if img.Bounds().Dx() != 50 {
t.Fatalf("thumbnail width: want %d, got %d", 50, img.Bounds().Dx())
}
}
// minimal PNG/JPEG signatures for content-type detection
var pngSig = []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n', 0, 0, 0, 0}
var jpgSig = []byte{0xff, 0xd8, 0xff, 0xe0, 0, 0, 'J', 'F', 'I', 'F'}
// helper to read file contents
func readFile(t *testing.T, path string) []byte {
t.Helper()
b, err := os.ReadFile(filepath.Clean(path))
if err != nil {
t.Fatalf("read file: %v", err)
}
return b
}
func TestDownloadImage_NilReceiver(t *testing.T) {
var w *Webinfo
_, err := w.DownloadImage(context.Background(), "", true)
if err == nil {
t.Fatalf("expected error for nil receiver")
}
}
func TestDownloadImage_SaveWithFilename(t *testing.T) {
// serve a PNG at /images/pic.png
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngSig)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/images/pic.png", UserAgent: ""}
out, err := w.DownloadImage(context.Background(), dest, false)
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
want := filepath.Join(dest, "pic.png")
if out != want {
t.Fatalf("unexpected path: got %q want %q", out, want)
}
got := readFile(t, out)
if !bytes.Equal(got, pngSig) {
t.Fatalf("content mismatch")
}
}
func TestDownloadImage_TemporaryWhenNoFilenameAndContentType(t *testing.T) {
// serve a JPEG at root (no filename in path) with Content-Type header
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/jpeg")
_, _ = wr.Write(jpgSig)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
// URL ending with "/" causes srcFname to be "/" and thus temporary forced true
w := &Webinfo{ImageURL: srv.URL + "/", UserAgent: ""}
out, err := w.DownloadImage(context.Background(), dest, false) // pass false; function should switch to temporary
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
if !strings.HasPrefix(out, dest) {
t.Fatalf("tmp file not created in dest: %s", out)
}
ext := filepath.Ext(out)
if ext != ".jpg" && ext != ".jpeg" && ext != ".img" {
t.Fatalf("unexpected extension %q", ext)
}
got := readFile(t, out)
if !bytes.Equal(got, jpgSig) {
t.Fatalf("content mismatch")
}
}
func TestDownloadImage_SniffingDeterminesExtension(t *testing.T) {
// serve PNG bytes but omit Content-Type header to force sniffing
handler := func(wr http.ResponseWriter, r *http.Request) {
// no Content-Type header
_, _ = wr.Write(pngSig)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
// nested dest dir to ensure MkdirAll behavior
base := t.TempDir()
dest := filepath.Join(base, "nested", "sub")
w := &Webinfo{ImageURL: srv.URL + "/", UserAgent: ""}
out, err := w.DownloadImage(context.Background(), dest, false) // should become temporary and use sniffed ext
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
if !strings.HasPrefix(out, base) {
t.Fatalf("output path not under base: %s", out)
}
ext := filepath.Ext(out)
if ext != ".png" && ext != ".img" {
t.Fatalf("unexpected extension %q", ext)
}
got := readFile(t, out)
if !bytes.Equal(got, pngSig) {
t.Fatalf("content mismatch")
}
}
func TestDownloadImage_MkdirAllFails(t *testing.T) {
// create a file where a directory is expected so MkdirAll fails
base := t.TempDir()
blocker := filepath.Join(base, "blocked")
if err := os.WriteFile(filepath.Clean(blocker), []byte("notadir"), 0o600); err != nil {
t.Fatalf("create blocker file: %v", err)
}
// dest path includes the blocker as a path component; MkdirAll should fail
dest := filepath.Join(blocker, "nested")
w := &Webinfo{ImageURL: "http://example.invalid/img.png"}
_, err := w.DownloadImage(context.Background(), dest, true)
if err == nil {
t.Fatalf("expected error when MkdirAll cannot create directories, got nil")
}
}
func TestDownloadImage_ReadFullReturnsError(t *testing.T) {
// override the default transport so the HTTP client used in DownloadImage
// receives a response whose Body returns a non-EOF error on Read.
orig := http.DefaultTransport
defer func() { http.DefaultTransport = orig }()
// errReader is defined at package scope below.
rt := roundTripperFunc(func(req *http.Request) (*http.Response, error) {
// return a response with no Content-Type header and a Body that errors
return &http.Response{
StatusCode: 200,
Status: "200 OK",
Header: make(http.Header),
Body: errReader{},
Request: req,
}, nil
})
http.DefaultTransport = rt
dest := t.TempDir()
w := &Webinfo{ImageURL: "http://example.invalid/"}
_, err := w.DownloadImage(context.Background(), dest, false)
if err == nil {
t.Fatalf("expected error when ReadFull returns non-EOF error, got nil")
}
}
func TestDownloadImage_CopyReadFails(t *testing.T) {
// RoundTripper that returns a response whose Body returns a non-EOF error after sniffing
orig := http.DefaultTransport
defer func() { http.DefaultTransport = orig }()
rt := roundTripperFunc(func(req *http.Request) (*http.Response, error) {
b := &failingBody{
firstData: pngSig, // allow sniffing to see PNG signature
firstErr: io.ErrUnexpectedEOF,
subsequentErr: errors.New("simulated read error"),
}
return &http.Response{
StatusCode: 200,
Status: "200 OK",
Header: make(http.Header),
Body: b,
Request: req,
}, nil
})
http.DefaultTransport = rt
dest := t.TempDir()
w := &Webinfo{ImageURL: "http://example.invalid/"}
_, err := w.DownloadImage(context.Background(), dest, false)
if err == nil {
t.Fatalf("expected error when io.Copy encounters read error, got nil")
}
}
// helper types used by tests
type errReader struct{}
func (errReader) Read(p []byte) (int, error) { return 0, errors.New("simulated read error") }
func (errReader) Close() error { return nil }
// helper type to allow inline RoundTripper function
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
// failingBody allows simulating read and close failures in response bodies.
type failingBody struct {
// firstRead returns data and an optional error for the initial sniffing ReadFull call
firstData []byte
firstErr error
// subsequentErr is returned on subsequent Read calls (to simulate io.Copy failing)
subsequentErr error
closeErr error
closed bool
}
func (b *failingBody) Read(p []byte) (int, error) {
if len(b.firstData) > 0 {
n := copy(p, b.firstData)
// consume firstData
b.firstData = b.firstData[n:]
if len(b.firstData) == 0 {
return n, b.firstErr
}
return n, nil
}
if b.subsequentErr != nil {
return 0, b.subsequentErr
}
return 0, io.EOF
}
func (b *failingBody) Close() error {
b.closed = true
if b.closeErr != nil {
return b.closeErr
}
return nil
}
// zeroImg implements image.Image but reports a zero width to exercise
// the zero-dimension handling in DownloadThumbnail.
type zeroImg struct{}
func (zeroImg) ColorModel() color.Model { return color.RGBAModel }
func (zeroImg) Bounds() image.Rectangle { return image.Rect(0, 0, 0, 10) }
func (zeroImg) At(x, y int) color.Color { return color.RGBA{0, 0, 0, 0} }
func TestOutputImage_EncodersAndFallback(t *testing.T) {
// create a simple source image
src := image.NewRGBA(image.Rect(0, 0, 20, 10))
// fill to avoid zero-content
for y := 0; y < 10; y++ {
for x := 0; x < 20; x++ {
src.SetRGBA(x, y, color.RGBA{R: 0x12, G: 0x34, B: 0x56, A: 0xff})
}
}
formats := []string{"jpeg", "png", "gif", "unknown"}
for _, fmtName := range formats {
tmp := t.TempDir()
fpath := filepath.Join(tmp, "out")
f, err := os.Create(filepath.Clean(fpath))
if err != nil {
t.Fatalf("create file: %v", err)
}
// ensure close before decode
if err := outputImage(f, src, fmtName); err != nil {
// for unknown format we still expect PNG encoding
t.Fatalf("outputImage(%s) error: %v", fmtName, err)
}
if err := f.Close(); err != nil {
t.Fatalf("close file: %v", err)
}
// reopen and decode
rb, rerr := os.ReadFile(filepath.Clean(fpath))
if rerr != nil {
t.Fatalf("read file: %v", rerr)
}
if _, _, derr := image.Decode(bytes.NewReader(rb)); derr != nil {
t.Fatalf("decoded output (%s) failed: %v", fmtName, derr)
}
}
}
func TestOutputImage_ClosedDstReturnsError(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 4, 4))
f, err := os.CreateTemp("", "closed-*")
if err != nil {
t.Fatalf("create temp: %v", err)
}
name := f.Name()
if err := f.Close(); err != nil {
t.Fatalf("close temp: %v", err)
}
// reopen read-only to ensure writes fail
ro, _ := os.Open(filepath.Clean(name))
defer func() { _ = ro.Close(); _ = os.Remove(name) }()
if err := outputImage(ro, src, "png"); err == nil {
t.Fatalf("expected error when writing to non-writable file")
}
}
func TestDownloadImage_ContentTypeWithCharset(t *testing.T) {
pngBytes := makeImageBytes(16, 8, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png; charset=utf-8")
_, _ = wr.Write(pngBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/"}
out, err := w.DownloadImage(context.Background(), dest, false)
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
defer func() { _ = os.Remove(out) }()
ext := filepath.Ext(out)
if ext != ".png" && ext != ".img" {
t.Fatalf("unexpected extension %q", ext)
}
}
func TestDownloadImage_BadURL(t *testing.T) {
w := &Webinfo{ImageURL: "://bad-url"}
_, err := w.DownloadImage(context.Background(), "", true)
if err == nil {
t.Fatalf("expected error for bad URL, got nil")
}
}
func TestDownloadImage_AppendExtWhenNoSrcExt(t *testing.T) {
// serve PNG at /images/pic (no extension in URL)
pngBytes := makeImageBytes(12, 6, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/images/pic"}
out, err := w.DownloadImage(context.Background(), dest, false)
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
defer func() { _ = os.Remove(out) }()
want := filepath.Join(dest, "pic.png")
if out != want {
t.Fatalf("unexpected path: got %q want %q", out, want)
}
b, rerr := os.ReadFile(filepath.Clean(out))
if rerr != nil {
t.Fatalf("read out file: %v", rerr)
}
if !bytes.Equal(b, pngBytes) {
t.Fatalf("content mismatch")
}
}
func TestDownloadImage_TemporaryWithoutDestDirUsesOSTemp(t *testing.T) {
pngBytes := makeImageBytes(6, 3, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
w := &Webinfo{ImageURL: srv.URL + "/img.png"}
out, err := w.DownloadImage(context.Background(), "", true)
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
defer func() { _ = os.Remove(out) }()
// check that filename matches the expected temporary pattern
base := filepath.Base(out)
if !strings.HasPrefix(base, "webinfo-image-") {
t.Fatalf("temporary file name does not match pattern: %s", base)
}
if filepath.Ext(base) == "" {
t.Fatalf("temporary file missing extension: %s", base)
}
}
func makeGIFBytes(w, h int) []byte {
pal := []color.Color{color.RGBA{R: 0xff, G: 0x00, B: 0x00, A: 0xff}, color.RGBA{R: 0x00, G: 0xff, B: 0x00, A: 0xff}}
img := image.NewPaletted(image.Rect(0, 0, w, h), pal)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
if (x+y)%2 == 0 {
img.SetColorIndex(x, y, 0)
} else {
img.SetColorIndex(x, y, 1)
}
}
}
var buf bytes.Buffer
_ = gif.Encode(&buf, img, nil)
return buf.Bytes()
}
func TestDownloadImage_GIF_SaveAndThumbnail(t *testing.T) {
gifBytes := makeGIFBytes(40, 20)
handler := func(wr http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/images/pic.gif" {
wr.Header().Set("Content-Type", "image/gif")
_, _ = wr.Write(gifBytes)
return
}
http.NotFound(wr, r)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/images/pic.gif"}
// Test DownloadImage saves with .gif
out, err := w.DownloadImage(context.Background(), dest, false)
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
defer func() { _ = os.Remove(out) }()
if filepath.Ext(out) != ".gif" {
t.Fatalf("expected .gif extension, got %q", filepath.Ext(out))
}
// Test DownloadThumbnail produces a GIF thumbnail when format is gif
thumb, err := w.DownloadThumbnail(context.Background(), dest, 20, false)
if err != nil {
t.Fatalf("DownloadThumbnail failed: %v", err)
}
defer func() { _ = os.Remove(thumb) }()
if filepath.Ext(thumb) != ".gif" {
t.Fatalf("expected thumbnail .gif extension, got %q", filepath.Ext(thumb))
}
// open and decode
fb, ferr := os.ReadFile(filepath.Clean(thumb))
if ferr != nil {
t.Fatalf("read thumb: %v", ferr)
}
if _, _, derr := image.Decode(bytes.NewReader(fb)); derr != nil {
t.Fatalf("decode thumb failed: %v", derr)
}
}
func TestDownloadImage_MultipleExtensionsByType(t *testing.T) {
// ensure mime package returns multiple extensions for a custom type
// register two synthetic extensions for a custom content type; the code under test picks the last one
_ = mime.AddExtensionType(".ex1my", "image/x-mytest")
_ = mime.AddExtensionType(".ex2my", "image/x-mytest")
pngBytes := makeImageBytes(10, 5, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
// omit filename extension; rely on Content-Type header
wr.Header().Set("Content-Type", "image/x-mytest")
_, _ = wr.Write(pngBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
base := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/"}
out, err := w.DownloadImage(context.Background(), base, false)
if err != nil {
t.Fatalf("DownloadImage failed: %v", err)
}
defer func() { _ = os.Remove(out) }()
// expect the last extension added (".ex2my") to be chosen
if filepath.Ext(out) != ".ex2my" {
t.Fatalf("expected extension .ex2my, got %q", filepath.Ext(out))
}
}
func TestOutputImage_WriteFails(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 8, 8))
// create a temp file and open it read-only to force write failure
tmp, err := os.CreateTemp("", "rofile-*")
if err != nil {
t.Fatalf("create temp: %v", err)
}
name := tmp.Name()
if err := tmp.Close(); err != nil {
t.Fatalf("close tmp: %v", err)
}
ro, err := os.Open(filepath.Clean(name))
if err != nil {
t.Fatalf("open read-only: %v", err)
}
defer func() { _ = ro.Close(); _ = os.Remove(name) }()
if err := outputImage(ro, src, "png"); err == nil {
t.Fatalf("expected error when writing to read-only file")
}
}
func TestDownloadImage_CreateFileFails(t *testing.T) {
pngBytes := makeImageBytes(6, 6, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
// override createFile to simulate failure when creating permanent files
orig := createFile
defer func() { createFile = orig }()
createFile = func(temp bool, dir, pathOrPattern string) (*os.File, error) {
if !temp {
return nil, errors.New("simulated permanent create failure")
}
return orig(temp, dir, pathOrPattern)
}
w := &Webinfo{ImageURL: srv.URL + "/images/pic.png"}
_, err := w.DownloadImage(context.Background(), dest, false)
if err == nil {
t.Fatalf("expected error when permanent file creation fails, got nil")
}
}
func TestDownloadImage_TemporaryCreateFails(t *testing.T) {
pngBytes := makeImageBytes(8, 8, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
// override createFile to simulate failure when creating temporary files
orig := createFile
defer func() { createFile = orig }()
createFile = func(temp bool, dir, pathOrPattern string) (*os.File, error) {
if temp {
return nil, errors.New("simulated temp create failure")
}
return orig(temp, dir, pathOrPattern)
}
w := &Webinfo{ImageURL: srv.URL + "/img.png"}
_, err := w.DownloadImage(context.Background(), t.TempDir(), true)
if err == nil {
t.Fatalf("expected error when temporary file creation fails, got nil")
}
}
func TestDownloadThumbnail_TemporaryCreateFails(t *testing.T) {
pngData := makeImageBytes(80, 40, "png", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngData)
})
srv := httptest.NewServer(handler)
defer srv.Close()
// override createFile to simulate failure when creating any temporary file
orig := createFile
defer func() { createFile = orig }()
createFile = func(temp bool, dir, pathOrPattern string) (*os.File, error) {
if temp {
return nil, errors.New("simulated temp create failure")
}
return orig(temp, dir, pathOrPattern)
}
w := &Webinfo{ImageURL: srv.URL + "/images/pic.png"}
_, err := w.DownloadThumbnail(context.Background(), t.TempDir(), 50, true)
if err == nil {
t.Fatalf("expected error when temporary thumbnail creation fails, got nil")
}
}
func TestDownloadThumbnail_OutputCreateFails(t *testing.T) {
// failure only for thumbnail output file, not for the intermediate original image download
pngData := makeImageBytes(80, 40, "png", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngData)
})
srv := httptest.NewServer(handler)
defer srv.Close()
// override createFile to simulate failure only for thumbnail temporary file
orig := createFile
defer func() { createFile = orig }()
createFile = func(temp bool, dir, pathOrPattern string) (*os.File, error) {
if temp && strings.Contains(pathOrPattern, "webinfo-thumb-") {
return nil, errors.New("simulated thumbnail temp create failure")
}
return orig(temp, dir, pathOrPattern)
}
// Use a dest dir for the thumbnail so createFile is called for the thumb
w := &Webinfo{ImageURL: srv.URL + "/images/pic.png"}
_, err := w.DownloadThumbnail(context.Background(), t.TempDir(), 50, true)
if err == nil {
t.Fatalf("expected error when thumbnail temporary creation fails, got nil")
}
}
func TestDownloadThumbnail_NilReceiver(t *testing.T) {
var w *Webinfo
_, err := w.DownloadThumbnail(context.Background(), "", 100, true)
if err == nil {
t.Fatalf("expected error for nil receiver")
}
}
func TestDownloadImage_HTTPClientTimeout(t *testing.T) {
// server delays longer than client timeout
handler := func(w http.ResponseWriter, r *http.Request) {
time.Sleep(200 * time.Millisecond)
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngSig)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
// override newHTTPClient to return a short timeout
orig := newHTTPClient
defer func() { newHTTPClient = orig }()
newHTTPClient = func() *http.Client { return &http.Client{Timeout: 50 * time.Millisecond} }
w := &Webinfo{ImageURL: srv.URL + "/img.png"}
_, err := w.DownloadImage(context.Background(), t.TempDir(), true)
if err == nil {
t.Fatalf("expected timeout error, got nil")
}
}
func TestDownloadThumbnail_TemporaryPNG_DefaultWidth(t *testing.T) {
// original image 200x100 -> expected thumbnail width 150 (default), height 75
pngBytes := makeImageBytes(200, 100, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/images/pic.png", UserAgent: ""}
out, err := w.DownloadThumbnail(context.Background(), dest, 0, true) // width 0 -> default 150
if err != nil {
t.Fatalf("DownloadThumbnail failed: %v", err)
}
if !strings.HasPrefix(out, dest) {
t.Fatalf("thumbnail not created in dest: %s", out)
}
ext := filepath.Ext(out)
if ext != ".png" && ext != ".img" {
t.Fatalf("unexpected extension %q", ext)
}
// verify dimensions
fb, err := os.ReadFile(filepath.Clean(out))
if err != nil {
t.Fatalf("read thumbnail: %v", err)
}
img, _, derr := image.Decode(bytes.NewReader(fb))
if derr != nil {
t.Fatalf("decode thumbnail: %v", derr)
}
if img.Bounds().Dx() != 150 {
t.Fatalf("unexpected thumb width: got %d want %d", img.Bounds().Dx(), 150)
}
if img.Bounds().Dy() != 75 {
t.Fatalf("unexpected thumb height: got %d want %d", img.Bounds().Dy(), 75)
}
}
func TestDownloadThumbnail_NonTemporaryJPEG_FilenameDerived(t *testing.T) {
// original 100x100 -> thumbnail 50x50
jpgBytes := makeImageBytes(100, 100, "jpeg", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/jpeg")
_, _ = wr.Write(jpgBytes)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/images/pic.jpg", UserAgent: ""}
out, err := w.DownloadThumbnail(context.Background(), dest, 50, false)
if err != nil {
t.Fatalf("DownloadThumbnail failed: %v", err)
}
want := filepath.Join(dest, "pic-thumb.jpg")
if out != want {
t.Fatalf("unexpected path: got %q want %q", out, want)
}
// verify dimensions
fb, err := os.ReadFile(filepath.Clean(out))
if err != nil {
t.Fatalf("read thumbnail: %v", err)
}
img, _, derr := image.Decode(bytes.NewReader(fb))
if derr != nil {
t.Fatalf("decode thumbnail: %v", derr)
}
if img.Bounds().Dx() != 50 || img.Bounds().Dy() != 50 {
t.Fatalf("unexpected thumb size: got %dx%d want %dx%d", img.Bounds().Dx(), img.Bounds().Dy(), 50, 50)
}
}
func TestDownloadThumbnail_MkdirAllFails(t *testing.T) {
// create a file where a directory is expected so MkdirAll fails
base := t.TempDir()
blocker := filepath.Join(base, "blocked")
if err := os.WriteFile(filepath.Clean(blocker), []byte("notadir"), 0o600); err != nil {
t.Fatalf("create blocker file: %v", err)
}
// dest path includes the blocker as a path component; MkdirAll should fail
dest := filepath.Join(blocker, "nested")
w := &Webinfo{ImageURL: "http://example.invalid/img.png"}
_, err := w.DownloadThumbnail(context.Background(), dest, 100, true)
if err == nil {
t.Fatalf("expected error when MkdirAll cannot create directories, got nil")
}
}
func TestDownloadThumbnail_BaseFallbackWhenURLHasNoBasename(t *testing.T) {
pngData := makeImageBytes(120, 60, "png", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngData)
})
srv := httptest.NewServer(handler)
defer srv.Close()
dest := t.TempDir()
// URL ends with '/', so basename logic should fall back to "webinfo-image"
w := &Webinfo{ImageURL: srv.URL + "/"}
out, err := w.DownloadThumbnail(context.Background(), dest, 30, false)
if err != nil {
t.Fatalf("DownloadThumbnail failed: %v", err)
}
defer func() { _ = os.Remove(out) }()
want := filepath.Join(dest, "webinfo-image-thumb.png")
if out != want {
t.Fatalf("unexpected thumbnail path: got %q want %q", out, want)
}
}
func TestDownloadImage_NoImageURL(t *testing.T) {
w := &Webinfo{ImageURL: ""}
_, err := w.DownloadImage(context.Background(), "", true)
if err == nil {
t.Fatalf("expected error for empty ImageURL, got nil")
}
}
func TestDownloadThumbnail_ZeroOrigDimensions(t *testing.T) {
// server returns a small PNG but we override decodeImage to return a
// zero-width image to exercise the origW==0 || origH==0 error path.
pngData := makeImageBytes(4, 4, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngData)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
// override decodeImage
origDecode := decodeImage
defer func() { decodeImage = origDecode }()
decodeImage = func(r io.Reader) (image.Image, string, error) {
return zeroImg{}, "png", nil
}
w := &Webinfo{ImageURL: srv.URL + "/img.png"}
_, err := w.DownloadThumbnail(context.Background(), t.TempDir(), 50, true)
if err == nil {
t.Fatalf("expected error when decoded image has zero dimension, got nil")
}
}
func TestDownloadThumbnail_HeightClampedToOne(t *testing.T) {
// original image very wide but 1px tall -> newH may round to 0 and should be clamped to 1
pngData := makeImageBytes(1000, 1, "png", 0x11, 0x88, 0x22)
handler := func(wr http.ResponseWriter, r *http.Request) {
wr.Header().Set("Content-Type", "image/png")
_, _ = wr.Write(pngData)
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/images/wide.png"}
out, err := w.DownloadThumbnail(context.Background(), dest, 1, true)
if err != nil {
t.Fatalf("DownloadThumbnail failed: %v", err)
}
defer func() { _ = os.Remove(out) }()
fb, err := os.ReadFile(filepath.Clean(out))
if err != nil {
t.Fatalf("read thumbnail: %v", err)
}
img, _, derr := image.Decode(bytes.NewReader(fb))
if derr != nil {
t.Fatalf("decode thumbnail: %v", derr)
}
if img.Bounds().Dy() != 1 {
t.Fatalf("thumbnail height clamped to 1: got %d", img.Bounds().Dy())
}
}
func TestDownloadThumbnail_CreateFileFailsWhenDestFileReadOnly(t *testing.T) {
pngData := makeImageBytes(80, 40, "png", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/images/pic.png" {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngData)
return
}
http.NotFound(w, r)
})
srv := httptest.NewServer(handler)
defer srv.Close()
dest := t.TempDir()
// override createFile to simulate failure when creating permanent thumbnail file
orig := createFile
defer func() { createFile = orig }()
createFile = func(temp bool, dir, pathOrPattern string) (*os.File, error) {
if !temp {
return nil, errors.New("simulated permanent thumbnail create failure")
}
return orig(temp, dir, pathOrPattern)
}
w := &Webinfo{ImageURL: srv.URL + "/images/pic.png"}
_, err := w.DownloadThumbnail(context.Background(), dest, 20, false)
if err == nil {
t.Fatalf("expected error when permanent thumbnail creation fails, got nil")
}
}
func TestDownloadThumbnail_SmallDimensions(t *testing.T) {
// small original image -> request very small width
pngData := makeImageBytes(2, 1, "png", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngData)
})
srv := httptest.NewServer(handler)
defer srv.Close()
dest := t.TempDir()
w := &Webinfo{ImageURL: srv.URL + "/small.png"}
// request width 1 (small) and non-temporary output
out, err := w.DownloadThumbnail(context.Background(), dest, 1, false)
if err != nil {
t.Fatalf("DownloadThumbnail failed for small dimensions: %v", err)
}
defer func() { _ = os.Remove(out) }()
f, err := os.Open(filepath.Clean(out))
if err != nil {
t.Fatalf("open thumb: %v", err)
}
defer func() { _ = f.Close() }()
img, _, derr := image.Decode(f)
if derr != nil {
t.Fatalf("decode thumb: %v", derr)
}
if img.Bounds().Dx() != 1 {
t.Fatalf("unexpected thumb width: got %d want %d", img.Bounds().Dx(), 1)
}
if img.Bounds().Dy() < 1 {
t.Fatalf("unexpected thumb height: got %d want >=%d", img.Bounds().Dy(), 1)
}
}
func TestDownloadThumbnail_OutputImageFails(t *testing.T) {
// serve a PNG and then override outputImage to simulate encoder failure
pngData := makeImageBytes(40, 20, "png", 0x11, 0x88, 0x22)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(pngData)
})
srv := httptest.NewServer(handler)