Repository navigation
Expand file tree
/
Copy pathbindings_test.go
More file actions
1227 lines (1089 loc) · 42.8 KB
/
Copy pathbindings_test.go
File metadata and controls
1227 lines (1089 loc) · 42.8 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
// bindings_test.go covers the Wails binding surface (ADR-0004): input
// validation, error mapping, and the success paths that do not require a
// real network, real accounts, or a GUI. HTTP-backed bindings are exercised
// against httptest servers; java detection is faked through the function
// variables in internal/services.
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"HRPMLW/internal/database"
"HRPMLW/internal/interop"
"HRPMLW/internal/models"
"HRPMLW/internal/repository"
"HRPMLW/internal/services"
)
// TestMain initializes one temporary SQLite database for the whole test
// binary (database.Initialize is sync.Once-guarded).
func TestMain(m *testing.M) {
dir, err := os.MkdirTemp("", "samuelclient-bindtest")
if err != nil {
os.Exit(1)
}
if err := database.Initialize(&database.Config{Path: filepath.Join(dir, "bindings.db")}); err != nil {
os.Exit(1)
}
code := m.Run()
_ = database.Close()
_ = os.RemoveAll(dir)
os.Exit(code)
}
// newTestApp builds an App wired to real services but with no Wails context
// (emit becomes a no-op) — exactly what binding tests need.
func newTestApp() *App {
return &App{
authService: services.NewAuthService(),
bmclService: services.NewBMCLAPIService(),
launcherService: services.NewLauncherService(),
javaRepo: repository.NewJavaRepository(),
}
}
func TestRetryInstallRetriesFailureAndStopsAfterSuccess(t *testing.T) {
attempts := 0
result := retryInstall(context.Background(), func() *models.ApiResponse {
attempts++
if attempts == 1 {
return &models.ApiResponse{Success: false, Error: "temporary network failure"}
}
return &models.ApiResponse{Success: true}
})
if !result.Success || attempts != 2 {
t.Fatalf("result = %+v after %d attempts, want success after 2", result, attempts)
}
}
func TestRetryInstallCapsAttempts(t *testing.T) {
attempts := 0
result := retryInstall(context.Background(), func() *models.ApiResponse {
attempts++
return &models.ApiResponse{Success: false, Error: "download failed"}
})
if result.Success || attempts != installRetryAttempts {
t.Fatalf("result = %+v after %d attempts, want failure after %d", result, attempts, installRetryAttempts)
}
}
// swapDataDir points the launcher data directory at dir for one test.
func swapDataDir(t *testing.T, dir string) {
t.Helper()
old := database.DataDirFn
database.DataDirFn = func() string { return dir }
t.Cleanup(func() { database.DataDirFn = old })
}
func TestDownloadSettingsSelectCustomVersionEndpoint(t *testing.T) {
t.Cleanup(func() { _ = repository.NewSettingRepository().Delete("launcher.download") })
app := newTestApp()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/mirror/mc/game/version_manifest_v2.json":
io.WriteString(w, `{"versions":[{"id":"official-shape"}]}`)
case "/mirror/mc/game/version_manifest.json":
io.WriteString(w, `{"versions":[{"id":"bmcl-shape"}]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
for _, tc := range []struct{ shape, version string }{
{"official", "official-shape"},
{"bmclapi", "bmcl-shape"},
} {
if res := app.SetDownloadSettings("custom", tc.shape, srv.URL+"/mirror/", 3); !res.Success {
t.Fatal(res.Error)
}
cfg := newTestApp().GetDownloadSettings().Data.(services.DownloadSettings)
if cfg.Source != "custom" || cfg.CustomShape != tc.shape || cfg.Concurrency != 3 || cfg.CustomURL != srv.URL+"/mirror" {
t.Fatalf("persisted settings = %+v", cfg)
}
result := app.GetVersions()
manifest, ok := result.Data.(services.BMCLVersionManifestResponse)
if !result.Success || !ok || len(manifest.Versions) != 1 || manifest.Versions[0].ID != tc.version {
t.Fatalf("source shape %q returned %+v", tc.shape, result)
}
}
for _, invalid := range []struct {
url string
concurrency int
}{{"file:///tmp/mirror", 8}, {"https://mirror.example", 33}, {"https://mirror.example/?q=x", 8}} {
if res := app.SetDownloadSettings("custom", "official", invalid.url, invalid.concurrency); res.Success {
t.Fatalf("invalid settings accepted: %+v", invalid)
}
}
}
func TestCancelInstall(t *testing.T) {
app := newTestApp()
// Empty id is rejected.
if res := app.CancelInstall(""); res.Success {
t.Errorf("CancelInstall(\"\") must fail")
}
// Unknown id is an idempotent no-op.
res := app.CancelInstall("not-running")
if !res.Success {
t.Fatalf("CancelInstall of an unknown id must succeed (idempotent), got %q", res.Error)
}
if cancelled, _ := res.Data.(map[string]interface{})["cancelled"].(bool); cancelled {
t.Errorf("unknown id must report cancelled=false")
}
// A registered install is cancelled and its context done.
ctx, entry := app.beginInstall("1.99")
res = app.CancelInstall("1.99")
if !res.Success {
t.Fatalf("CancelInstall of a running id must succeed, got %q", res.Error)
}
if cancelled, _ := res.Data.(map[string]interface{})["cancelled"].(bool); !cancelled {
t.Errorf("running id must report cancelled=true")
}
select {
case <-ctx.Done():
// expected
default:
t.Errorf("context must be done after CancelInstall")
}
_ = entry
// Finishing the install removes it; a later cancel is again a no-op.
app.finishInstall("1.99", entry)
res = app.CancelInstall("1.99")
if !res.Success {
t.Fatalf("CancelInstall after finish must succeed, got %q", res.Error)
}
if cancelled, _ := res.Data.(map[string]interface{})["cancelled"].(bool); cancelled {
t.Errorf("finished install must report cancelled=false")
}
}
// clearLauncherSettings removes launcher.* rows so config tests start clean
// (the DB is shared across the test binary).
func clearLauncherSettings(t *testing.T) {
t.Helper()
repo := repository.NewSettingRepository()
for _, key := range []string{
"launcher.max_memory", "launcher.min_memory", "launcher.java_args",
"launcher.game_width", "launcher.game_height", "launcher.game_dir",
"launcher.authlib_jar", "launcher.game_dirs",
} {
_ = repo.Delete(key)
}
}
// clearJavaTable empties java_installations for tests that assert list
// contents.
func clearJavaTable(t *testing.T) {
t.Helper()
all, err := repository.NewJavaRepository().GetAll()
if err != nil {
t.Fatalf("list java installations: %v", err)
}
for _, j := range all {
_ = repository.NewJavaRepository().Delete(j.ID)
}
}
// fakeJavaDetections swaps the java detection seams and restores them on
// cleanup.
func fakeJavaDetections(t *testing.T, systemPath, version string) {
t.Helper()
origVersion, origSystem := services.DetectJavaVersion, services.DetectSystemJava
t.Cleanup(func() {
services.DetectJavaVersion, services.DetectSystemJava = origVersion, origSystem
})
services.DetectJavaVersion = func(path string) (string, error) {
if systemPath != "" && path == systemPath {
return version, nil
}
return version, nil
}
services.DetectSystemJava = func() string { return systemPath }
}
func wantFailure(t *testing.T, got *models.ApiResponse, wantErr string) {
t.Helper()
if got.Success {
t.Fatalf("expected failure, got success (data=%v)", got.Data)
}
if wantErr != "" && got.Error != wantErr {
t.Errorf("Error = %q, want %q", got.Error, wantErr)
}
if got.Error == "" {
t.Error("failed ApiResponse must carry a non-empty Error")
}
}
// ==================== newClientToken ====================
func TestNewClientToken(t *testing.T) {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
first := newClientToken()
if len(first) != 32 {
t.Errorf("token length = %d, want 32", len(first))
}
for _, r := range first {
if !strings.ContainsRune(charset, r) {
t.Errorf("token contains %q outside the charset", r)
}
}
// Two draws must differ (crypto/rand, not the old deterministic
// placeholder).
second := newClientToken()
if first == second {
t.Errorf("two consecutive tokens are identical: %q", first)
}
}
// ==================== validation failures (all 19 bindings) ====================
func TestBindingValidationFailures(t *testing.T) {
app := newTestApp()
cases := []struct {
name string
call func() *models.ApiResponse
wantErr string
}{
{"GetFabricVersions empty mc", func() *models.ApiResponse { return app.GetFabricVersions("") }, "mc version is required"},
{"GetForgeVersions empty mc", func() *models.ApiResponse { return app.GetForgeVersions("") }, "mc version is required"},
{"HRPAuthLogin empty username", func() *models.ApiResponse { return app.HRPAuthLogin("", "p", "") }, "username and password are required"},
{"HRPAuthLogin empty password", func() *models.ApiResponse { return app.HRPAuthLogin("u", "", "") }, "username and password are required"},
{"HRPAuthRefresh empty tokens", func() *models.ApiResponse { return app.HRPAuthRefresh("", "", "") }, "access token and client token are required"},
{"HRPAuthValidate empty token", func() *models.ApiResponse { return app.HRPAuthValidate("", "") }, "access token is required"},
{"DownloadVersion empty id", func() *models.ApiResponse { return app.DownloadVersion("", "") }, "version_id is required"},
{"InstallFabricLoader empty mc", func() *models.ApiResponse { return app.InstallFabricLoader("", "0.15.0", "") }, "mc version is required"},
{"InstallFabricLoader empty loader", func() *models.ApiResponse { return app.InstallFabricLoader("1.99", "", "") }, "loader version is required"},
{"InstallForgeLoader empty mc", func() *models.ApiResponse { return app.InstallForgeLoader("", "47.2.0", "") }, "mc version is required"},
{"InstallForgeLoader empty forge", func() *models.ApiResponse { return app.InstallForgeLoader("1.99", "", "") }, "forge version is required"},
{"LaunchGame empty request", func() *models.ApiResponse { return app.LaunchGame(LaunchGameRequest{}) }, "version_id is required"},
{"LaunchGame missing user", func() *models.ApiResponse {
return app.LaunchGame(LaunchGameRequest{VersionID: "1.99"})
}, "username and uuid are required"},
{"LaunchGame missing tokens", func() *models.ApiResponse {
return app.LaunchGame(LaunchGameRequest{VersionID: "1.99", Username: "u", UUID: "id"})
}, "access token and client token are required"},
{"AddJavaInstallation empty path", func() *models.ApiResponse { return app.AddJavaInstallation("", "") }, "path is required"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
wantFailure(t, tc.call(), tc.wantErr)
})
}
}
// UpdateJavaInstallation on a missing id must fail with a not-found error.
func TestUpdateJavaInstallationMissingID(t *testing.T) {
app := newTestApp()
wantFailure(t, app.UpdateJavaInstallation(999999, "/x", "n"), "")
}
// Delete/SetDefault on a missing id must surface the repository not-found
// error instead of silently succeeding.
func TestDeleteJavaInstallationMissingID(t *testing.T) {
app := newTestApp()
wantFailure(t, app.DeleteJavaInstallation(999999), "")
}
func TestSetDefaultJavaInstallationMissingID(t *testing.T) {
app := newTestApp()
wantFailure(t, app.SetDefaultJavaInstallation(999999), "")
}
// Updating the path must re-detect the version through the seam.
func TestUpdateJavaInstallationRedetectsVersion(t *testing.T) {
app := newTestApp()
clearJavaTable(t)
fakeJavaDetections(t, "", "17.0.9")
added := app.AddJavaInstallation("/opt/jdk-old/bin/java", "Old JDK")
if !added.Success {
t.Fatalf("AddJavaInstallation failed: %s", added.Error)
}
id := int(added.Data.(*models.JavaInstallation).ID)
t.Cleanup(func() { _ = app.javaRepo.Delete(int64(id)) })
// The seam now reports a different version for the new path.
fakeJavaDetections(t, "", "21.0.5")
upd := app.UpdateJavaInstallation(id, "/opt/jdk-new/bin/java", "")
if !upd.Success {
t.Fatalf("UpdateJavaInstallation failed: %s", upd.Error)
}
updated := upd.Data.(*models.JavaInstallation)
if updated.Path != "/opt/jdk-new/bin/java" {
t.Errorf("Path = %q, want the new path", updated.Path)
}
if updated.Version != "21.0.5" {
t.Errorf("Version = %q, want re-detected 21.0.5", updated.Version)
}
if updated.FriendlyName != "Old JDK" {
t.Errorf("FriendlyName = %q, want unchanged Old JDK", updated.FriendlyName)
}
}
// A failing version detection must surface as an error, for both add and update.
func TestJavaInstallationDetectionFailure(t *testing.T) {
app := newTestApp()
clearJavaTable(t)
orig := services.DetectJavaVersion
t.Cleanup(func() { services.DetectJavaVersion = orig })
services.DetectJavaVersion = func(path string) (string, error) { return "17", nil }
added := app.AddJavaInstallation("/opt/jdk-ok/bin/java", "OK JDK")
if !added.Success {
t.Fatalf("AddJavaInstallation failed: %s", added.Error)
}
id := int(added.Data.(*models.JavaInstallation).ID)
t.Cleanup(func() { _ = app.javaRepo.Delete(int64(id)) })
services.DetectJavaVersion = func(path string) (string, error) { return "", fmt.Errorf("exec exploded") }
result := app.AddJavaInstallation("/opt/jdk-bad/bin/java", "Bad JDK")
if result.Success || !strings.Contains(result.Error, "Failed to detect Java version") {
t.Errorf("Add with failing detection: Success=%v Error=%q", result.Success, result.Error)
}
result = app.UpdateJavaInstallation(id, "/opt/jdk-other/bin/java", "")
if result.Success || !strings.Contains(result.Error, "Failed to detect Java version") {
t.Errorf("Update with failing detection: Success=%v Error=%q", result.Success, result.Error)
}
}
// ==================== HTTP-backed bindings against httptest ====================
const hrpauthAuthResponse = `{
"accessToken": "access-123",
"clientToken": "client-456",
"availableProfiles": [{"id": "p1", "name": "PlayerOne"}],
"selectedProfile": {"id": "p1", "name": "PlayerOne"}
}`
// pointHRPAuthAt aims the built-in HRPAuth endpoint at a test server for the
// duration of one test and restores the production value afterwards.
func pointHRPAuthAt(t *testing.T, url string) {
t.Helper()
old := services.HRPAuthBaseURL
services.HRPAuthBaseURL = url
t.Cleanup(func() { services.HRPAuthBaseURL = old })
}
func TestHRPAuthLoginBindingSuccessGeneratesClientToken(t *testing.T) {
var gotBody map[string]interface{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/authserver/authenticate" {
http.NotFound(w, r)
return
}
body, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(body, &gotBody)
io.WriteString(w, hrpauthAuthResponse)
}))
defer srv.Close()
pointHRPAuthAt(t, srv.URL)
app := newTestApp()
result := app.HRPAuthLogin("alice", "secret", "")
if !result.Success {
t.Fatalf("HRPAuthLogin failed: %s", result.Error)
}
// The binding must have generated a 32-char client token on its own.
ct, _ := gotBody["clientToken"].(string)
if len(ct) != 32 {
t.Errorf("generated clientToken length = %d, want 32 (body=%v)", len(ct), gotBody)
}
resp, ok := result.Data.(services.AuthlibAuthResponse)
if !ok {
t.Fatalf("Data is %T, want AuthlibAuthResponse", result.Data)
}
if resp.AccessToken != "access-123" || resp.SelectedProfile.Name != "PlayerOne" {
t.Errorf("unexpected login result: %+v", resp)
}
}
func TestHRPAuthBindingsFailureMapping(t *testing.T) {
// A closed server simulates an unreachable auth endpoint: the binding
// must map the transport error into ApiResponse.Error, never panic.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
srv.Close()
pointHRPAuthAt(t, srv.URL)
app := newTestApp()
wantFailure(t, app.HRPAuthLogin("u", "p", ""), "")
wantFailure(t, app.HRPAuthRefresh("at", "ct", ""), "")
wantFailure(t, app.HRPAuthValidate("at", ""), "")
}
func TestRefreshAndValidateBindingSuccess(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/authserver/refresh", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, hrpauthAuthResponse)
})
mux.HandleFunc("/authserver/validate", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"meta": {"serverName": "BindingTestAuth"}, "signaturePublickey": "pk", "skinDomains": []}`)
})
srv := httptest.NewServer(mux)
defer srv.Close()
pointHRPAuthAt(t, srv.URL)
app := newTestApp()
if result := app.HRPAuthRefresh("at", "ct", "p1"); !result.Success {
t.Fatalf("HRPAuthRefresh failed: %s", result.Error)
}
if result := app.HRPAuthValidate("at", "ct"); !result.Success {
t.Fatalf("HRPAuthValidate failed: %s", result.Error)
}
meta := app.authService.GetHRPAuthMeta()
if !meta.Success {
t.Fatalf("GetHRPAuthMeta failed: %s", meta.Error)
}
data, ok := meta.Data.(map[string]interface{})
if !ok {
t.Fatalf("meta Data is %T, want map", meta.Data)
}
serverMeta, ok := data["meta"].(*services.AuthlibServerMeta)
if !ok || serverMeta.Meta.ServerName != "BindingTestAuth" {
t.Errorf("meta payload = %+v, want serverName BindingTestAuth", data["meta"])
}
}
// bmclFixture serves the three read-only BMCLAPI endpoints used by bindings.
func bmclFixture(t *testing.T) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/mc/game/version_manifest.json", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"latest": {"release": "1.99"}, "versions": [{"id": "1.99", "type": "release", "url": "u"}]}`)
})
mux.HandleFunc("/fabric-meta/v2/versions/loader/1.99", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `[{"loader": {"version": "0.15.0"}}]`)
})
mux.HandleFunc("/forge/minecraft/1.99", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `[{"version": "47.2.0"}]`)
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func TestVersionListBindingsSuccess(t *testing.T) {
srv := bmclFixture(t)
app := newTestApp()
app.bmclService = services.NewBMCLAPIServiceWithBaseURL(srv.URL)
versions := app.GetVersions()
if !versions.Success {
t.Fatalf("GetVersions failed: %s", versions.Error)
}
manifest, ok := versions.Data.(services.BMCLVersionManifestResponse)
if !ok || len(manifest.Versions) != 1 {
t.Fatalf("unexpected versions data: %T %+v", versions.Data, versions.Data)
}
fabric := app.GetFabricVersions("1.99")
if !fabric.Success {
t.Fatalf("GetFabricVersions failed: %s", fabric.Error)
}
forge := app.GetForgeVersions("1.99")
if !forge.Success {
t.Fatalf("GetForgeVersions failed: %s", forge.Error)
}
}
func TestVersionBindingFailureMapping(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
url := srv.URL
srv.Close()
app := newTestApp()
app.bmclService = services.NewBMCLAPIServiceWithBaseURL(url)
for name, result := range map[string]*models.ApiResponse{
"GetVersions": app.GetVersions(),
"GetFabricVersions": app.GetFabricVersions("1.99"),
"GetForgeVersions": app.GetForgeVersions("1.99"),
} {
if result.Success {
t.Errorf("%s: expected failure against a closed server", name)
}
if result.Error == "" {
t.Errorf("%s: failure must carry an error message", name)
}
}
}
// ==================== java installation bindings ====================
func TestJavaInstallationBindingsLifecycle(t *testing.T) {
clearJavaTable(t)
fakeJavaDetections(t, "", "17.0.9")
app := newTestApp()
// Add.
added := app.AddJavaInstallation("/opt/jdk/bin/java", "Test JDK")
if !added.Success {
t.Fatalf("AddJavaInstallation failed: %s", added.Error)
}
created, ok := added.Data.(*models.JavaInstallation)
if !ok || created.ID == 0 {
t.Fatalf("AddJavaInstallation Data = %T, want *models.JavaInstallation with ID", added.Data)
}
if created.Version != "17.0.9" {
t.Errorf("detected version = %q, want the faked 17.0.9", created.Version)
}
// List contains it.
list := app.GetJavaInstallations()
if !list.Success {
t.Fatalf("GetJavaInstallations failed: %s", list.Error)
}
javas, ok := list.Data.([]models.JavaInstallation)
if !ok || len(javas) != 1 {
t.Fatalf("GetJavaInstallations Data = %T %+v, want one row", list.Data, list.Data)
}
// Update name.
upd := app.UpdateJavaInstallation(int(created.ID), "", "Renamed JDK")
if !upd.Success {
t.Fatalf("UpdateJavaInstallation failed: %s", upd.Error)
}
if updated := upd.Data.(*models.JavaInstallation); updated.FriendlyName != "Renamed JDK" {
t.Errorf("friendly name = %q, want Renamed JDK", updated.FriendlyName)
}
// Second installation + default switching.
second := app.AddJavaInstallation("/opt/jdk2/bin/java", "Second JDK")
if !second.Success {
t.Fatalf("second AddJavaInstallation failed: %s", second.Error)
}
secondID := second.Data.(*models.JavaInstallation).ID
if result := app.SetDefaultJavaInstallation(int(created.ID)); !result.Success {
t.Fatalf("SetDefaultJavaInstallation failed: %s", result.Error)
}
def, err := app.javaRepo.GetDefault()
if err != nil || def.ID != created.ID {
t.Fatalf("default after first SetDefault = %+v / %v", def, err)
}
if result := app.SetDefaultJavaInstallation(int(secondID)); !result.Success {
t.Fatalf("second SetDefaultJavaInstallation failed: %s", result.Error)
}
def, err = app.javaRepo.GetDefault()
if err != nil || def.ID != secondID {
t.Errorf("default must move to the second installation, got %+v / %v", def, err)
}
// Delete both.
if result := app.DeleteJavaInstallation(int(created.ID)); !result.Success {
t.Fatalf("DeleteJavaInstallation failed: %s", result.Error)
}
if result := app.DeleteJavaInstallation(int(secondID)); !result.Success {
t.Fatalf("second DeleteJavaInstallation failed: %s", result.Error)
}
if _, err := app.javaRepo.GetByID(created.ID); err == nil {
t.Error("deleted java installation still readable")
}
}
func TestGetJavaInstallationsAutoDetectsSystemJava(t *testing.T) {
clearJavaTable(t)
fakeJavaDetections(t, "/fake/system/java", "21.0.1")
app := newTestApp()
result := app.GetJavaInstallations()
if !result.Success {
t.Fatalf("GetJavaInstallations failed: %s", result.Error)
}
javas := result.Data.([]models.JavaInstallation)
if len(javas) != 1 {
t.Fatalf("auto-detection created %d rows, want 1", len(javas))
}
if javas[0].Path != "/fake/system/java" || !javas[0].IsDefault || javas[0].Version != "21.0.1" {
t.Errorf("auto-detected row = %+v", javas[0])
}
clearJavaTable(t)
}
func TestGetJavaInstallationsEmptyWithoutSystemJava(t *testing.T) {
clearJavaTable(t)
fakeJavaDetections(t, "", "")
app := newTestApp()
result := app.GetJavaInstallations()
if !result.Success {
t.Fatalf("GetJavaInstallations failed: %s", result.Error)
}
javas := result.Data.([]models.JavaInstallation)
if len(javas) != 0 {
t.Errorf("expected empty list when no system java exists, got %+v", javas)
}
}
// ==================== launcher config bindings ====================
func TestGetLauncherConfigBindingDefaults(t *testing.T) {
clearLauncherSettings(t)
javaHome := t.TempDir()
bin := filepath.Join(javaHome, "bin")
if err := os.MkdirAll(bin, 0755); err != nil {
t.Fatalf("mkdir: %v", err)
}
javaPath := filepath.Join(bin, "java")
if err := os.WriteFile(javaPath, []byte("#!/bin/sh\n"), 0755); err != nil {
t.Fatalf("write fake java: %v", err)
}
t.Setenv("JAVA_HOME", javaHome)
t.Setenv("HOME", t.TempDir())
app := newTestApp()
result := app.GetLauncherConfig()
if !result.Success {
t.Fatalf("GetLauncherConfig failed: %s", result.Error)
}
cfg, ok := result.Data.(models.LauncherConfig)
if !ok {
t.Fatalf("Data is %T, want models.LauncherConfig", result.Data)
}
if cfg.MaxMemory != 4096 || cfg.MinMemory != 1024 || cfg.GameWidth != 854 || cfg.GameHeight != 480 {
t.Errorf("defaults wrong: %+v", cfg)
}
if cfg.JavaPath != javaPath {
t.Errorf("JavaPath = %q, want %q", cfg.JavaPath, javaPath)
}
}
func TestUpdateLauncherConfigBinding(t *testing.T) {
clearLauncherSettings(t)
app := newTestApp()
valid := app.UpdateLauncherConfig(models.LauncherConfig{
MaxMemory: 2048, MinMemory: 512, JavaArgs: "-Xss1M", GameWidth: 1280, GameHeight: 720,
})
if !valid.Success {
t.Fatalf("valid UpdateLauncherConfig failed: %s", valid.Error)
}
merged, ok := valid.Data.(models.LauncherConfig)
if !ok || merged.MaxMemory != 2048 || merged.GameWidth != 1280 {
t.Errorf("merged config = %+v, want the saved values", merged)
}
// Invalid values must surface the service validation error.
invalid := app.UpdateLauncherConfig(models.LauncherConfig{MaxMemory: 1024, MinMemory: 2048})
wantFailure(t, invalid, "min memory cannot exceed max memory")
clearLauncherSettings(t)
}
// ==================== installed versions binding ====================
func TestGetInstalledVersionsBinding(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
swapDataDir(t, home)
versionsDir := filepath.Join(home, ".minecraft", "versions")
// Complete version: json + jar.
full := filepath.Join(versionsDir, "1.99")
if err := os.MkdirAll(full, 0755); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := os.WriteFile(filepath.Join(full, "1.99.json"), []byte(`{"type": "release"}`), 0644); err != nil {
t.Fatalf("write json: %v", err)
}
if err := os.WriteFile(filepath.Join(full, "1.99.jar"), []byte("jar"), 0644); err != nil {
t.Fatalf("write jar: %v", err)
}
// Partial version: json only.
partial := filepath.Join(versionsDir, "0.5-partial")
if err := os.MkdirAll(partial, 0755); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := os.WriteFile(filepath.Join(partial, "0.5-partial.json"), []byte(`{"type": "snapshot"}`), 0644); err != nil {
t.Fatalf("write json: %v", err)
}
app := newTestApp()
result := app.GetInstalledVersions()
if !result.Success {
t.Fatalf("GetInstalledVersions failed: %s", result.Error)
}
data, ok := result.Data.(map[string]interface{})
if !ok {
t.Fatalf("Data is %T, want map", result.Data)
}
versions, ok := data["versions"].([]InstalledVersion)
if !ok || len(versions) != 2 {
t.Fatalf("versions = %+v, want both directories", data["versions"])
}
byID := map[string]InstalledVersion{}
for _, v := range versions {
byID[v.ID] = v
}
fullGot, ok := byID["1.99"]
if !ok || !fullGot.HasJSON || !fullGot.HasJAR || fullGot.Type != "release" {
t.Errorf("full version = %+v, want has_json+has_jar release", fullGot)
}
partialGot, ok := byID["0.5-partial"]
if !ok || !partialGot.HasJSON || partialGot.HasJAR || partialGot.Type != "snapshot" {
t.Errorf("partial version = %+v, want has_json only snapshot", partialGot)
}
}
func TestScanInstalledVersionsKeepsRepairableModpackWithoutVersions(t *testing.T) {
dir := t.TempDir()
const id = "fabric-loader-0.16.0-1.20.1"
marker := `{"name":"Example pack","version_id":"` + id + `","managed":true}`
if err := os.WriteFile(filepath.Join(dir, ".samuel-modpack.json"), []byte(marker), 0644); err != nil {
t.Fatal(err)
}
versions := scanInstalledVersions(dir)
if len(versions) != 1 || versions[0].ID != id || versions[0].ModpackName != "Example pack" ||
!versions[0].Repairable || versions[0].HasJSON || versions[0].HasJAR {
t.Fatalf("expected the missing profile to remain selectable for repair, got %+v", versions)
}
}
func TestGetInstalledVersionsEmptyWhenNoDir(t *testing.T) {
t.Setenv("HOME", t.TempDir())
app := newTestApp()
result := app.GetInstalledVersions()
if !result.Success {
t.Fatalf("GetInstalledVersions failed on missing dir: %s", result.Error)
}
data := result.Data.(map[string]interface{})
versions := data["versions"].([]InstalledVersion)
if len(versions) != 0 {
t.Errorf("versions = %+v, want empty", versions)
}
}
// ==================== download binding (full flow, hermetic) ====================
func TestDownloadVersionBindingSuccess(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/mc/game/version_manifest.json", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"versions": [{"id": "1.99", "type": "release", "url": "https://piston-meta.mojang.com/v1/packages/abc/1.99.json"}]}`)
})
mux.HandleFunc("/v1/packages/abc/1.99.json", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{
"id": "1.99",
"mainClass": "net.minecraft.client.main.Main",
"downloads": {"client": {"sha1": "c1", "size": 8, "url": "https://piston-data.mojang.com/v1/objects/c1/client.jar"}},
"libraries": []
}`)
})
mux.HandleFunc("/v1/objects/c1/client.jar", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "jar-bytes")
})
srv := httptest.NewServer(mux)
defer srv.Close()
app := newTestApp()
app.bmclService = services.NewBMCLAPIServiceWithBaseURL(srv.URL)
gameDir := t.TempDir()
result := app.DownloadVersion("1.99", gameDir)
if !result.Success {
t.Fatalf("DownloadVersion failed: %s", result.Error)
}
versionDir := filepath.Join(gameDir, "versions", "1.99")
if _, err := os.Stat(filepath.Join(versionDir, "1.99.json")); err != nil {
t.Errorf("version JSON missing: %v", err)
}
if got, err := os.ReadFile(filepath.Join(versionDir, "1.99.jar")); err != nil || string(got) != "jar-bytes" {
t.Errorf("version jar missing or wrong (err=%v got=%q)", err, got)
}
}
func TestDownloadVersionBindingFailure(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusInternalServerError)
}))
defer srv.Close()
app := newTestApp()
app.bmclService = services.NewBMCLAPIServiceWithBaseURL(srv.URL)
wantFailure(t, app.DownloadVersion("1.99", t.TempDir()), "")
}
// ==================== launch binding ====================
// LaunchGame's success path spawns a real detached game process and is
// deliberately not exercised here (see TESTING-TODO.md); validation and the
// pre-flight HRPAuth metadata fetch are the in-scope parts.
func TestLaunchGameValidationOnly(t *testing.T) {
app := newTestApp()
// Covered by the table-driven validation test above; here we additionally
// assert the exact ApiResponse shape of a failure: Success=false, Error
// set, Data nil.
result := app.LaunchGame(LaunchGameRequest{})
if result.Success || result.Error == "" || result.Data != nil {
t.Errorf("failure shape = %+v, want Success=false/Error set/Data nil", result)
}
}
// ==================== loader install bindings (hermetic) ====================
// TestInstallFabricLoaderBindingSuccess drives the binding layer against a
// fake Fabric meta server: the profile JSON is persisted under the
// binding-constructed version id on top of an installed parent version.
func TestInstallFabricLoaderBindingSuccess(t *testing.T) {
var srvURL string
mux := http.NewServeMux()
mux.HandleFunc("/fabric-meta/v2/versions/loader/1.99/0.15.0/profile/json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{
"id": "fabric-loader-0.15.0-1.99",
"inheritsFrom": "1.99",
"mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient",
"libraries": [
{
"name": "net.fabricmc:fabric-loader:0.15.0",
"downloads": {"artifact": {"path": "net/fabricmc/fabric-loader/0.15.0/fabric-loader-0.15.0.jar", "url": "%s/maven/fabric-loader.jar", "size": 10}}
}
]
}`, srvURL)
})
mux.HandleFunc("/maven/fabric-loader.jar", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "fabric-lib")
})
srv := httptest.NewServer(mux)
srvURL = srv.URL
defer srv.Close()
gameDir := t.TempDir()
parentDir := filepath.Join(gameDir, "versions", "1.99")
if err := os.MkdirAll(parentDir, 0755); err != nil {
t.Fatalf("mkdir parent: %v", err)
}
if err := os.WriteFile(filepath.Join(parentDir, "1.99.json"), []byte(`{"id": "1.99", "type": "release"}`), 0644); err != nil {
t.Fatalf("write parent json: %v", err)
}
app := newTestApp()
app.bmclService = services.NewBMCLAPIServiceWithBaseURL(srv.URL)
result := app.InstallFabricLoader("1.99", "0.15.0", gameDir)
if !result.Success {
t.Fatalf("InstallFabricLoader failed: %s", result.Error)
}
data, ok := result.Data.(map[string]interface{})
if !ok || data["version_id"] != "fabric-loader-0.15.0-1.99" {
t.Fatalf("data = %+v, want version_id fabric-loader-0.15.0-1.99", result.Data)
}
profilePath := filepath.Join(gameDir, "versions", "fabric-loader-0.15.0-1.99", "fabric-loader-0.15.0-1.99.json")
if _, err := os.Stat(profilePath); err != nil {
t.Errorf("profile json missing after install: %v", err)
}
}
// TestInstallForgeLoaderBindingSuccess wires the binding's java path
// resolution (JAVA_HOME seam) to a fake installer script standing in for
// `java -jar installer --installClient`, then asserts the generated version
// directory and the transient installer jar cleanup.
func TestInstallForgeLoaderBindingSuccess(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skipf("fake installer is a shell script; GOOS=%s", runtime.GOOS)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/maven/net/minecraftforge/forge/1.99-47.2.0/forge-1.99-47.2.0-installer.jar" {
http.NotFound(w, r)
return
}
io.WriteString(w, "installer-bytes")
}))
defer srv.Close()
// JAVA_HOME seam: bin/java is the fake installer script (arguments are
// ignored, mirroring the service-level fake).
javaHome := t.TempDir()
if err := os.MkdirAll(filepath.Join(javaHome, "bin"), 0755); err != nil {
t.Fatalf("mkdir bin: %v", err)
}
script := "#!/bin/sh\n" +
"mkdir -p \"versions/1.99-forge-47.2.0\"\n" +
"printf '{\"id\": \"1.99-forge-47.2.0\", \"inheritsFrom\": \"1.99\"}' > \"versions/1.99-forge-47.2.0/1.99-forge-47.2.0.json\"\n" +
"exit 0\n"
if err := os.WriteFile(filepath.Join(javaHome, "bin", "java"), []byte(script), 0755); err != nil {
t.Fatalf("write fake java: %v", err)
}
t.Setenv("JAVA_HOME", javaHome)
app := newTestApp()
app.bmclService = services.NewBMCLAPIServiceWithBaseURL(srv.URL)
gameDir := t.TempDir()
result := app.InstallForgeLoader("1.99", "47.2.0", gameDir)
if !result.Success {
t.Fatalf("InstallForgeLoader failed: %s", result.Error)
}
if _, err := os.Stat(filepath.Join(gameDir, "versions", "1.99-forge-47.2.0", "1.99-forge-47.2.0.json")); err != nil {
t.Errorf("generated version json missing: %v", err)
}
if _, err := os.Stat(filepath.Join(gameDir, "forge-installer-47.2.0.jar")); !os.IsNotExist(err) {
t.Errorf("installer jar must be removed after the install, stat err = %v", err)
}
}
// Loader versions have no client jar of their own; GetInstalledVersions must
// count the parent's jar as theirs via inheritsFrom so the UI treats them as
// launchable.
func TestGetInstalledVersionsLoaderInheritsParentJar(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
swapDataDir(t, home)
versionsDir := filepath.Join(home, ".minecraft", "versions")
parent := filepath.Join(versionsDir, "1.99")
loader := filepath.Join(versionsDir, "fabric-loader-0.15.0-1.99")
for _, d := range []string{parent, loader} {
if err := os.MkdirAll(d, 0755); err != nil {
t.Fatalf("mkdir: %v", err)
}
}
if err := os.WriteFile(filepath.Join(parent, "1.99.json"), []byte(`{"type": "release"}`), 0644); err != nil {
t.Fatalf("write parent json: %v", err)
}
if err := os.WriteFile(filepath.Join(parent, "1.99.jar"), []byte("jar"), 0644); err != nil {
t.Fatalf("write parent jar: %v", err)
}
if err := os.WriteFile(filepath.Join(loader, "fabric-loader-0.15.0-1.99.json"), []byte(`{"type": "release", "inheritsFrom": "1.99"}`), 0644); err != nil {
t.Fatalf("write loader json: %v", err)
}
app := newTestApp()
result := app.GetInstalledVersions()
if !result.Success {
t.Fatalf("GetInstalledVersions failed: %s", result.Error)
}
versions := result.Data.(map[string]interface{})["versions"].([]InstalledVersion)
byID := map[string]InstalledVersion{}
for _, v := range versions {
byID[v.ID] = v
}