summaryrefslogtreecommitdiff
path: root/internal/httpctx/httpctx_test.go
blob: e9f2a85a8e8ad1dd8c38d4b00ef90ce3b21ead9c (plain)
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
package httpctx

import (
	"context"
	"net/http"
	"testing"
	"time"

	"google.golang.org/genai"
)

func TestWithTimeoutUnlessSet_AlreadyHasDeadline(t *testing.T) {
	t.Parallel()

	parent, cancel := context.WithTimeout(context.Background(), time.Hour)
	defer cancel()

	ctx, childCancel := WithTimeoutUnlessSet(parent, time.Nanosecond)
	defer childCancel()

	if ctx != parent {
		t.Fatal("expected same context when parent already has deadline")
	}
}

func TestWithTimeoutUnlessSet_NoDeadline(t *testing.T) {
	t.Parallel()

	ctx, cancel := WithTimeoutUnlessSet(context.Background(), 50*time.Millisecond)
	defer cancel()

	deadline, ok := ctx.Deadline()
	if !ok {
		t.Fatal("expected deadline")
	}
	if time.Until(deadline) > time.Second {
		t.Fatalf("deadline too far: %v", deadline)
	}
}

func TestWithTimeoutUnlessSet_NilUsesBackground(t *testing.T) {
	t.Parallel()

	ctx, cancel := WithTimeoutUnlessSet(context.Background(), 50*time.Millisecond)
	defer cancel()

	if err := ctx.Err(); err != nil {
		t.Fatalf("context should not be done: %v", err)
	}
}

func TestNewGenAIClientAppliesDefaultHTTPClient(t *testing.T) {
	t.Parallel()

	customClient := &http.Client{Timeout: time.Second}
	cfg := &genai.ClientConfig{
		APIKey: "test-key",
	}

	client, err := NewGenAIClient(context.Background(), cfg)
	if err != nil {
		t.Fatalf("NewGenAIClient() error = %v", err)
	}
	if client == nil {
		t.Fatal("NewGenAIClient() client = nil")
	}
	if cfg.HTTPClient != nil {
		t.Fatalf("NewGenAIClient() mutated input config HTTPClient = %#v, want nil", cfg.HTTPClient)
	}

	cfg2 := &genai.ClientConfig{
		APIKey:     "test-key",
		HTTPClient: customClient,
	}
	if _, err := NewGenAIClient(context.Background(), cfg2); err != nil {
		t.Fatalf("NewGenAIClient() error = %v", err)
	}
	if cfg2.HTTPClient != customClient {
		t.Fatal("NewGenAIClient() should preserve caller HTTPClient")
	}
}