-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
1672 lines (1557 loc) · 63.5 KB
/
Copy pathmain_test.go
File metadata and controls
1672 lines (1557 loc) · 63.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
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 main
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"io"
"math"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestValidateProfileName(t *testing.T) {
tests := []struct {
name string
ok bool
}{
{"Default", true},
{"Rail World_2.0", true},
{"", false},
{"../escape", false},
{".", false},
{"bad/name", false},
{"bad\\name", false},
{" hidden", true},
}
for _, test := range tests {
err := validateProfileName(test.name)
if test.ok && err != nil {
t.Fatalf("validateProfileName(%q) returned %v", test.name, err)
}
if !test.ok && !errors.Is(err, errInvalidProfileName) {
t.Fatalf("validateProfileName(%q) = %v, want errInvalidProfileName", test.name, err)
}
}
}
func TestSanitizeProfileName(t *testing.T) {
tests := []struct {
name string
want string
}{
{" My Map ", "My Map"},
{"../escape", "escape"},
{"bad/name\\here", "bad-name-here"},
{"name:with*symbols?", "name-with-symbols"},
{"spaces\tand\nlines", "spaces and lines"},
{"---", ""},
{strings.Repeat("a", 80), strings.Repeat("a", maxProfileNameLength)},
}
for _, test := range tests {
if got := sanitizeProfileName(test.name); got != test.want {
t.Fatalf("sanitizeProfileName(%q) = %q, want %q", test.name, got, test.want)
}
if test.want != "" {
if err := validateProfileName(test.want); err != nil {
t.Fatalf("sanitized name %q did not validate: %v", test.want, err)
}
}
}
}
func newTestStore(t *testing.T) *store {
t.Helper()
root := t.TempDir()
st := &store{
defaultRoot: filepath.Join(root, "default-presets"),
customRoot: filepath.Join(root, "custom-presets"),
}
if err := st.ensure(); err != nil {
t.Fatalf("ensure store: %v", err)
}
return st
}
func TestGuestCanReadAndDownloadProfilesButNotMutate(t *testing.T) {
st := newTestStore(t)
if _, err := st.createProfile("Guest Copy", "default"); err != nil {
t.Fatalf("createProfile: %v", err)
}
srv := &server{store: st}
list := httptest.NewRecorder()
srv.handleProfiles(list, httptest.NewRequest(http.MethodGet, "/api/profiles", nil))
if list.Code != http.StatusOK {
t.Fatalf("guest list status = %d body=%s", list.Code, list.Body.String())
}
read := httptest.NewRecorder()
srv.handleProfile(read, httptest.NewRequest(http.MethodGet, "/api/profiles/default:Default", nil))
if read.Code != http.StatusOK {
t.Fatalf("guest read status = %d body=%s", read.Code, read.Body.String())
}
var doc profileDocument
if err := json.Unmarshal(read.Body.Bytes(), &doc); err != nil {
t.Fatalf("decode profile: %v", err)
}
if doc.ID != "default:Default" || !doc.ReadOnly {
t.Fatalf("guest read doc id/readOnly = %q/%v, want default:Default/true", doc.ID, doc.ReadOnly)
}
download := httptest.NewRecorder()
srv.handleProfile(download, httptest.NewRequest(http.MethodGet, "/api/profiles/default:Default/download.zip", nil))
if download.Code != http.StatusOK {
t.Fatalf("guest download status = %d body=%s", download.Code, download.Body.String())
}
if got := download.Header().Get("Content-Type"); got != "application/zip" {
t.Fatalf("guest download Content-Type = %q, want application/zip", got)
}
create := httptest.NewRecorder()
srv.handleProfiles(create, httptest.NewRequest(http.MethodPost, "/api/profiles", strings.NewReader(`{"name":"Blocked","preset":"default"}`)))
if create.Code != http.StatusUnauthorized {
t.Fatalf("guest create status = %d body=%s", create.Code, create.Body.String())
}
update := httptest.NewRecorder()
srv.handleProfile(update, httptest.NewRequest(http.MethodPut, "/api/profiles/Guest%20Copy", strings.NewReader(`{"mapGen":{},"mapSettings":{}}`)))
if update.Code != http.StatusUnauthorized {
t.Fatalf("guest update status = %d body=%s", update.Code, update.Body.String())
}
duplicate := httptest.NewRecorder()
srv.handleProfile(duplicate, httptest.NewRequest(http.MethodPost, "/api/profiles/default:Default/duplicate", strings.NewReader(`{"name":"Blocked copy"}`)))
if duplicate.Code != http.StatusUnauthorized {
t.Fatalf("guest duplicate status = %d body=%s", duplicate.Code, duplicate.Body.String())
}
docForImport, err := st.readProfile("Guest Copy")
if err != nil {
t.Fatalf("read guest copy for local import: %v", err)
}
exchangeString, err := EncodeMapExchangeString(docForImport.MapGen, docForImport.MapSettings)
if err != nil {
t.Fatalf("encode exchange string for local import: %v", err)
}
importBody, _ := json.Marshal(importExchangeStringRequest{Name: "../Guest/Import??", ExchangeString: exchangeString})
importExchange := httptest.NewRecorder()
srv.handleProfile(importExchange, httptest.NewRequest(http.MethodPost, "/api/profiles/import-exchange", bytes.NewReader(importBody)))
if importExchange.Code != http.StatusOK {
t.Fatalf("guest local import status = %d body=%s", importExchange.Code, importExchange.Body.String())
}
var imported profileDocument
if err := json.Unmarshal(importExchange.Body.Bytes(), &imported); err != nil {
t.Fatalf("decode guest local import response: %v", err)
}
if imported.ID != "local:Guest-Import" || imported.Source != profileSourceLocal || imported.ReadOnly {
t.Fatalf("guest local import doc = %#v, want local Guest-Import", imported)
}
if _, err := os.Stat(filepath.Join(st.customRoot, "Guest-Import")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("guest local import wrote a preset directory err=%v, want not exist", err)
}
rename := httptest.NewRecorder()
srv.handleProfile(rename, httptest.NewRequest(http.MethodPost, "/api/profiles/Guest%20Copy/rename", strings.NewReader(`{"name":"Blocked rename"}`)))
if rename.Code != http.StatusUnauthorized {
t.Fatalf("guest rename status = %d body=%s", rename.Code, rename.Body.String())
}
deleteRec := httptest.NewRecorder()
srv.handleProfile(deleteRec, httptest.NewRequest(http.MethodDelete, "/api/profiles/Guest%20Copy", nil))
if deleteRec.Code != http.StatusUnauthorized {
t.Fatalf("guest delete status = %d body=%s", deleteRec.Code, deleteRec.Body.String())
}
}
func TestDownloadZipCanUsePostedCurrentSettings(t *testing.T) {
st := newTestStore(t)
if _, err := st.createProfile("Guest Zip", "default"); err != nil {
t.Fatalf("createProfile: %v", err)
}
srv := &server{store: st}
req := httptest.NewRequest(http.MethodPost, "/api/profiles/Guest%20Zip/download.zip", strings.NewReader(`{"mapGen":{"width":321,"height":654},"mapSettings":{"pollution":{"enabled":false}}}`))
rec := httptest.NewRecorder()
srv.handleProfile(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("download current settings status = %d body=%s", rec.Code, rec.Body.String())
}
if got := rec.Header().Get("Content-Type"); got != "application/zip" {
t.Fatalf("Content-Type = %q, want application/zip", got)
}
if got := rec.Header().Get("Content-Disposition"); !strings.Contains(got, "Guest-Zip-") || !strings.HasSuffix(got, `.zip"`) {
t.Fatalf("Content-Disposition = %q, want timestamped Guest-Zip filename", got)
}
zr, err := zip.NewReader(bytes.NewReader(rec.Body.Bytes()), int64(rec.Body.Len()))
if err != nil {
t.Fatalf("read zip: %v", err)
}
files := map[string]string{}
for _, file := range zr.File {
rc, err := file.Open()
if err != nil {
t.Fatalf("open zip file %s: %v", file.Name, err)
}
body, err := io.ReadAll(rc)
_ = rc.Close()
if err != nil {
t.Fatalf("read zip file %s: %v", file.Name, err)
}
files[file.Name] = string(body)
}
if !strings.Contains(files[mapGenFile], `"width": 321`) || !strings.Contains(files[mapGenFile], `"height": 654`) {
t.Fatalf("map-gen zip entry did not use posted settings: %s", files[mapGenFile])
}
if !strings.Contains(files[mapSettingsFile], `"enabled": false`) {
t.Fatalf("map-settings zip entry did not use posted settings: %s", files[mapSettingsFile])
}
saved, err := st.readProfile("Guest Zip")
if err != nil {
t.Fatalf("read saved profile after current-settings download: %v", err)
}
if bytes.Contains(saved.MapGen, []byte(`"width": 321`)) || bytes.Contains(saved.MapSettings, []byte(`"enabled": false`)) {
t.Fatalf("posted download settings were written to saved profile: mapGen=%s mapSettings=%s", saved.MapGen, saved.MapSettings)
}
localReq := httptest.NewRequest(http.MethodPost, "/api/profiles/local%3AGuest%20Zip/download.zip", strings.NewReader(`{"name":"Guest Zip Local","mapGen":{"width":123},"mapSettings":{"pollution":{"enabled":false}}}`))
localRec := httptest.NewRecorder()
srv.handleProfile(localRec, localReq)
if localRec.Code != http.StatusOK {
t.Fatalf("local download current settings status = %d body=%s", localRec.Code, localRec.Body.String())
}
if got := localRec.Header().Get("Content-Disposition"); !strings.Contains(got, "Guest-Zip-Local-") {
t.Fatalf("local Content-Disposition = %q, want Guest-Zip-Local filename", got)
}
}
func TestStoreCreateReadAndSave(t *testing.T) {
st := newTestStore(t)
doc, err := st.createProfile("Peaceful", "peaceful-rich")
if err != nil {
t.Fatalf("createProfile: %v", err)
}
if doc.Name != "Peaceful" {
t.Fatalf("created profile name = %q", doc.Name)
}
var mapGen map[string]any
if err := json.Unmarshal(doc.MapGen, &mapGen); err != nil {
t.Fatalf("unmarshal map gen: %v", err)
}
if peaceful, ok := mapGen["peaceful_mode"].(bool); !ok || !peaceful {
t.Fatalf("peaceful-rich preset peaceful_mode = %#v", mapGen["peaceful_mode"])
}
if doc.Source != profileSourceCustom || doc.ReadOnly {
t.Fatalf("created profile source/readOnly = %q/%v, want custom/false", doc.Source, doc.ReadOnly)
}
if _, err := os.Stat(filepath.Join(st.customRoot, "Peaceful", mapGenFile)); err != nil {
t.Fatalf("map-gen file missing: %v", err)
}
if _, err := os.Stat(filepath.Join(st.customRoot, "Peaceful", mapSettingsFile)); err != nil {
t.Fatalf("map-settings file missing: %v", err)
}
doc.MapGen = json.RawMessage(`{"width": 512, "height": 256}`)
saved, err := st.saveProfile("Peaceful", doc.MapGen, doc.MapSettings)
if err != nil {
t.Fatalf("saveProfile: %v", err)
}
if !bytes.Contains(saved.MapGen, []byte(`"width": 512`)) {
t.Fatalf("saved map gen was not normalized: %s", saved.MapGen)
}
doc.MapGen = json.RawMessage(`{"width": 0, "height": null, "starting_area": 1}`)
saved, err = st.saveProfile("Peaceful", doc.MapGen, doc.MapSettings)
if err != nil {
t.Fatalf("saveProfile zero dimensions: %v", err)
}
if bytes.Contains(saved.MapGen, []byte(`"width"`)) || bytes.Contains(saved.MapGen, []byte(`"height"`)) {
t.Fatalf("saved map gen retained implicit map dimensions: %s", saved.MapGen)
}
}
func TestStoreRenameProfile(t *testing.T) {
st := newTestStore(t)
doc, err := st.createProfile(" ../Old/Name?? ", "default")
if err != nil {
t.Fatalf("createProfile: %v", err)
}
if doc.Name != "Old-Name" || doc.ID != "custom:Old-Name" {
t.Fatalf("sanitized created profile = %q/%q, want Old-Name/custom:Old-Name", doc.Name, doc.ID)
}
saved, err := st.saveProfile(doc.ID, json.RawMessage(`{"width": 512, "height": 256}`), doc.MapSettings)
if err != nil {
t.Fatalf("saveProfile: %v", err)
}
renamed, err := st.renameProfile(saved.ID, " ../New/Name:?? ")
if err != nil {
t.Fatalf("renameProfile: %v", err)
}
if renamed.ID != "custom:New-Name" || renamed.Name != "New-Name" || renamed.ReadOnly {
t.Fatalf("renamed profile = %#v, want custom New-Name", renamed)
}
if !bytes.Contains(renamed.MapGen, []byte(`"width": 512`)) {
t.Fatalf("renamed profile lost map-gen contents: %s", renamed.MapGen)
}
if _, err := os.Stat(filepath.Join(st.customRoot, "Old-Name")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("old profile dir stat err = %v, want not exist", err)
}
if _, err := os.Stat(filepath.Join(st.customRoot, "New-Name", mapGenFile)); err != nil {
t.Fatalf("new profile map-gen missing: %v", err)
}
if _, err := st.readProfile("Old-Name"); !errors.Is(err, errProfileNotFound) {
t.Fatalf("read old profile err = %v, want errProfileNotFound", err)
}
if _, err := st.createProfile("Taken", "default"); err != nil {
t.Fatalf("create taken profile: %v", err)
}
if _, err := st.renameProfile("New-Name", "Taken"); !errors.Is(err, errProfileExists) {
t.Fatalf("rename conflict err = %v, want errProfileExists", err)
}
if _, err := st.renameProfile("New-Name", "////"); !errors.Is(err, errInvalidProfileName) {
t.Fatalf("rename invalid err = %v, want errInvalidProfileName", err)
}
if _, err := st.renameProfile("default:Default", "Renamed Default"); !errors.Is(err, errReadOnlyProfile) {
t.Fatalf("rename default err = %v, want errReadOnlyProfile", err)
}
}
func TestProfileRenameRoute(t *testing.T) {
st := newTestStore(t)
if _, err := st.createProfile("Before", "default"); err != nil {
t.Fatalf("createProfile: %v", err)
}
auth, password := newTestAuthStore(t)
srv := &server{store: st, auth: auth}
loginReq := httptest.NewRequest(http.MethodPost, "/api/session", strings.NewReader(`{"username":"admin","password":"`+password+`"}`))
login := httptest.NewRecorder()
srv.handleSession(login, loginReq)
if login.Code != http.StatusOK {
t.Fatalf("login status = %d body=%s", login.Code, login.Body.String())
}
cookies := login.Result().Cookies()
if len(cookies) == 0 {
t.Fatal("login did not set a cookie")
}
req := httptest.NewRequest(http.MethodPost, "/api/profiles/Before/rename", strings.NewReader(`{"name":"After"}`))
req.AddCookie(cookies[0])
rec := httptest.NewRecorder()
srv.handleProfile(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("rename status = %d body=%s", rec.Code, rec.Body.String())
}
var doc profileDocument
if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil {
t.Fatalf("decode rename response: %v", err)
}
if doc.ID != "custom:After" || doc.Name != "After" {
t.Fatalf("renamed doc id/name = %q/%q, want custom:After/After", doc.ID, doc.Name)
}
if _, err := st.readProfile("After"); err != nil {
t.Fatalf("read renamed profile: %v", err)
}
if _, err := st.readProfile("Before"); !errors.Is(err, errProfileNotFound) {
t.Fatalf("read old route profile err = %v, want errProfileNotFound", err)
}
}
func TestDecodeNativeFactorioExchangeString(t *testing.T) {
input := `>>>eNp1VDGIE0EUnbkYcuYuGiQIwnFGuDYW6oGFZEcbETlru3Wymc0Nbnbi7EzktDDoFRaCjc3ZaGtjpYXdgY2CgigIWp0cgoWFh1EshDizm9nMbuLA//v2vz///zc77BwAYE0ZWKria5IGzPW4bBOX0QCAgWOs5OHAo4LYsX0ew5mkssd6PcIbjGfy9scVG7mKZRKS7kajhSOVDFBiA6fiB5JxGhK3T0Jhb6j4Mugwjl0voL5vMwcNQ6MAh+3I5hY6AWnN2FNN4vEQbjLEhFxMyJ6qJmZViwQLyYz4dSwIt+PzlLMwfx6VgIp1KrtuS+vM9A2x7NNoetoiZ97VzCTFyOO4Z0cORwJzQcOOiznBbpfRSMhs5+LU4LVIBr7k1HOxR9tuh2xEWQVFwQnJdF4UMuxEgoRuTteC5DhUuqb09mXg4VAqXbkLcyhl+kwDGnUzvafOE8Cty+T2YHMZaBvdAvXRSJtCO+oGaQNwoK6SyoYqaK/6WWXnJpUgvFl7ev7LjQcOTBKOozHYGUe2WyZywYBL6L/UigGnrDon4/XTAklToVqMs+bRBCTkpiYh3Fvfvfv8z7AJ/z7Ze7/WuuLA/p3K8NexZ01FlrTSudQ93NLrhZECrBES6pMD377R67sDi3pHTTt0WrntiwUAqwcUenxPufoSMKM1TZkagn68fhsluwZ8cPI61EGc0cWXtXulXdwwnQwmEN1HEB017JFJitp/AtgztCcKX5u2L63+uUGmP4StIxdZQTM+Q1k3bKfuWyGdRp3nu5J5Q48QLGigs4YqlryNf2dxqeRZRfFxF9K7+MMxT5gCXeTj56+r/wBeqDbe<<<`
mapGen, mapSettings, err := decodeExchangeString(input)
if err != nil {
t.Fatalf("decode native Factorio exchange string: %v", err)
}
if !bytes.Contains(mapGen, []byte(`"autoplace_controls"`)) {
t.Fatalf("native map-gen JSON missing autoplace controls: %s", mapGen)
}
if !bytes.Contains(mapSettings, []byte(`"pollution"`)) {
t.Fatalf("native map-settings JSON missing pollution: %s", mapSettings)
}
}
func TestDecodeFactorio21ExchangeString(t *testing.T) {
input := `>>>eNp1VE2LEzEYTqx1u19apAjisvawN1nBVcGDdKIgIqJ/YUynaQ1OJzUfldWDPXhUvHjRi3sSXGE9eS+IordFz8KKFz0oFUQvQk06k2nSroFknnk/nud93wmzB0AwCwoALJXxTUVjFkZcNUjIaAxAL7B7JsJxRCVxbXsjhp0ggOYi1ukQvso4cc2zI8ZVj1EHk4S011frWHiki81YMU4TEnZJIn2PiluM4zCKabOZ0QDzPGA9VMQ4aQgrYZ7zrZjUd8kpp/ZREeFkEQups6PZZMaGAodNSJZ4CZn9FpaEu/YS5SyZnMdiTOV1qtph3fTp6SZYdamYrrbIWXRDuKFFEXHccS2HhMRc0qQVYk5w2GZUSMWJn+QXDlBFqLipOI1CHNFG2CLrwu+gKDkhnvKCVElLSJKEzGefVxwnuq+pfrsqjnCidF/ehekFB3NPlxlARfvF5uZYe2qeAB478ull794yMHt4F1SHQ7M12tFSZgPYA6Cvo6E22lXMJgqq5/Q+P6aD8E5l6+Ln248CmEYeRxkYZJZ+3VouWXAV/de1YsEphwfCB99fbfx5u12Df5///HClfi2AJy5UfgzWtmraWTRFF8yxL0dp7o6tqoQmLRo8eWzWtyAlqIzTygiiM/qtf7kAYHm/Rhv39VFdyiNqlq+CYHO0fgfw5Gh9seDjlLhu7qxRWTbHO3MUx6IA6VZS8FDrH7Xew+MQnb8G3Boa5i1t472Vfe3oTxQyPVy3jwlLHlxywJwRbOTH14I76u0Z+4aeotFnACbqF8w+Ckj/KSlVPmkz90J+0VaQf3sMMCRvnp0e/AMndh/V<<<`
data, err := ParseMapExchangeString(input)
if err != nil {
t.Fatalf("parse Factorio 2.1 exchange string: %v", err)
}
if data.Version != [4]uint16{2, 1, 9, 3} {
t.Fatalf("version = %v, want 2.1.9-3", data.Version)
}
if _, ok := data.MapSettings["steering"]; ok {
t.Fatalf("Factorio 2.1 map-settings unexpectedly included removed steering block")
}
expansion := asMap(data.MapSettings["enemy_expansion"])
if got := expansion["min_expansion_distance"]; got != uint32(3) {
t.Fatalf("min_expansion_distance = %#v, want 3", got)
}
if got := expansion["evolution_group_size_factor"]; got != float64(4) {
t.Fatalf("evolution_group_size_factor = %#v, want 4", got)
}
mapGen, mapSettings, err := decodeExchangeString(input)
if err != nil {
t.Fatalf("decode native Factorio exchange string: %v", err)
}
if !bytes.Contains(mapGen, []byte(`"autoplace_controls"`)) {
t.Fatalf("native map-gen JSON missing autoplace controls: %s", mapGen)
}
if !bytes.Contains(mapSettings, []byte(`"min_expansion_distance": 3`)) {
t.Fatalf("native map-settings JSON missing Factorio 2.1 expansion fields: %s", mapSettings)
}
}
func TestProfileExchangeStringRoutes(t *testing.T) {
st := newTestStore(t)
if _, err := st.createProfile("Source", "default"); err != nil {
t.Fatalf("create source profile: %v", err)
}
srv := &server{store: st}
exportRec := httptest.NewRecorder()
srv.handleProfile(exportRec, httptest.NewRequest(http.MethodGet, "/api/profiles/Source/exchange-string", nil))
if exportRec.Code != http.StatusOK {
t.Fatalf("export exchange status = %d body=%s", exportRec.Code, exportRec.Body.String())
}
var exported exchangeStringResponse
if err := json.Unmarshal(exportRec.Body.Bytes(), &exported); err != nil {
t.Fatalf("decode export response: %v", err)
}
if !strings.HasPrefix(exported.ExchangeString, ">>>") || !strings.HasSuffix(exported.ExchangeString, "<<<") {
t.Fatalf("exchange string = %q, want native Factorio wrapper", exported.ExchangeString)
}
decodedExport, err := ParseMapExchangeString(exported.ExchangeString)
if err != nil {
t.Fatalf("parse exported native exchange string: %v", err)
}
if decodedExport.Version != [4]uint16{2, 0, 10, 0} {
t.Fatalf("exported exchange version = %v, want 2.0.10-0", decodedExport.Version)
}
if _, ok := decodedExport.MapGenSettings["width"]; ok {
t.Fatalf("exported exchange string included implicit width 0")
}
if _, ok := decodedExport.MapGenSettings["height"]; ok {
t.Fatalf("exported exchange string included implicit height 0")
}
controls := asMap(decodedExport.MapGenSettings["autoplace_controls"])
for _, key := range []string{"coal", "copper-ore", "iron-ore", "stone"} {
if _, ok := controls[key]; ok {
t.Fatalf("exported exchange string included default autoplace control %q", key)
}
}
if autoplaceSettings := asMap(decodedExport.MapGenSettings["autoplace_settings"]); len(autoplaceSettings) != 0 {
t.Fatalf("exported exchange string included default autoplace settings: %v", autoplaceSettings)
}
exportedMapGen, exportedMapSettings, err := decodeExchangeString(exported.ExchangeString)
if err != nil {
t.Fatalf("decode exported exchange string: %v", err)
}
if bytes.Contains(exportedMapGen, []byte(`"nauvis_cliff"`)) || bytes.Contains(exportedMapGen, []byte(`"deepwater"`)) {
t.Fatalf("decoded exported map-gen JSON included default runtime settings: mapGen=%s", exportedMapGen)
}
if !bytes.Contains(exportedMapSettings, []byte(`"pollution"`)) {
t.Fatalf("decoded exported map-settings JSON missing pollution settings: mapSettings=%s", exportedMapSettings)
}
doc, err := st.readProfile("Source")
if err != nil {
t.Fatalf("read source profile: %v", err)
}
var currentMapGen map[string]interface{}
if err := json.Unmarshal(doc.MapGen, ¤tMapGen); err != nil {
t.Fatalf("decode source map gen: %v", err)
}
currentMapGen["width"] = 77
currentMapGenRaw, err := json.Marshal(currentMapGen)
if err != nil {
t.Fatalf("marshal edited map gen: %v", err)
}
postBody, err := json.Marshal(exchangeStringRequest{MapGen: currentMapGenRaw, MapSettings: doc.MapSettings})
if err != nil {
t.Fatalf("marshal exchange request: %v", err)
}
postRec := httptest.NewRecorder()
postReq := httptest.NewRequest(http.MethodPost, "/api/profiles/Source/exchange-string", bytes.NewReader(postBody))
srv.handleProfile(postRec, postReq)
if postRec.Code != http.StatusOK {
t.Fatalf("export posted exchange status = %d body=%s", postRec.Code, postRec.Body.String())
}
var posted exchangeStringResponse
if err := json.Unmarshal(postRec.Body.Bytes(), &posted); err != nil {
t.Fatalf("decode posted export response: %v", err)
}
mapGen, mapSettings, err := decodeExchangeString(posted.ExchangeString)
if err != nil {
t.Fatalf("decode posted exchange string: %v", err)
}
if !bytes.Contains(mapGen, []byte(`"width": 77`)) {
t.Fatalf("posted exchange did not include current map gen settings: mapGen=%s mapSettings=%s", mapGen, mapSettings)
}
auth, password := newTestAuthStore(t)
srv.auth = auth
loginReq := httptest.NewRequest(http.MethodPost, "/api/session", strings.NewReader(`{"username":"admin","password":"`+password+`"}`))
login := httptest.NewRecorder()
srv.handleSession(login, loginReq)
if login.Code != http.StatusOK {
t.Fatalf("login status = %d body=%s", login.Code, login.Body.String())
}
cookies := login.Result().Cookies()
if len(cookies) == 0 {
t.Fatal("login did not set a cookie")
}
importBody, _ := json.Marshal(importExchangeStringRequest{Name: "Imported", ExchangeString: exported.ExchangeString})
importReq := httptest.NewRequest(http.MethodPost, "/api/profiles/import-exchange", bytes.NewReader(importBody))
importReq.AddCookie(cookies[0])
importRec := httptest.NewRecorder()
srv.handleProfile(importRec, importReq)
if importRec.Code != http.StatusCreated {
t.Fatalf("import exchange status = %d body=%s", importRec.Code, importRec.Body.String())
}
if _, err := st.readProfile("Imported"); err != nil {
t.Fatalf("read imported profile: %v", err)
}
}
func TestStoreWritesProfileZip(t *testing.T) {
st := newTestStore(t)
if _, err := st.createProfile("Peaceful", "peaceful-rich"); err != nil {
t.Fatalf("createProfile: %v", err)
}
rec := httptest.NewRecorder()
if err := st.writeProfileZip(rec, "Peaceful"); err != nil {
t.Fatalf("writeProfileZip: %v", err)
}
zr, err := zip.NewReader(bytes.NewReader(rec.Body.Bytes()), int64(rec.Body.Len()))
if err != nil {
t.Fatalf("read zip: %v", err)
}
seen := map[string]bool{}
for _, file := range zr.File {
seen[file.Name] = true
}
for _, want := range []string{mapGenFile, mapSettingsFile} {
if !seen[want] {
t.Fatalf("zip missing %s", want)
}
}
if got := rec.Header().Get("Content-Type"); got != "application/zip" {
t.Fatalf("Content-Type = %q, want application/zip", got)
}
}
func TestStoreRejectsInvalidJSONAndSanitizesTraversal(t *testing.T) {
st := newTestStore(t)
doc, err := st.createProfile("../Escape", "default")
if err != nil {
t.Fatalf("createProfile sanitized traversal name: %v", err)
}
if doc.Name != "Escape" || doc.ID != "custom:Escape" {
t.Fatalf("sanitized traversal profile = %q/%q, want Escape/custom:Escape", doc.Name, doc.ID)
}
if _, err := os.Stat(filepath.Join(st.customRoot, "Escape", mapGenFile)); err != nil {
t.Fatalf("sanitized traversal profile was not written inside custom root: %v", err)
}
if _, err := st.saveProfile("Bad", json.RawMessage(`{"ok": true} trailing`), json.RawMessage(`{}`)); err == nil {
t.Fatal("saveProfile accepted invalid JSON")
}
if _, err := normalizeJSON(json.RawMessage(`{} {}`)); err == nil {
t.Fatal("normalizeJSON accepted multiple JSON documents")
}
if _, err := normalizeJSON(json.RawMessage(`[]`)); err == nil {
t.Fatal("normalizeJSON accepted a non-object JSON document")
}
}
func TestStoreDefaultProfilesAreReadOnly(t *testing.T) {
st := newTestStore(t)
doc, err := st.readProfile("default:Default")
if err != nil {
t.Fatalf("read default profile: %v", err)
}
if doc.Source != profileSourceDefault || !doc.ReadOnly {
t.Fatalf("default profile source/readOnly = %q/%v, want default/true", doc.Source, doc.ReadOnly)
}
if _, err := st.saveProfile(doc.ID, json.RawMessage(`{"width": 1}`), doc.MapSettings); !errors.Is(err, errReadOnlyProfile) {
t.Fatalf("save default err = %v, want errReadOnlyProfile", err)
}
if err := st.deleteProfile(doc.ID); !errors.Is(err, errReadOnlyProfile) {
t.Fatalf("delete default err = %v, want errReadOnlyProfile", err)
}
duplicate, err := st.duplicateProfile(doc.ID, "Default copy")
if err != nil {
t.Fatalf("duplicate default profile: %v", err)
}
if duplicate.Source != profileSourceCustom || duplicate.ReadOnly {
t.Fatalf("duplicate source/readOnly = %q/%v, want custom/false", duplicate.Source, duplicate.ReadOnly)
}
}
func TestPreviewRequestForUserLimitsGuestPreviewOptions(t *testing.T) {
guest := previewRequestForUser(previewRequest{Size: 4096, Zoom: "out-4"}, nil)
if guest.Size != guestMaxPreviewSize {
t.Fatalf("guest preview size = %d, want %d", guest.Size, guestMaxPreviewSize)
}
if guest.Zoom != "1" {
t.Fatalf("guest preview zoom = %q, want normal", guest.Zoom)
}
fastGuest := previewRequestForUser(previewRequest{Engine: previewEngineFast, Size: 512, Zoom: "2.75"}, nil)
if fastGuest.Zoom != "1" {
t.Fatalf("fast guest preview zoom = %q, want 1", fastGuest.Zoom)
}
exactGuest := previewRequestForUser(previewRequest{Engine: previewEngineFactorio, Size: 512, Zoom: "2.75"}, nil)
if exactGuest.Engine != previewEngineFast {
t.Fatalf("exact guest preview engine = %q, want fast", exactGuest.Engine)
}
if exactGuest.Zoom != "1" {
t.Fatalf("exact guest preview zoom = %q, want normal", exactGuest.Zoom)
}
defaultSizedGuest := previewRequestForUser(previewRequest{}, nil)
if defaultSizedGuest.Size != guestMaxPreviewSize {
t.Fatalf("default guest preview size = %d, want %d", defaultSizedGuest.Size, guestMaxPreviewSize)
}
signedIn := previewRequestForUser(previewRequest{Size: 4096, Zoom: "out-4"}, &authUser{ID: 1, Username: "user"})
if signedIn.Size != 4096 || signedIn.Zoom != "out-4" {
t.Fatalf("signed-in preview request = %#v, want unchanged", signedIn)
}
}
func TestGuestExactPreviewRequestIsForbidden(t *testing.T) {
srv := &server{store: newTestStore(t)}
req := httptest.NewRequest(
http.MethodPost,
"/api/profiles/default:Default/preview",
strings.NewReader(`{"engine":"factorio","size":512,"planet":"nauvis"}`),
)
rec := httptest.NewRecorder()
srv.handleProfile(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("guest Exact preview status = %d body=%s, want 403", rec.Code, rec.Body.String())
}
}
func TestFastPreviewValidationErrorsReturnBadRequest(t *testing.T) {
tests := []struct {
name string
body string
}{
{name: "unsupported planet", body: `{"engine":"fast","planet":"mars","seed":"1"}`},
{name: "zero seed", body: `{"engine":"fast","planet":"nauvis","seed":"0"}`},
{name: "overflow seed", body: `{"engine":"fast","planet":"nauvis","seed":"4294967296"}`},
{name: "non-object map generation settings", body: `{"engine":"fast","planet":"nauvis","seed":"1","mapGen":[]}`},
{name: "out-of-range JSON number", body: `{"engine":"fast","planet":"nauvis","seed":"1","mapGen":{"width":1e400}}`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
preview := &previewer{}
srv := &server{store: newTestStore(t), previewer: preview}
req := httptest.NewRequest(
http.MethodPost,
"/api/profiles/default:Default/preview",
strings.NewReader(test.body),
)
rec := httptest.NewRecorder()
srv.handleProfile(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d body=%s, want 400", rec.Code, rec.Body.String())
}
if preview.fastPreviewCache != nil {
t.Fatal("invalid request initialized the Fast tile cache")
}
})
}
}
func TestPreviewZoomSpec(t *testing.T) {
tests := []struct {
name string
zoom string
outputSize int
wantMode string
wantScale float64
wantRender int
wantErr bool
}{
{name: "normal", zoom: "", outputSize: 1024, wantMode: "normal", wantScale: 1, wantRender: 1024},
{name: "legacy zoom out", zoom: "out-4", outputSize: 4096, wantMode: "scale", wantScale: 4, wantRender: 16384},
{name: "decimal zoom out", zoom: "2.75", outputSize: 1024, wantMode: "scale", wantScale: 2.75, wantRender: 2816},
{name: "decimal zoom in", zoom: "0.37", outputSize: 1024, wantMode: "scale", wantScale: 0.37, wantRender: 1024},
{name: "legacy zoom in", zoom: "in-3", outputSize: 1024, wantMode: "scale", wantScale: 1.0 / 3, wantRender: 1024},
{name: "source render too large", zoom: "4.0001", outputSize: 4096, wantErr: true},
{name: "below minimum", zoom: "0.001", outputSize: 1024, wantErr: true},
{name: "above maximum", zoom: "65", outputSize: 256, wantErr: true},
{name: "bad", zoom: "sideways-2", outputSize: 1024, wantErr: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := previewZoomSpec(test.zoom, test.outputSize)
if test.wantErr {
if err == nil {
t.Fatalf("previewZoomSpec(%q, %d) succeeded: %#v", test.zoom, test.outputSize, got)
}
return
}
if err != nil {
t.Fatalf("previewZoomSpec(%q, %d): %v", test.zoom, test.outputSize, err)
}
if got.mode != test.wantMode ||
math.Abs(got.tilesPerPixel-test.wantScale) > 1e-12 ||
got.renderSize != test.wantRender {
t.Fatalf("previewZoomSpec(%q, %d) = %#v, want mode=%s scale=%g render=%d", test.zoom, test.outputSize, got, test.wantMode, test.wantScale, test.wantRender)
}
})
}
}
func TestFastPreviewZoomSpecDoesNotUseFactorioSourceLimit(t *testing.T) {
got, err := fastPreviewZoomSpec("64", maxPreviewOutputSize)
if err != nil {
t.Fatalf("fastPreviewZoomSpec at maximum scale: %v", err)
}
if got.tilesPerPixel != 64 || got.renderSize != maxPreviewOutputSize*64 {
t.Fatalf("fast zoom = %#v, want scale 64 and render size %d", got, maxPreviewOutputSize*64)
}
if _, err := previewZoomSpec("64", maxPreviewOutputSize); err == nil {
t.Fatal("exact preview accepted a source render above the Factorio limit")
}
}
func TestNormalizedPreviewCenterRejectsScaleAlignmentOutsideBounds(t *testing.T) {
for _, center := range []float64{maxPreviewCenter, -maxPreviewCenter} {
if _, _, err := normalizedPreviewCenter(center, 0, 63); err == nil {
t.Fatalf("normalizedPreviewCenter(%g, 0, 63) succeeded outside aligned bounds", center)
}
}
}
func TestFastPreviewCacheBudgetFromMiB(t *testing.T) {
for _, test := range []struct {
mebibytes int64
wantBytes int64
wantError bool
}{
{mebibytes: 1, wantBytes: 1 << 20},
{mebibytes: 2048, wantBytes: 2 << 30},
{mebibytes: 0, wantError: true},
{mebibytes: (math.MaxInt64 >> 20) + 1, wantError: true},
} {
got, err := fastPreviewCacheBytesForMiB(test.mebibytes)
if test.wantError {
if err == nil {
t.Fatalf("fastPreviewCacheBytesForMiB(%d) succeeded with %d", test.mebibytes, got)
}
continue
}
if err != nil || got != test.wantBytes {
t.Fatalf("fastPreviewCacheBytesForMiB(%d) = %d, %v; want %d, nil", test.mebibytes, got, err, test.wantBytes)
}
}
preview := &previewer{fastPreviewCacheBytes: 7 << 20}
if got := preview.fastCache().maxBytes; got != 7<<20 {
t.Fatalf("configured Fast cache bytes = %d, want %d", got, 7<<20)
}
}
func TestWarmDefaultFastPreviewCache(t *testing.T) {
st := newTestStore(t)
preview := &previewer{fastPreviewCacheBytes: 8 << 20}
srv := &server{store: st, previewer: preview}
srv.warmDefaultFastPreviewCache(context.Background())
stats := preview.fastCache().stats()
wantBytes := int64(1024 * 1024 * 4)
if stats.Worlds != 1 || stats.Tiles != 64 || stats.Bytes != wantBytes {
t.Fatalf("warm Default cache stats = %#v, want one world, 64 tiles, and %d bytes", stats, wantBytes)
}
ref := profileRef{Source: profileSourceDefault, Name: "Default"}
mapGen, err := readNormalizedMapGenJSON(filepath.Join(st.profileDir(ref), mapGenFile))
if err != nil {
t.Fatal(err)
}
settings, err := parseFastPreviewSettings(mapGen, defaultFastPreviewWarmSeed)
if err != nil {
t.Fatal(err)
}
key, err := fastPreviewCacheKey(mapGen, settings.seed)
if err != nil {
t.Fatal(err)
}
if _, err := preview.fastCache().render(context.Background(), key, settings, 1024, 1, 0, 0); err != nil {
t.Fatal(err)
}
after := preview.fastCache().stats()
if after.Misses != stats.Misses || after.Hits-stats.Hits != 64 {
t.Fatalf("repeat Default cache stats = %#v after %#v, want 64 hits and no misses", after, stats)
}
}
func TestExactPreviewPassesNormalizedMapOffset(t *testing.T) {
dir := t.TempDir()
argsPath := filepath.Join(dir, "args.txt")
pngPath := filepath.Join(dir, "source.png")
pngFile, err := os.Create(pngPath)
if err != nil {
t.Fatal(err)
}
if err := png.Encode(pngFile, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil {
_ = pngFile.Close()
t.Fatal(err)
}
if err := pngFile.Close(); err != nil {
t.Fatal(err)
}
bin := filepath.Join(dir, "fake-factorio")
script := fmt.Sprintf(`#!/bin/sh
printf '%%s\n' "$@" > %q
output=
next_is_output=0
for argument in "$@"; do
if [ "$next_is_output" = 1 ]; then
output="$argument"
break
fi
if [ "$argument" = "--generate-map-preview" ]; then
next_is_output=1
fi
done
cp %q "$output"
`, argsPath, pngPath)
if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
mapGenPath := filepath.Join(dir, mapGenFile)
if err := os.WriteFile(mapGenPath, []byte(`{"seed":123456}`), 0o600); err != nil {
t.Fatal(err)
}
preview := &previewer{factorioBin: bin, timeout: 5 * time.Second}
response, err := preview.render(
context.Background(),
profileRef{Source: profileSourceCustom, Name: "offset"},
mapGenPath,
previewRequest{Size: 256, Planet: "nauvis", Zoom: "2.75", CenterX: 12.4, CenterY: -8.6},
false,
)
if err != nil {
t.Fatal(err)
}
if response.CenterX != 13.75 || response.CenterY != -8.25 || response.TilesPerPixel != 2.75 {
t.Fatalf("response viewport = (%g,%g) at %g, want (13.75,-8.25) at 2.75", response.CenterX, response.CenterY, response.TilesPerPixel)
}
arguments, err := os.ReadFile(argsPath)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(arguments), "--map-preview-offset\n13.75,-8.25\n") {
t.Fatalf("Factorio arguments missing normalized offset:\n%s", arguments)
}
}
func TestEncodePNGPreviewImageUsesOpaqueTruecolor(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 32, 32))
for y := 0; y < 32; y++ {
for x := 0; x < 32; x++ {
img.Set(x, y, color.RGBA{R: uint8(x * 7), G: uint8(y * 7), B: uint8((x + y) * 3), A: 255})
}
}
got, contentType, ext, err := encodePNGPreviewImage(img)
if err != nil {
t.Fatalf("encodePNGPreviewImage: %v", err)
}
if contentType != "image/png" || ext != ".png" {
t.Fatalf("PNG metadata = (%q, %q)", contentType, ext)
}
decoded, err := png.Decode(bytes.NewReader(got))
if err != nil {
t.Fatalf("decode encoded preview: %v", err)
}
for y := 0; y < 32; y++ {
for x := 0; x < 32; x++ {
if decoded.At(x, y) != img.At(x, y) {
t.Fatalf("pixel (%d,%d) changed", x, y)
}
}
}
}
func TestPreviewImagesRemainAvailableForSaving(t *testing.T) {
st := newTestStore(t)
srv := &server{
store: st,
previewer: &previewer{},
}
name, err := srv.previewer.storePreviewImage([]byte("png"), "image/png", ".png")
if err != nil {
t.Fatalf("storePreviewImage: %v", err)
}
rec := httptest.NewRecorder()
srv.handlePreviewImage(rec, httptest.NewRequest(http.MethodGet, "/api/previews/"+name, nil))
if rec.Code != http.StatusOK {
t.Fatalf("preview status = %d body=%s", rec.Code, rec.Body.String())
}
if got := rec.Header().Get("Content-Type"); got != "image/png" {
t.Fatalf("Content-Type = %q, want image/png", got)
}
if got := rec.Header().Get("Content-Disposition"); got != `inline; filename="`+name+`"` {
t.Fatalf("Content-Disposition = %q, want inline filename", got)
}
if got := rec.Body.String(); got != "png" {
t.Fatalf("preview body = %q, want png", got)
}
again := httptest.NewRecorder()
srv.handlePreviewImage(again, httptest.NewRequest(http.MethodGet, "/api/previews/"+name, nil))
if again.Code != http.StatusOK {
t.Fatalf("second preview status = %d body=%s", again.Code, again.Body.String())
}
if got := again.Body.String(); got != "png" {
t.Fatalf("second preview body = %q, want png", got)
}
bad := httptest.NewRecorder()
srv.handlePreviewImage(bad, httptest.NewRequest(http.MethodGet, "/api/previews/preview-render_123.txt", nil))
if bad.Code != http.StatusNotFound {
t.Fatalf("bad preview filename status = %d body=%s", bad.Code, bad.Body.String())
}
}
func TestPreviewImagesAreCapped(t *testing.T) {
preview := &previewer{}
var first string
for i := 0; i < maxPreviewImages+1; i++ {
name, err := preview.storePreviewImage([]byte("png"), "image/png", ".png")
if err != nil {
t.Fatalf("storePreviewImage %d: %v", i, err)
}
if i == 0 {
first = name
}
}
if got := len(preview.images); got != maxPreviewImages {
t.Fatalf("preview image count = %d, want %d", got, maxPreviewImages)
}
if got, want := preview.imageBytes, int64(maxPreviewImages*len("png")); got != want {
t.Fatalf("preview image bytes = %d, want %d", got, want)
}
if _, ok := preview.getPreviewImage(first); ok {
t.Fatal("oldest preview was retained after exceeding cap")
}
}
func TestPreviewImagesAreEvictedByPayloadBytes(t *testing.T) {
preview := &previewer{imageByteLimit: 6}
first, err := preview.storePreviewImage([]byte("1234"), "image/png", ".png")
if err != nil {
t.Fatalf("store first preview: %v", err)
}
second, err := preview.storePreviewImage([]byte("abc"), "image/png", ".png")
if err != nil {
t.Fatalf("store second preview: %v", err)
}
if got := len(preview.images); got != 1 {
t.Fatalf("preview image count = %d, want 1", got)
}
if got := preview.imageBytes; got != 3 {
t.Fatalf("preview image bytes = %d, want 3", got)
}
if _, ok := preview.getPreviewImage(first); ok {
t.Fatal("oldest preview was retained after exceeding byte cap")
}
if img, ok := preview.getPreviewImage(second); !ok || string(img.data) != "abc" {
t.Fatalf("new preview = (%q, %v), want (abc, true)", img.data, ok)
}
}