Skip to content

Commit 59228aa

Browse files
author
Vipul Rawat
authored
Merge pull request #344 from gofr-dev/development
Release v1.0.1
2 parents c068bf2 + 9ce5abb commit 59228aa

File tree

17 files changed

+294
-26
lines changed

17 files changed

+294
-26
lines changed

examples/http-server-using-redis/main_test.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,21 @@ package main
22

33
import (
44
"bytes"
5+
"context"
6+
57
"net/http"
68
"testing"
79
"time"
810

11+
"github.com/go-redis/redismock/v9"
912
"github.com/stretchr/testify/assert"
13+
14+
"gofr.dev/pkg/gofr"
15+
"gofr.dev/pkg/gofr/container"
16+
"gofr.dev/pkg/gofr/datasource/redis"
17+
gofrHTTP "gofr.dev/pkg/gofr/http"
18+
"gofr.dev/pkg/gofr/logging"
19+
"gofr.dev/pkg/gofr/testutil"
1020
)
1121

1222
func TestHTTPServerUsingRedis(t *testing.T) {
@@ -41,3 +51,50 @@ func TestHTTPServerUsingRedis(t *testing.T) {
4151
assert.Equal(t, tc.statusCode, resp.StatusCode, "TEST[%d], Failed.\n%s", i, tc.desc)
4252
}
4353
}
54+
55+
func TestRedisSetHandler(t *testing.T) {
56+
a := gofr.New()
57+
logger := logging.NewLogger(logging.DEBUG)
58+
redisClient, mock := redismock.NewClientMock()
59+
60+
rc := redis.NewClient(testutil.NewMockConfig(map[string]string{"REDIS_HOST": "localhost", "REDIS_PORT": "2001"}), logger, a.Metrics())
61+
rc.Client = redisClient
62+
63+
mock.ExpectSet("key", "value", 5*time.Minute).SetErr(testutil.CustomError{ErrorMessage: "redis get error"})
64+
65+
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:5000/handle", bytes.NewBuffer([]byte(`{"key":"value"}`)))
66+
67+
gofrReq := gofrHTTP.NewRequest(req)
68+
69+
ctx := &gofr.Context{Context: context.Background(),
70+
Request: gofrReq, Container: &container.Container{Logger: logger, Redis: rc}}
71+
72+
resp, err := RedisSetHandler(ctx)
73+
74+
assert.Nil(t, resp)
75+
assert.NotNil(t, err)
76+
}
77+
78+
func TestRedisPipelineHandler(t *testing.T) {
79+
a := gofr.New()
80+
logger := logging.NewLogger(logging.DEBUG)
81+
redisClient, mock := redismock.NewClientMock()
82+
83+
rc := redis.NewClient(testutil.NewMockConfig(map[string]string{"REDIS_HOST": "localhost", "REDIS_PORT": "2001"}), logger, a.Metrics())
84+
rc.Client = redisClient
85+
86+
mock.ExpectSet("testKey1", "testValue1", time.Minute*5).SetErr(testutil.CustomError{ErrorMessage: "redis get error"})
87+
mock.ClearExpect()
88+
89+
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:5000/handle", bytes.NewBuffer([]byte(`{"key":"value"}`)))
90+
91+
gofrReq := gofrHTTP.NewRequest(req)
92+
93+
ctx := &gofr.Context{Context: context.Background(),
94+
Request: gofrReq, Container: &container.Container{Logger: logger, Redis: rc}}
95+
96+
resp, err := RedisPipelineHandler(ctx)
97+
98+
assert.Nil(t, resp)
99+
assert.NotNil(t, err)
100+
}

examples/http-server/README.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,9 @@ docker run --name gofr-redis -p 2002:6379 -d redis:7.0.5
1111

1212
- Run the docker image of mysql
1313
```console
14-
docker run --name gofr-mysql -e MYSQL_ROOT_PASSWORD=password -p 2001:3306 -d mysql:8.0.30
14+
docker run --name gofr-mysql -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=test -p 2001:3306 -d mysql:8.0.30
1515
```
1616

17-
NOTE: Please create a DB named `test` as mentioned in `DB_NAME` using above mysql image.
18-
1917
- Now run the example
2018
```console
2119
go run main.go

examples/http-server/main_test.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
package main
22

33
import (
4+
"context"
45
"net/http"
56
"testing"
67
"time"
78

9+
"github.com/go-redis/redismock/v9"
810
"github.com/stretchr/testify/assert"
11+
12+
"gofr.dev/pkg/gofr"
13+
"gofr.dev/pkg/gofr/container"
14+
"gofr.dev/pkg/gofr/datasource/redis"
15+
"gofr.dev/pkg/gofr/logging"
16+
"gofr.dev/pkg/gofr/testutil"
917
)
1018

11-
func TestSimpleAPIServer(t *testing.T) {
19+
func TestIntegration_SimpleAPIServer(t *testing.T) {
1220
const host = "http://localhost:9000"
1321
go main()
1422
time.Sleep(time.Second * 3) // Giving some time to start the server
@@ -39,3 +47,22 @@ func TestSimpleAPIServer(t *testing.T) {
3947
assert.Equal(t, tc.statusCode, resp.StatusCode, "TEST[%d], Failed.\n%s", i, tc.desc)
4048
}
4149
}
50+
51+
func TestRedisHandler(t *testing.T) {
52+
a := gofr.New()
53+
logger := logging.NewLogger(logging.DEBUG)
54+
redisClient, mock := redismock.NewClientMock()
55+
56+
rc := redis.NewClient(testutil.NewMockConfig(map[string]string{"REDIS_HOST": "localhost", "REDIS_PORT": "2001"}), logger, a.Metrics())
57+
rc.Client = redisClient
58+
59+
mock.ExpectGet("test").SetErr(testutil.CustomError{ErrorMessage: "redis get error"})
60+
61+
ctx := &gofr.Context{Context: context.Background(),
62+
Request: nil, Container: &container.Container{Logger: logger, Redis: rc}}
63+
64+
resp, err := RedisHandler(ctx)
65+
66+
assert.Nil(t, resp)
67+
assert.NotNil(t, err)
68+
}
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
HTTP_PORT=9011
2+
13
APP_NAME=using-metrics
24
APP_VERSION=v0.1.0
35

4-
METRICS_PORT=2121
6+
METRICS_PORT=2120
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package main
2+
3+
import (
4+
"io"
5+
"net/http"
6+
"testing"
7+
"time"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func TestIntegration(t *testing.T) {
13+
const host = "http://localhost:9011"
14+
go main()
15+
time.Sleep(time.Second * 1) // Giving some time to start the server
16+
17+
c := http.Client{}
18+
19+
req, _ := http.NewRequest("POST", host+"/transaction", nil)
20+
21+
_, err := c.Do(req)
22+
if err != nil {
23+
t.Fatalf("request to /transaction failed %v", err)
24+
}
25+
26+
req, _ = http.NewRequest("POST", host+"/return", nil)
27+
28+
_, err = c.Do(req)
29+
if err != nil {
30+
t.Fatalf("request to /transaction failed %v", err)
31+
}
32+
33+
req, _ = http.NewRequest("GET", "http://localhost:2120/metrics", nil)
34+
35+
resp, err := c.Do(req)
36+
if err != nil {
37+
t.Fatalf("request to localhost:2120/metrics failed %v", err)
38+
}
39+
40+
body, _ := io.ReadAll(resp.Body)
41+
42+
strBody := string(body)
43+
44+
assert.Equal(t, http.StatusOK, resp.StatusCode, "TEST[%d], Failed.\n%s")
45+
46+
assert.Contains(t, strBody, `product_stock{otel_scope_name="using-metrics",otel_scope_version="v0.1.0"} 50`)
47+
assert.Contains(t, strBody, `total_credit_day_sale{otel_scope_name="using-metrics",otel_scope_version="v0.1.0",sale_type="credit"} 1000`)
48+
assert.Contains(t, strBody, `total_credit_day_sale{otel_scope_name="using-metrics",otel_scope_version="v0.1.0",sale_type="credit_return"} -1000`)
49+
assert.Contains(t, strBody, `transaction_success_total{otel_scope_name="using-metrics",otel_scope_version="v0.1.0"} 1`)
50+
assert.Contains(t, strBody, "transaction_time")
51+
}

examples/using-http-service/main_test.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
package main
22

33
import (
4+
"bytes"
5+
"context"
46
"io"
57
"net/http"
8+
"net/http/httptest"
69
"testing"
710
"time"
811

912
"github.com/stretchr/testify/assert"
13+
14+
"gofr.dev/pkg/gofr"
15+
"gofr.dev/pkg/gofr/container"
16+
gofrHTTP "gofr.dev/pkg/gofr/http"
17+
"gofr.dev/pkg/gofr/logging"
18+
"gofr.dev/pkg/gofr/service"
1019
)
1120

1221
func Test_main(t *testing.T) {
@@ -54,3 +63,46 @@ func Test_main(t *testing.T) {
5463
resp.Body.Close()
5564
}
5665
}
66+
67+
func TestHTTPHandlerURLError(t *testing.T) {
68+
logger := logging.NewLogger(logging.DEBUG)
69+
70+
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:5000/handle", bytes.NewBuffer([]byte(`{"key":"value"}`)))
71+
72+
gofrReq := gofrHTTP.NewRequest(req)
73+
74+
ctx := &gofr.Context{Context: context.Background(),
75+
Request: gofrReq, Container: &container.Container{Logger: logger}}
76+
77+
ctx.Container.Services = map[string]service.HTTP{"cat-facts": service.NewHTTPService("http://invalid", ctx.Logger, nil)}
78+
79+
resp, err := Handler(ctx)
80+
81+
assert.Nil(t, resp)
82+
assert.NotNil(t, err)
83+
}
84+
85+
func TestHTTPHandlerResponseUnmarshalError(t *testing.T) {
86+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
87+
// read request body
88+
w.WriteHeader(http.StatusOK)
89+
w.Write([]byte(`{invalid body}`))
90+
}))
91+
defer server.Close()
92+
93+
logger := logging.NewLogger(logging.DEBUG)
94+
95+
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:5000/handle", bytes.NewBuffer([]byte(`{"key":"value"}`)))
96+
97+
gofrReq := gofrHTTP.NewRequest(req)
98+
99+
ctx := &gofr.Context{Context: context.Background(),
100+
Request: gofrReq, Container: &container.Container{Logger: logger}}
101+
102+
ctx.Container.Services = map[string]service.HTTP{"cat-facts": service.NewHTTPService(server.URL, ctx.Logger, nil)}
103+
104+
resp, err := Handler(ctx)
105+
106+
assert.Nil(t, resp)
107+
assert.NotNil(t, err)
108+
}

examples/using-migrations/main.go

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,10 @@ func GetHandler(c *gofr.Context) (interface{}, error) {
4343
return nil, errors.New("name can't be empty")
4444
}
4545

46-
row := c.SQL.QueryRowContext(c, queryGetEmployee, name)
47-
if row.Err() != nil {
48-
return nil, errors.New(fmt.Sprintf("DB Error : %v", row.Err()))
49-
}
50-
5146
var emp Employee
5247

53-
err := row.Scan(&emp.ID, &emp.Name, &emp.Gender, &emp.Phone, &emp.DOB)
48+
err := c.SQL.QueryRowContext(c, queryGetEmployee, name).
49+
Scan(&emp.ID, &emp.Name, &emp.Gender, &emp.Phone, &emp.DOB)
5450
if err != nil {
5551
return nil, errors.New(fmt.Sprintf("DB Error : %v", err))
5652
}
@@ -68,10 +64,9 @@ func PostHandler(c *gofr.Context) (interface{}, error) {
6864

6965
// Execute the INSERT query
7066
_, err := c.SQL.ExecContext(c, queryInsertEmployee, emp.ID, emp.Name, emp.Gender, emp.Phone, emp.DOB)
71-
7267
if err != nil {
7368
return Employee{}, errors.New(fmt.Sprintf("DB Error : %v", err))
7469
}
7570

76-
return fmt.Sprintf("succesfully posted entity : %v", emp.Name), nil
71+
return fmt.Sprintf("successfully posted entity : %v", emp.Name), nil
7772
}

examples/using-migrations/main_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,12 @@ func TestExampleMigration(t *testing.T) {
2424
{"post new employee with valid data", http.MethodPost, "/employee",
2525
[]byte(`{"id":2,"name":"John","gender":"Male","contact_number":1234567890,"dob":"2000-01-01"}`), 200},
2626
{"get employee with valid name", http.MethodGet, "/employee?name=John", nil, 200},
27+
{"get employee does not exist", http.MethodGet, "/employee?name=Invalid", nil, 500},
2728
{"get employee with empty name", http.MethodGet, "/employee", nil, http.StatusInternalServerError},
2829
{"post new employee with invalid data", http.MethodPost, "/employee", []byte(`{"id":2"}`),
2930
http.StatusInternalServerError},
31+
{"post new employee with invalid gender", http.MethodPost, "/employee",
32+
[]byte(`{"id":2,"name":"John","gender":"Male123","contact_number":1234567890,"dob":"2000-01-01"}`), 500},
3033
}
3134

3235
for i, tc := range tests {

examples/using-migrations/readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ This GoFr example demonstrates the use of `migrations` through a simple http ser
66
- Run the docker image of mysql and redis
77

88
```console
9-
docker run --name gofr-mysql -e MYSQL_ROOT_PASSWORD=password -p 2001:3306 -d mysql:8.0.30
9+
docker run --name gofr-mysql -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=test -p 2001:3306 -d mysql:8.0.30
1010
docker run --name gofr-redis -p 2002:6379 -d redis:7.0.5
1111
```
1212

examples/using-publisher/main.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@ package main
22

33
import (
44
"encoding/json"
5+
"fmt"
56

67
"gofr.dev/pkg/gofr"
78
)
89

910
func main() {
1011
app := gofr.New()
1112

13+
fmt.Println(app.Config.Get("PUBSUB_BROKER"))
14+
1215
app.POST("/publish-order", order)
1316

1417
app.POST("/publish-product", product)

0 commit comments

Comments
 (0)