diff --git a/cmd/serve_test.go b/cmd/serve_test.go new file mode 100644 index 0000000..6a3da47 --- /dev/null +++ b/cmd/serve_test.go @@ -0,0 +1,184 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sort" + "testing" + + "github.com/gorilla/mux" +) + +func setupTest(t *testing.T) (string, func()) { + tempDir := t.TempDir() + oldDir := serveDirectory + serveDirectory = tempDir + + return tempDir, func() { + serveDirectory = oldDir + } +} + +func TestUploadHandler_Success(t *testing.T) { + tempDir, cleanup := setupTest(t) + defer cleanup() + + r := mux.NewRouter() + r.HandleFunc("/backup/{filename}", uploadHandler).Methods("POST") + + body := bytes.NewBufferString("test data") + req := httptest.NewRequest("POST", "/backup/testfile", body) + req = mux.SetURLVars(req, map[string]string{"filename": "testfile"}) + + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Errorf("Expected status 200, got %d", w.Code) + } + + filePath := filepath.Join(tempDir, "testfile") + data, err := os.ReadFile(filePath) + if err != nil { + t.Fatal("File not created:", err) + } + + if string(data) != "test data" { + t.Errorf("Expected 'test data', got '%s'", string(data)) + } +} + +func TestUploadHandler_CreateFileError(t *testing.T) { + _, cleanup := setupTest(t) + defer cleanup() + + // Создаем директорию без прав на запись + serveDirectory = "/proc/invalid_path" + + r := mux.NewRouter() + r.HandleFunc("/backup/{filename}", uploadHandler).Methods("POST") + + body := bytes.NewBufferString("test") + req := httptest.NewRequest("POST", "/backup/testfile", body) + req = mux.SetURLVars(req, map[string]string{"filename": "testfile"}) + + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != http.StatusInternalServerError { + t.Errorf("Expected status 500, got %d", w.Code) + } +} + +func TestDownloadHandler_Success(t *testing.T) { + tempDir, cleanup := setupTest(t) + defer cleanup() + + // Создаем тестовый файл + filePath := filepath.Join(tempDir, "testfile") + if err := os.WriteFile(filePath, []byte("test data"), 0644); err != nil { + t.Fatal(err) + } + + r := mux.NewRouter() + r.HandleFunc("/backup/{filename}", downloadHandler).Methods("GET") + + req := httptest.NewRequest("GET", "/backup/testfile", nil) + req = mux.SetURLVars(req, map[string]string{"filename": "testfile"}) + + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Errorf("Expected status 200, got %d", w.Code) + } + + if body := w.Body.String(); body != "test data" { + t.Errorf("Expected 'test data', got '%s'", body) + } +} + +func TestDownloadHandler_NotFound(t *testing.T) { + _, cleanup := setupTest(t) + defer cleanup() + + r := mux.NewRouter() + r.HandleFunc("/backup/{filename}", downloadHandler).Methods("GET") + + req := httptest.NewRequest("GET", "/backup/missing", nil) + req = mux.SetURLVars(req, map[string]string{"filename": "missing"}) + + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != http.StatusNotFound { + t.Errorf("Expected status 404, got %d", w.Code) + } +} + +func TestListHandler_Success(t *testing.T) { + tempDir, cleanup := setupTest(t) + defer cleanup() + + // Создаем тестовые файлы + files := []string{"file1.txt", "file2.txt"} + for _, f := range files { + path := filepath.Join(tempDir, f) + if err := os.WriteFile(path, []byte("data"), 0644); err != nil { + t.Fatal(err) + } + } + + r := mux.NewRouter() + r.HandleFunc("/backup", listHandler).Methods("GET") + + req := httptest.NewRequest("GET", "/backup", nil) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Errorf("Expected status 200, got %d", w.Code) + } + + var result []string + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal("Failed to parse JSON:", err) + } + + sort.Strings(result) + expected := []string{"file1.txt", "file2.txt"} + sort.Strings(expected) + + if len(result) != len(expected) { + t.Fatalf("Expected %d files, got %d", len(expected), len(result)) + } + + for i := range expected { + if expected[i] != result[i] { + t.Errorf("Expected %s, got %s", expected[i], result[i]) + } + } +} + +func TestListHandler_ReadDirError(t *testing.T) { + tempDir, cleanup := setupTest(t) + defer cleanup() + + // Удаляем директорию чтобы вызвать ошибку + os.RemoveAll(tempDir) + + r := mux.NewRouter() + r.HandleFunc("/backup", listHandler).Methods("GET") + + req := httptest.NewRequest("GET", "/backup", nil) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != http.StatusInternalServerError { + t.Errorf("Expected status 500, got %d", w.Code) + } +}