blossom_test.mx raw
1 package blossom
2
3 import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "io"
9 "net/http"
10 "net/http/httptest"
11 "testing"
12 )
13
14 func TestUploadAndDownload(t *testing.T) {
15 srv, err := New(t.TempDir())
16 if err != nil {
17 t.Fatal(err)
18 }
19 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
20 // Bypass auth for testing
21 if r.Method == "PUT" || r.Method == "POST" {
22 srv.storeFile(w, r)
23 return
24 }
25 srv.ServeHTTP(w, r)
26 }))
27 defer ts.Close()
28
29 data := []byte("hello blossom")
30 resp, err := http.Post(ts.URL+"/upload", "application/octet-stream", bytes.NewReader(data))
31 if err != nil {
32 t.Fatal(err)
33 }
34 defer resp.Body.Close()
35 if resp.StatusCode != 200 {
36 body, _ := io.ReadAll(resp.Body)
37 t.Fatalf("upload status %d: %s", resp.StatusCode, body)
38 }
39
40 var result map[string]any
41 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
42 t.Fatal(err)
43 }
44 hash, ok := result["sha256"].(string)
45 if !ok || len(hash) != 64 {
46 t.Fatalf("bad hash in response: %v", result)
47 }
48
49 // Verify hash
50 expected := sha256.Sum256(data)
51 if hash != hex.EncodeToString(expected[:]) {
52 t.Error("hash mismatch")
53 }
54
55 // Download
56 resp2, err := http.Get(ts.URL + "/" + hash)
57 if err != nil {
58 t.Fatal(err)
59 }
60 defer resp2.Body.Close()
61 got, _ := io.ReadAll(resp2.Body)
62 if !bytes.Equal(got, data) {
63 t.Errorf("download mismatch: got %q, want %q", got, data)
64 }
65 }
66
67 func TestDownloadNotFound(t *testing.T) {
68 srv, err := New(t.TempDir())
69 if err != nil {
70 t.Fatal(err)
71 }
72 ts := httptest.NewServer(srv)
73 defer ts.Close()
74
75 resp, err := http.Get(ts.URL + "/" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
76 if err != nil {
77 t.Fatal(err)
78 }
79 resp.Body.Close()
80 if resp.StatusCode != 404 {
81 t.Errorf("expected 404, got %d", resp.StatusCode)
82 }
83 }
84
85 func TestBadHashPath(t *testing.T) {
86 srv, err := New(t.TempDir())
87 if err != nil {
88 t.Fatal(err)
89 }
90 ts := httptest.NewServer(srv)
91 defer ts.Close()
92
93 resp, err := http.Get(ts.URL + "/not-a-hash")
94 if err != nil {
95 t.Fatal(err)
96 }
97 resp.Body.Close()
98 if resp.StatusCode != 404 {
99 t.Errorf("expected 404 for bad hash, got %d", resp.StatusCode)
100 }
101 }
102
103 func TestIsHex(t *testing.T) {
104 if !isHex("0123456789abcdef") {
105 t.Error("valid hex rejected")
106 }
107 if isHex("xyz") {
108 t.Error("invalid hex accepted")
109 }
110 }
111