package rest import ( "bytes" "crypto/md5" "encoding/json" "errors" "fmt" "io" "net" "net/http" "os" "path/filepath" "reflect" "strings" "sync" "testing" "time" "github.com/GopeedLab/gopeed/internal/test" "github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/download" enginewebview "github.com/GopeedLab/gopeed/pkg/download/engine/webview" "github.com/GopeedLab/gopeed/pkg/rest/model" ) var ( restPort int taskReq = &base.Request{ Extra: map[string]any{ "method": "", "header": map[string]string{ "Usr-Agent": "gopeed", }, "body": "", }, } taskRes = &base.Resource{ Size: test.BuildSize, Range: true, Files: []*base.FileInfo{ { Name: test.BuildName, Path: "", Size: test.BuildSize, }, }, } createOpts = &base.Options{ Path: test.Dir, Name: test.DownloadName, Extra: map[string]any{ "connections": 2, }, } resolveReq = &model.ResolveTask{ Req: taskReq, Opts: createOpts, } createReq = &model.CreateTask{ Req: taskReq, Opts: createOpts, } installExtensionReq = &model.InstallExtension{ URL: "https://github.com/GopeedLab/gopeed-extension-samples#github-contributor-avatars-sample", } ) func currentTestDownloadFile() string { return filepath.Join(createOpts.Path, createOpts.Name) } func TestInfo(t *testing.T) { matchKeys := []string{"version", "runtime", "os", "arch", "inDocker"} doTest(func() { resp := httpRequestCheckOk[map[string]any](http.MethodGet, "/api/v1/info", nil) for _, key := range matchKeys { if _, ok := resp[key]; !ok { t.Errorf("Info() missing key = %v", key) } } }) } func TestResolve(t *testing.T) { doTest(func() { resp := httpRequestCheckOk[*download.ResolveResult](http.MethodPost, "/api/v1/resolve", resolveReq) if !test.AssertResourceEqual(taskRes, resp.Res) { t.Errorf("Resolve() got = %v, want %v", test.ToJson(resp.Res), test.ToJson(taskRes)) } }) } func TestCreateTask(t *testing.T) { doTest(func() { resp := httpRequestCheckOk[*download.ResolveResult](http.MethodPost, "/api/v1/resolve", resolveReq) var wg sync.WaitGroup wg.Add(1) Downloader.Listener(func(event *download.Event) { if event.Key == download.EventKeyFinally { wg.Done() } }) taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", &model.CreateTask{ Rid: resp.ID, }) if taskId == "" { t.Fatal("create task failed") } wg.Wait() want := test.FileMd5(test.BuildFile) got := test.FileMd5(currentTestDownloadFile()) if want != got { t.Errorf("CreateTask() got = %v, want %v", got, want) } }) } func TestCreateDirectTask(t *testing.T) { doTest(func() { var wg sync.WaitGroup wg.Add(1) Downloader.Listener(func(event *download.Event) { if event.Key == download.EventKeyFinally { wg.Done() } }) taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) if taskId == "" { t.Fatal("create task failed") } wg.Wait() want := test.FileMd5(test.BuildFile) got := test.FileMd5(currentTestDownloadFile()) if want != got { t.Errorf("CreateDirectTask() got = %v, want %v", got, want) } }) } func TestCreateDirectTaskBatch(t *testing.T) { doTest(func() { reqs := make([]*base.CreateTaskBatchItem, 0) for i := 0; i < 5; i++ { reqs = append(reqs, &base.CreateTaskBatchItem{ Req: createReq.Req, }) } taskIds := httpRequestCheckOk[[]string](http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{ Reqs: reqs, }) if len(taskIds) != len(reqs) { t.Errorf("CreateDirectTaskBatch() got = %v, want %v", len(taskIds), len(reqs)) } }) } func TestCreateDirectTaskBatchWithOpt(t *testing.T) { doTest(func() { reqs := make([]*base.CreateTaskBatchItem, 0) for i := 0; i < 5; i++ { item := &base.CreateTaskBatchItem{ Req: createReq.Req, } if i == 0 { item.Opts = &base.Options{ Name: "spe_opt.data", } } reqs = append(reqs, item) } taskIds := httpRequestCheckOk[[]string](http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{ Reqs: reqs, Opts: &base.Options{ Name: "default_opt.data", }, }) if len(taskIds) != len(reqs) { t.Errorf("CreateDirectTaskBatch() got = %v, want %v", len(taskIds), len(reqs)) } for i, taskId := range taskIds { task := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil) if i == 0 { if !strings.Contains(task.Name(), "spe_opt") { t.Errorf("CreateDirectTaskBatch() got = %v, want %v", task.Name(), "spe_opt.data") } } else { if !strings.Contains(task.Name(), "default_opt") { t.Errorf("CreateDirectTaskBatch() got = %v, want %v", task.Name(), "default_opt.data") } } } }) } func TestPauseAndContinueTask(t *testing.T) { doTest(func() { var wg sync.WaitGroup wg.Add(1) Downloader.Listener(func(event *download.Event) { switch event.Key { case download.EventKeyFinally: wg.Done() } }) taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) t1 := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil) if t1.Status != base.DownloadStatusRunning { t.Errorf("CreateTask() got = %v, want %v", t1.Status, base.DownloadStatusRunning) } httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/"+taskId+"/pause", nil) t2 := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil) if t2.Status != base.DownloadStatusPause { t.Errorf("PauseTask() got = %v, want %v", t2.Status, base.DownloadStatusPause) } time.Sleep(time.Millisecond * 100) httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/"+taskId+"/continue", nil) t3 := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil) if t3.Status != base.DownloadStatusRunning { t.Errorf("ContinueTask() got = %v, want %v", t3.Status, base.DownloadStatusRunning) } wg.Wait() want := test.FileMd5(test.BuildFile) got := test.FileMd5(currentTestDownloadFile()) if !reflect.DeepEqual(got, want) { t.Errorf("PauseAndContinueTask() got = %v, want %v", got, want) } }) } func TestPatchTask(t *testing.T) { doTest(func() { // Create a task taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) if taskId == "" { t.Fatal("create task failed") } // Pause the task httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/"+taskId+"/pause", nil) time.Sleep(time.Millisecond * 100) // Patch the task with new labels patchReq := &model.ResolveTask{ Req: &base.Request{ Labels: map[string]string{ "patched": "true", "version": "2", }, }, } httpRequestCheckOk[any](http.MethodPatch, "/api/v1/tasks/"+taskId, patchReq) // Verify the patch was applied task := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil) if task.Meta.Req.Labels["patched"] != "true" { t.Errorf("PatchTask() label 'patched' = %v, want %v", task.Meta.Req.Labels["patched"], "true") } if task.Meta.Req.Labels["version"] != "2" { t.Errorf("PatchTask() label 'version' = %v, want %v", task.Meta.Req.Labels["version"], "2") } // Clean up httpRequestCheckOk[any](http.MethodDelete, "/api/v1/tasks/"+taskId+"?force=true", nil) }) } func TestPatchTaskNotFound(t *testing.T) { doTest(func() { // Try to patch a non-existent task patchReq := &model.ResolveTask{ Req: &base.Request{ Labels: map[string]string{ "test": "value", }, }, } code, _ := httpRequest[any](http.MethodPatch, "/api/v1/tasks/non-existent-id", patchReq) if code != int(model.CodeTaskNotFound) { t.Errorf("PatchTaskNotFound() result code = %v, want %v", code, model.CodeTaskNotFound) } }) } func TestPauseAllAndContinueALLTasks(t *testing.T) { doTest(func() { slowListener := test.StartTestLowSpeedServer(5 * time.Nanosecond) defer slowListener.Close() taskReq.URL = "http://" + slowListener.Addr().String() + "/" + test.BuildName cfg, err := Downloader.GetConfig() if err != nil { t.Fatal(err) } createAndPause := func() { taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) time.Sleep(time.Millisecond * 5) httpRequestCheckOk[*download.Task](http.MethodPut, "/api/v1/tasks/"+taskId+"/pause", nil) } total := cfg.MaxRunning + 2 for i := 0; i < total; i++ { createAndPause() } time.Sleep(time.Millisecond * 50) // continue all httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/continue", nil) time.Sleep(time.Millisecond * 100) tasks := httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s", base.DownloadStatusRunning), nil) if len(tasks) != cfg.MaxRunning { t.Errorf("ContinueAllTasks() got = %v, want %v", len(tasks), cfg.MaxRunning) } // pause all httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/pause", nil) time.Sleep(time.Millisecond * 100) tasks = httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s", base.DownloadStatusPause), nil) if len(tasks) != total { t.Errorf("PauseAllTasks() got = %v, want %v", len(tasks), total) } }) } func TestDeleteTask(t *testing.T) { doTest(func() { taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) time.Sleep(time.Millisecond * 200) httpRequestCheckOk[any](http.MethodDelete, "/api/v1/tasks/"+taskId, nil) code, _ := httpRequest[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil) checkCode(code, model.CodeTaskNotFound) }) } func TestDeleteTaskForce(t *testing.T) { doTest(func() { taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) time.Sleep(time.Millisecond * 200) httpRequestCheckOk[any](http.MethodDelete, "/api/v1/tasks/"+taskId+"?force=true", nil) code, _ := httpRequest[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil) checkCode(code, model.CodeTaskNotFound) if _, err := os.Stat(currentTestDownloadFile()); !errors.Is(err, os.ErrNotExist) { t.Errorf("DeleteTaskForce() got = %v, want %v", err, os.ErrNotExist) } }) } func TestDeleteAllTasks(t *testing.T) { doTest(func() { taskCount := 3 var wg sync.WaitGroup wg.Add(taskCount) Downloader.Listener(func(event *download.Event) { if event.Key == download.EventKeyFinally { wg.Done() } }) for i := 0; i < taskCount; i++ { httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) } wg.Wait() httpRequestCheckOk[any](http.MethodDelete, "/api/v1/tasks?force=true", nil) tasks := httpRequestCheckOk[[]*download.Task](http.MethodGet, "/api/v1/tasks", nil) if len(tasks) != 0 { t.Errorf("DeleteTasks() got = %v, want %v", len(tasks), 0) } }) } func TestDeleteTasksByStatues(t *testing.T) { doTest(func() { taskCount := 3 var wg sync.WaitGroup wg.Add(taskCount) Downloader.Listener(func(event *download.Event) { if event.Key == download.EventKeyFinally { wg.Done() } }) for i := 0; i < taskCount; i++ { httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq) } wg.Wait() httpRequestCheckOk[any](http.MethodDelete, fmt.Sprintf("/api/v1/tasks?status=%s&force=true", base.DownloadStatusDone), nil) tasks := httpRequestCheckOk[[]*download.Task](http.MethodGet, "/api/v1/tasks", nil) if len(tasks) != 0 { t.Errorf("DeleteTasks() got = %v, want %v", len(tasks), 0) } }) } func TestGetTasks(t *testing.T) { doTest(func() { var wg sync.WaitGroup wg.Add(1) Downloader.Listener(func(event *download.Event) { if event.Key == download.EventKeyFinally { wg.Done() } }) httpRequestCheckOk[string](http.MethodPost, fmt.Sprintf("/api/v1/tasks?status=%s&status=%s", base.DownloadStatusReady, base.DownloadStatusRunning), createReq) httpRequestCheckOk[[]*download.Task](http.MethodGet, "/api/v1/tasks", nil) wg.Wait() r := httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s", base.DownloadStatusDone), nil) if r[0].Status != base.DownloadStatusDone { t.Errorf("GetTasks() got = %v, want %v", r[0].Status, base.DownloadStatusDone) } r = httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s,%s", base.DownloadStatusReady, base.DownloadStatusRunning), nil) if len(r) > 0 { t.Errorf("GetTasks() got = %v, want %v", len(r), 0) } }) } func TestGetAndPutConfig(t *testing.T) { doTest(func() { cfg := httpRequestCheckOk[*base.DownloaderStoreConfig](http.MethodGet, "/api/v1/config", nil) cfg.DownloadDir = "./download" cfg.Extra = map[string]any{ "serverConfig": &Config{ Host: "127.0.0.1", Port: 8080, }, "theme": "dark", } httpRequestCheckOk[any](http.MethodPut, "/api/v1/config", cfg) newCfg := httpRequestCheckOk[*base.DownloaderStoreConfig](http.MethodGet, "/api/v1/config", nil) if !test.JsonEqual(cfg, newCfg) { t.Errorf("GetAndPutConfig() got = %v, want %v", test.ToJson(newCfg), test.ToJson(cfg)) } }) } func TestInstallExtension(t *testing.T) { doTest(func() { identity := httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq) if identity == "" { t.Errorf("InstallExtension() got = %v, want %v", identity, "not empty") } // not a valid extension repository code, _ := httpRequest[string](http.MethodPost, "/api/v1/extensions", &model.InstallExtension{ URL: "https://github.com/GopeedLab/gopeed", }) checkCode(code, model.CodeError) // not a git repository code, _ = httpRequest[string](http.MethodPost, "/api/v1/extensions", &model.InstallExtension{ URL: "https://github.com", }) checkCode(code, model.CodeError) }) } func TestGetExtensions(t *testing.T) { doTest(func() { httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq) extensions := httpRequestCheckOk[[]*download.Extension](http.MethodGet, "/api/v1/extensions", nil) if len(extensions) == 0 { t.Errorf("GetExtensions() got = %v, want %v", len(extensions), "not empty") } }) } func TestUpdateExtensionSettings(t *testing.T) { doTest(func() { identity := httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq) httpRequestCheckOk[any](http.MethodPut, "/api/v1/extensions/"+identity+"/settings", &model.UpdateExtensionSettings{ Settings: map[string]any{ "undefined": "test", "ua": "test", }, }) settings := httpRequestCheckOk[*download.Extension](http.MethodGet, "/api/v1/extensions/"+identity, nil).Settings if len(settings) != 1 { t.Errorf("UpdateExtensionSettings() got = %v, want %v", len(settings), 1) } if settings[0].Name != "ua" || settings[0].Value != "test" { t.Errorf("UpdateExtensionSettings() got = %v, want %v", settings[0].Value, "test") } }) } func TestSwitchExtension(t *testing.T) { doTest(func() { identity := httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq) httpRequestCheckOk[any](http.MethodPut, "/api/v1/extensions/"+identity+"/switch", &model.SwitchExtension{ Status: false, }) extensions := httpRequestCheckOk[[]*download.Extension](http.MethodGet, "/api/v1/extensions", nil) if !extensions[0].Disabled { t.Errorf("TestSwitchExtension() got = %v, want %v", extensions[0].Disabled, true) } }) } func TestDeleteExtension(t *testing.T) { doTest(func() { identity := httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq) httpRequestCheckOk[any](http.MethodDelete, "/api/v1/extensions/"+identity, nil) extensions := httpRequestCheckOk[[]*download.Extension](http.MethodGet, "/api/v1/extensions", nil) if len(extensions) != 0 { t.Errorf("TestDeleteExtension() got = %v, want %v", len(extensions), 0) } }) } func TestUpdateCheckExtension(t *testing.T) { doTest(func() { identity := httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq) resp := httpRequestCheckOk[*model.UpdateCheckExtensionResp](http.MethodGet, "/api/v1/extensions/"+identity+"/update", nil) // no new version if resp.NewVersion != "" { t.Errorf("UpdateCheckExtension() got = %v, want %v", resp.NewVersion, "") } // force update httpRequestCheckOk[any](http.MethodPost, "/api/v1/extensions/"+identity+"/update", nil) }) } func TestFsExtension(t *testing.T) { doTest(func() { identity := httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq) statusCode, _ := doHttpRequest0(http.MethodGet, "/fs/extensions/"+identity+"/icon.png", nil, nil) if statusCode != http.StatusOK { t.Errorf("FsExtension() got = %v, want %v", statusCode, http.StatusOK) } }) } func TestFsExtensionFail(t *testing.T) { doTest(func() { statusCode, _ := doHttpRequest0(http.MethodGet, "/fs/extensions/not_exist/icon.png", nil, nil) if statusCode != http.StatusNotFound { t.Errorf("TestFsExtensionFail() got = %v, want %v", statusCode, http.StatusNotFound) } }) } func TestWebFsEnhance(t *testing.T) { indexHtml := `