54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package sync
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func TestUpload(t *testing.T) {
|
|
const wantKey = "secret"
|
|
var gotBody []byte
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
t.Errorf("method %s", r.Method)
|
|
}
|
|
if r.Header.Get("X-API-Key") != wantKey {
|
|
t.Errorf("X-API-Key")
|
|
}
|
|
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
|
t.Errorf("Content-Type %q", ct)
|
|
}
|
|
var err error
|
|
gotBody, err = io.ReadAll(r.Body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}))
|
|
defer srv.Close()
|
|
|
|
client := srv.Client()
|
|
body := []byte(`{"ok":true}`)
|
|
if err := Upload(context.Background(), client, srv.URL, wantKey, body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if string(gotBody) != string(body) {
|
|
t.Fatalf("body %q", gotBody)
|
|
}
|
|
}
|
|
|
|
func TestUploadNon2xx(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
http.Error(w, "nope", http.StatusTeapot)
|
|
}))
|
|
defer srv.Close()
|
|
|
|
err := Upload(context.Background(), srv.Client(), srv.URL, "k", []byte("{}"))
|
|
if err == nil {
|
|
t.Fatal("expected error")
|
|
}
|
|
}
|