Skip to content

Commit cbd0db3

Browse files
yahya077yahya.hindioglu
authored andcommitted
test coverage
1 parent 996cca9 commit cbd0db3

File tree

19 files changed

+608
-384
lines changed

19 files changed

+608
-384
lines changed

body.go

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ func (f FormURLEncodedBody) Parse() *bytes.Buffer {
4444

4545
switch f.v.(type) {
4646
case map[string]any:
47-
values = mapToUrlValues(f.v.(map[string]any))
47+
for key, value := range f.v.(map[string]any) {
48+
values.Add(key, value.(string))
49+
}
4850
default:
4951
values, _ = query.Values(f.v)
5052
}
@@ -55,13 +57,3 @@ func (f FormURLEncodedBody) Parse() *bytes.Buffer {
5557
type dumpBody struct{}
5658

5759
func (f dumpBody) Parse() *bytes.Buffer { return new(bytes.Buffer) }
58-
59-
func mapToUrlValues(v map[string]any) url.Values {
60-
values := url.Values{}
61-
62-
for key, value := range v {
63-
values.Add(key, value.(string))
64-
}
65-
66-
return values
67-
}

body_test.go

Lines changed: 61 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,81 @@
11
package room
22

33
import (
4+
"strings"
45
"testing"
56
)
67

78
func TestJsonBody_Parse(t *testing.T) {
9+
// Test case where JSON encoding is successful
810
data := map[string]interface{}{"key": "value"}
9-
body := NewJsonBodyParser(data).Parse()
10-
11-
if body == nil {
12-
t.Error("Expected a non-nil buffer, but got nil")
11+
body := JsonBody{v: data}
12+
buffer := body.Parse()
13+
expected := `{"key":"value"}`
14+
bufferString := strings.TrimRight(buffer.String(), "\n") // Remove trailing newline
15+
if bufferString != expected {
16+
t.Errorf("JsonBody Parse() returned %s, expected %s", bufferString, expected)
1317
}
1418

15-
// Optionally, you can check the content of the buffer or other expectations.
19+
// Test case where JSON encoding fails
20+
defer func() {
21+
if r := recover(); r == nil {
22+
t.Error("JsonBody Parse() did not panic when JSON encoding failed")
23+
}
24+
}()
25+
invalidData := make(chan int) // Invalid data for JSON encoding
26+
invalidBody := JsonBody{v: invalidData}
27+
_ = invalidBody.Parse()
1628
}
1729

18-
type testStruct struct {
19-
Key string `url:"key"`
30+
func TestFormURLEncodedBodyAsStruct_Parse(t *testing.T) {
31+
mapData := struct {
32+
Key1 string `url:"key1"`
33+
Key2 int `url:"key2"`
34+
}{"value1", 42}
35+
body := FormURLEncodedBody{v: mapData}
36+
buffer := body.Parse()
37+
expected := "key1=value1&key2=42"
38+
if buffer.String() != expected {
39+
t.Errorf("FormURLEncodedBody Parse() returned %s, expected %s", buffer.String(), expected)
40+
}
2041
}
2142

22-
func TestFormURLEncodedBody_Parse(t *testing.T) {
23-
data := testStruct{"value"}
24-
body := NewFormURLEncodedBodyParser(data).Parse()
25-
26-
if body == nil {
27-
t.Error("Expected a non-nil buffer, but got nil")
43+
func TestFormURLEncodedBodyAsMap_Parse(t *testing.T) {
44+
mapData := map[string]any{"key1": "value1", "key2": "42"}
45+
body := FormURLEncodedBody{v: mapData}
46+
buffer := body.Parse()
47+
expected := "key1=value1&key2=42"
48+
if buffer.String() != expected {
49+
t.Errorf("FormURLEncodedBody Parse() returned %s, expected %s", buffer.String(), expected)
2850
}
51+
}
2952

30-
// Optionally, you can check the content of the buffer or other expectations.
53+
func TestDumpBody_Parse(t *testing.T) {
54+
// Test DumpBody Parse() always returns an empty buffer
55+
body := dumpBody{}
56+
buffer := body.Parse()
57+
expected := ""
58+
if buffer.String() != expected {
59+
t.Errorf("DumpBody Parse() returned %s, expected empty", buffer.String())
60+
}
3161
}
3262

33-
func TestFormURLEncodedBody_Parse_Error(t *testing.T) {
34-
// Test case where query.Values returns an error
35-
data := map[string]interface{}{"key": make(chan int)} // invalid type to trigger an error
36-
defer func() {
37-
if r := recover(); r == nil {
38-
t.Error("Expected a panic, but no panic occurred")
39-
}
40-
}()
63+
func TestNewJsonBodyParser(t *testing.T) {
64+
// Test NewJsonBodyParser() creates a JsonBody instance
65+
data := map[string]interface{}{"key": "value"}
66+
bodyParser := NewJsonBodyParser(data)
67+
_, ok := bodyParser.(JsonBody)
68+
if !ok {
69+
t.Error("NewJsonBodyParser() did not return a JsonBody instance")
70+
}
71+
}
4172

42-
_ = NewFormURLEncodedBodyParser(data).Parse()
73+
func TestNewFormURLEncodedBodyParser(t *testing.T) {
74+
// Test NewFormURLEncodedBodyParser() creates a FormURLEncodedBody instance
75+
data := map[string]interface{}{"key": "value"}
76+
bodyParser := NewFormURLEncodedBodyParser(data)
77+
_, ok := bodyParser.(FormURLEncodedBody)
78+
if !ok {
79+
t.Error("NewFormURLEncodedBodyParser() did not return a FormURLEncodedBody instance")
80+
}
4381
}

context_test.go

Lines changed: 20 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,33 @@ package room
22

33
import (
44
"context"
5-
"github.com/stretchr/testify/assert"
65
"testing"
76
"time"
87
)
98

10-
// Test cases for ContextBuilder
119
func TestContextBuilder_Build(t *testing.T) {
12-
// Test case: Build context without a timeout
13-
builderWithoutTimeout := NewContextBuilder(0)
14-
ctxWithoutTimeout := builderWithoutTimeout.Build()
10+
// Test case where timeout is not set
11+
builder := NewContextBuilder(0)
12+
ctx := builder.Build()
1513

16-
// Check if the returned context is background and cancel function is nil
17-
assert.Equal(t, context.Background(), ctxWithoutTimeout.ctx)
18-
assert.Nil(t, ctxWithoutTimeout.cancel)
19-
20-
// Test case: Build context with a timeout
21-
timeoutDuration := time.Second * 5
22-
builderWithTimeout := NewContextBuilder(timeoutDuration)
23-
ctxWithTimeout := builderWithTimeout.Build()
24-
25-
// Check if the returned context is with a timeout and cancel function is not nil
26-
assert.NotEqual(t, context.Background(), ctxWithTimeout.ctx)
27-
assert.NotNil(t, ctxWithTimeout.cancel)
28-
29-
// Check if the context is canceled after the specified timeout
30-
select {
31-
case <-ctxWithTimeout.ctx.Done():
32-
// Context is canceled, as expected
33-
case <-time.After(timeoutDuration + time.Second): // Allow extra time for the context to be canceled
34-
t.Error("Context is not canceled within the specified timeout")
14+
// Ensure that the context is background context and cancel function is nil
15+
if ctx.Ctx != context.Background() {
16+
t.Error("Context is not background context when timeout is not set")
17+
}
18+
if ctx.Cancel != nil {
19+
t.Error("Cancel function is not nil when timeout is not set")
3520
}
3621

37-
// Ensure cancel function is called after the test
38-
defer ctxWithTimeout.cancel()
39-
}
40-
41-
func TestContextBuilder_Timeout(t *testing.T) {
42-
// Test case: Get timeout from the ContextBuilder
43-
timeoutDuration := time.Second * 10
44-
builder := NewContextBuilder(timeoutDuration)
22+
// Test case where timeout is set
23+
timeout := time.Second
24+
builder = NewContextBuilder(timeout)
25+
ctx = builder.Build()
4526

46-
// Check if the returned timeout matches the expected value
47-
assert.Equal(t, timeoutDuration, builder.Timeout())
27+
// Ensure that the context is context with timeout and cancel function is not nil
28+
if ctx.Ctx.Err() != nil {
29+
t.Error("Context is not context with timeout when timeout is set")
30+
}
31+
if ctx.Cancel == nil {
32+
t.Error("Cancel function is nil when timeout is set")
33+
}
4834
}

elevator/elevator.go

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ type IElevatorEngine interface {
3838
PutQuery(roomKey, requestKey string, authStrategy room.IQuery) IElevatorEngine
3939
PutDTO(roomKey, requestKey string, dto any) IElevatorEngine
4040
GetElapsedTime() float64
41-
PutAuthStrategy(roomKey string, authStrategy room.IAuth) IElevatorEngine
4241
}
4342

4443
type ElevatorEngine struct {
@@ -52,7 +51,7 @@ func (e *ElevatorEngine) GetElapsedTime() float64 {
5251
}
5352

5453
type RoomContainer struct {
55-
Room room.IAuthRoom
54+
Room room.IRoom
5655
Requests map[string]*room.Request
5756
}
5857

@@ -126,12 +125,12 @@ func (e *ElevatorEngine) WarmUp() IElevatorEngine {
126125
room.WithHeaderContextBuilder(room.NewContextBuilder(time.Duration(r.Connection.Timeout)*time.Second)),
127126
)
128127

129-
var roomObj room.IAuthRoom
128+
var roomObj room.IRoom
130129

131130
if r.Connection.Auth.Type == "bearer" {
132-
roomObj = room.NewAuthRoom(c, nil, e.CreateRequest(r.Connection.Auth.Request))
131+
roomObj = room.NewAuthRoom(c, e.CreateRequest(r.Connection.Auth.Request), r.Connection.Auth.AccessTokenKey)
133132
} else {
134-
roomObj = room.NewAuthRoom(c, nil, nil)
133+
roomObj = room.NewAuthRoom(c, nil, "")
135134
}
136135

137136
roomContainers[roomKey] = RoomContainer{
@@ -198,15 +197,6 @@ func (e *ElevatorEngine) PutQuery(roomKey, requestKey string, query room.IQuery)
198197
panic(fmt.Sprintf("engine for %s not configured", roomKey))
199198
}
200199

201-
func (e *ElevatorEngine) PutAuthStrategy(roomKey string, authStrategy room.IAuth) IElevatorEngine {
202-
if roomContainerEntry, ok := e.RoomContainers[roomKey]; ok {
203-
roomContainerEntry.Room.SetAuthStrategy(authStrategy)
204-
return e
205-
}
206-
207-
panic(fmt.Sprintf("engine for %s not configured", roomKey))
208-
}
209-
210200
func (e *ElevatorEngine) PutDTO(roomKey, requestKey string, dto any) IElevatorEngine {
211201
if roomContainerEntry, ok := e.RoomContainers[roomKey]; ok {
212202
if requestEntry, ok := roomContainerEntry.Requests[requestKey]; ok {
@@ -289,8 +279,9 @@ type Connection struct {
289279
}
290280

291281
type ConnectionAuth struct {
292-
Type string `yaml:"type"`
293-
Request Request `yaml:"request"`
282+
Type string `yaml:"type"`
283+
AccessTokenKey string `yaml:"accessTokenKey"`
284+
Request Request `yaml:"request"`
294285
}
295286

296287
type Request struct {

enums_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package room
2+
3+
import "testing"
4+
5+
func TestHTTPMethod_String(t *testing.T) {
6+
tests := []struct {
7+
method HTTPMethod
8+
expected string
9+
}{
10+
{GET, "GET"},
11+
{POST, "POST"},
12+
{PUT, "PUT"},
13+
{PATCH, "PATCH"},
14+
{DELETE, "DELETE"},
15+
{HEAD, "HEAD"},
16+
{"INVALID", "GET"}, // Test case for invalid method, should default to GET
17+
}
18+
19+
for _, test := range tests {
20+
result := test.method.String()
21+
if result != test.expected {
22+
t.Errorf("HTTPMethod.String() returned %s, expected %s", result, test.expected)
23+
}
24+
}
25+
}
26+
27+
func TestHTTPProtocol_String(t *testing.T) {
28+
tests := []struct {
29+
protocol HTTPProtocol
30+
expected string
31+
}{
32+
{Http, "http://"},
33+
{Https, "https://"},
34+
{HTTPProtocol(999), "https://"}, // Test case for invalid protocol, should default to HTTPS
35+
}
36+
37+
for _, test := range tests {
38+
result := test.protocol.String()
39+
if result != test.expected {
40+
t.Errorf("HTTPProtocol.String() returned %s, expected %s", result, test.expected)
41+
}
42+
}
43+
}

examples/auth_room/main.go

Lines changed: 0 additions & 57 deletions
This file was deleted.

examples/solo_request/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import (
66
)
77

88
func main() {
9-
response, err := room.NewRequest("https://jsonplaceholder.typicode.com/posts/1").Send()
9+
response, err := room.NewRequest("https://jsonplaceholder.typicode.com/posts/1", room.ForceDTO()).Send()
1010

1111
fmt.Println(err)
1212

13-
fmt.Println("Response:", response)
13+
fmt.Println("Response:", response.DTO)
1414
}

examples/yml_example/integration.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ flat:
88
Content-Type: "application/json"
99
auth:
1010
type: "bearer"
11+
accessTokenKey: "token"
1112
request:
1213
method: "POST"
1314
path: "auth/login"

examples/yml_example/main.go

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,11 @@ var payload = AddTODORequest{
1818
UserId: 1,
1919
}
2020

21-
type Auth struct{}
22-
23-
func (a Auth) Apply(connector *room.Connector, response room.Response) {
24-
connector.Header.Add("Authorization", "Bearer "+response.DTO.(map[string]any)["token"].(string))
25-
}
26-
2721
func main() {
2822
el := elevator.NewElevator("examples/yml_example/integration.yml")
2923
engine := elevator.NewElevatorEngine(el).WarmUp()
3024

3125
response, err := engine.
32-
PutAuthStrategy("todoRoom", Auth{}).
3326
PutBodyParser("todoRoom", "addTodo", room.NewJsonBodyParser(payload)).
3427
Execute("todoRoom", "addTodo")
3528

0 commit comments

Comments
 (0)