File size: 5,132 Bytes
be98dc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6606d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be98dc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package api

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"reflect"
	"testing"

	"github.com/JuanCS-Dev/byte-tui/cmd/config"
)

// RoundTripFunc .
type RoundTripFunc func(req *http.Request) *http.Response

// RoundTrip .
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
	return f(req), nil
}

// NewTestClient returns *http.Client with Transport replaced to avoid making real calls
func NewTestClient(fn RoundTripFunc) *http.Client {
	return &http.Client{
		Transport: RoundTripFunc(fn),
	}
}

func TestClientAuthenticationHeaders(t *testing.T) {
	cfg := config.Config{
		ApiUrl:     "http://test.com",
		AdminToken: "test-admin",
		HFToken:    "test-hf",
	}

	client := NewClient(cfg)

	// Inject mocked HTTP client
	client.HTTPClient = NewTestClient(func(req *http.Request) *http.Response {
		// Assert Headers Correctness
		if req.Header.Get("X-Byte-Admin-Token") != "test-admin" {
			t.Errorf("Expected X-Byte-Admin-Token to be 'test-admin', got '%s'", req.Header.Get("X-Byte-Admin-Token"))
		}
		if req.Header.Get("Authorization") != "Bearer test-hf" {
			t.Errorf("Expected Authorization to be 'Bearer test-hf', got '%s'", req.Header.Get("Authorization"))
		}

		// Fake response
		return &http.Response{
			StatusCode: 200,
			Body:       io.NopCloser(bytes.NewBufferString(`{"success": true}`)),
			Header:     make(http.Header),
		}
	})

	_, err := client.Get("/test")
	if err != nil {
		t.Fatal(err)
	}
}

func TestClientGet(t *testing.T) {
	cfg := config.Config{ApiUrl: "http://test.com"}
	client := NewClient(cfg)

	client.HTTPClient = NewTestClient(func(req *http.Request) *http.Response {
		if req.Method != "GET" {
			t.Errorf("Expected method GET, got %s", req.Method)
		}
		return &http.Response{
			StatusCode: 200,
			Body:       io.NopCloser(bytes.NewBufferString(`{"data": "value"}`)),
			Header:     make(http.Header),
		}
	})

	res, err := client.Get("/some-path")
	if err != nil {
		t.Fatal(err)
	}

	expected := map[string]interface{}{"data": "value"}
	if !reflect.DeepEqual(res, expected) {
		t.Errorf("Expected %v, got %v", expected, res)
	}
}

func TestClientPost(t *testing.T) {
	cfg := config.Config{ApiUrl: "http://test.com"}
	client := NewClient(cfg)

	client.HTTPClient = NewTestClient(func(req *http.Request) *http.Response {
		if req.Method != "POST" {
			t.Errorf("Expected method POST, got %s", req.Method)
		}
		var payload map[string]interface{}
		json.NewDecoder(req.Body).Decode(&payload)
		if payload["input"] != "hello" {
			t.Errorf("Expected body {input: hello}, got %v", payload)
		}

		return &http.Response{
			StatusCode: 200,
			Body:       io.NopCloser(bytes.NewBufferString(`{"result": "ok"}`)),
			Header:     make(http.Header),
		}
	})

	res, err := client.Post("/send", map[string]interface{}{"input": "hello"})
	if err != nil {
		t.Fatal(err)
	}

	if res["result"] != "ok" {
		t.Errorf("Expected 'result': 'ok', got %v", res)
	}
}

func TestClientErrorHandling500(t *testing.T) {
	cfg := config.Config{ApiUrl: "http://test.com"}
	client := NewClient(cfg)

	client.HTTPClient = NewTestClient(func(req *http.Request) *http.Response {
		return &http.Response{
			StatusCode: 500,
			Status:     "500 Internal Server Error",
			Body:       io.NopCloser(bytes.NewBufferString(`{"detail": "Agent crashed"}`)),
			Header:     make(http.Header),
		}
	})

	_, err := client.Get("/crash")
	if err == nil {
		t.Fatal("Expected an error for 500 status code, got none")
	}

	apiErr, ok := err.(*APIError)
	if !ok {
		t.Fatalf("Expected error of type *APIError, got %T", err)
	}

	if apiErr.StatusCode != 500 {
		t.Errorf("Expected status code 500, got %d", apiErr.StatusCode)
	}
	if apiErr.Message != "Agent crashed" {
		t.Errorf("Expected message 'Agent crashed', got '%s'", apiErr.Message)
	}
}

func TestClientHealthPlaintext(t *testing.T) {
	cfg := config.Config{ApiUrl: "http://test.com"}
	client := NewClient(cfg)

	client.HTTPClient = NewTestClient(func(req *http.Request) *http.Response {
		return &http.Response{
			StatusCode: 200,
			Body:       io.NopCloser(bytes.NewBufferString("AGENT_ONLINE")),
			Header:     make(http.Header),
		}
	})

	res, err := client.Get("/health")
	if err != nil {
		t.Fatal(err)
	}

	if res["status"] != "AGENT_ONLINE" || res["ok"] != true {
		t.Errorf("Expected {ok: true, status: AGENT_ONLINE}, got %v", res)
	}
}

func TestClientPutAndDelete(t *testing.T) {
	cfg := config.Config{ApiUrl: "http://test.com"}
	client := NewClient(cfg)

	client.HTTPClient = NewTestClient(func(req *http.Request) *http.Response {
		if req.Method == "PUT" || req.Method == "DELETE" {
			return &http.Response{
				StatusCode: 200,
				Body:       io.NopCloser(bytes.NewBufferString(`{"status": "mod_ok"}`)),
				Header:     make(http.Header),
			}
		}
		return &http.Response{StatusCode: 400, Body: io.NopCloser(bytes.NewBufferString(""))}
	})

	resPut, err := client.Put("/modify", map[string]interface{}{"val": 1})
	if err != nil || resPut["status"] != "mod_ok" {
		t.Errorf("Failed PUT test")
	}

	resDel, err := client.Delete("/remove")
	if err != nil || resDel["status"] != "mod_ok" {
		t.Errorf("Failed DELETE test")
	}
}