This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package shelly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestClientGetStatusUsesStatusEndpointAndBasicAuth(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != "/device/status" {
|
||||
t.Errorf("request path = %q, want /device/status", request.URL.Path)
|
||||
}
|
||||
username, password, ok := request.BasicAuth()
|
||||
if !ok || username != "admin" || password != "secret" {
|
||||
t.Errorf("BasicAuth() = (%q, %q, %t), want admin, secret, true", username, password, ok)
|
||||
}
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
_, _ = response.Write([]byte(`{"serial":42}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(server.URL+"/device/", "admin", "secret", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var status struct {
|
||||
Serial int `json:"serial"`
|
||||
}
|
||||
if err := client.GetStatus(context.Background(), &status); err != nil {
|
||||
t.Fatalf("GetStatus() returned an unexpected error: %v", err)
|
||||
}
|
||||
if status.Serial != 42 {
|
||||
t.Fatalf("Serial = %d, want 42", status.Serial)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetStatusReportsHTTPError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(response, "not authorized", http.StatusUnauthorized)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(server.URL, "admin", "wrong", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = client.GetStatus(context.Background(), &struct{}{})
|
||||
if err == nil || !strings.Contains(err.Error(), "401 Unauthorized") {
|
||||
t.Fatalf("GetStatus() error = %v, want a 401 error", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user