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
|
package account
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestDownloadFile_Success(t *testing.T) {
expectedContent := "file content here"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(expectedContent))
}))
defer server.Close()
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "subdir", "test.png")
err := downloadFile(context.Background(), server.URL+"/icon.png", filePath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
data, err := os.ReadFile(filePath)
if err != nil {
t.Fatalf("failed to read downloaded file: %v", err)
}
if string(data) != expectedContent {
t.Errorf("expected content %q, got %q", expectedContent, string(data))
}
}
func TestDownloadFile_NotFound(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer server.Close()
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "test.png")
err := downloadFile(context.Background(), server.URL+"/missing.png", filePath)
if err == nil {
t.Error("expected error for 404 response")
}
}
func TestDownloadFile_ServerError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer server.Close()
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "test.png")
err := downloadFile(context.Background(), server.URL+"/error.png", filePath)
if err == nil {
t.Error("expected error for 500 response")
}
}
func TestDownloadFile_InvalidURL(t *testing.T) {
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "test.png")
err := downloadFile(context.Background(), "http://localhost:1/unreachable", filePath)
if err == nil {
t.Error("expected error for unreachable server")
}
}
func TestDownloadFile_ContextCanceled(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("data"))
}))
defer server.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel immediately
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "test.png")
err := downloadFile(ctx, server.URL+"/icon.png", filePath)
if err == nil {
t.Error("expected error for canceled context")
}
}
|