mcias/client/client_test.go

81 lines
2.2 KiB
Go

package client
import (
"net/http"
"testing"
"time"
)
func TestNewClient(t *testing.T) {
// Test default client
client := NewClient()
if client.BaseURL != "http://localhost:8080" {
t.Errorf("Expected BaseURL to be http://localhost:8080, got %s", client.BaseURL)
}
if client.HTTPClient == nil {
t.Error("Expected HTTPClient to be initialized")
}
if client.Token != "" {
t.Errorf("Expected Token to be empty, got %s", client.Token)
}
if client.Username != "" {
t.Errorf("Expected Username to be empty, got %s", client.Username)
}
// Test client with options
customHTTPClient := &http.Client{Timeout: 5 * time.Second}
client = NewClient(
WithBaseURL("https://mcias.example.com"),
WithHTTPClient(customHTTPClient),
WithToken("test-token"),
WithUsername("test-user"),
)
if client.BaseURL != "https://mcias.example.com" {
t.Errorf("Expected BaseURL to be https://mcias.example.com, got %s", client.BaseURL)
}
if client.HTTPClient != customHTTPClient {
t.Error("Expected HTTPClient to be the custom client")
}
if client.Token != "test-token" {
t.Errorf("Expected Token to be test-token, got %s", client.Token)
}
if client.Username != "test-user" {
t.Errorf("Expected Username to be test-user, got %s", client.Username)
}
}
func TestIsAuthenticated(t *testing.T) {
// Test unauthenticated client
client := NewClient()
if client.IsAuthenticated() {
t.Error("Expected IsAuthenticated to return false for client without token")
}
// Test authenticated client
client = NewClient(WithToken("test-token"))
if !client.IsAuthenticated() {
t.Error("Expected IsAuthenticated to return true for client with token")
}
}
func TestIsTokenExpired(t *testing.T) {
client := NewClient()
// Test expired token
pastTime := time.Now().Add(-1 * time.Hour).Unix()
if !client.IsTokenExpired(pastTime) {
t.Error("Expected IsTokenExpired to return true for past time")
}
// Test valid token
futureTime := time.Now().Add(1 * time.Hour).Unix()
if client.IsTokenExpired(futureTime) {
t.Error("Expected IsTokenExpired to return false for future time")
}
// Test zero time (no expiry)
if client.IsTokenExpired(0) {
t.Error("Expected IsTokenExpired to return false for zero time")
}
}