Skip to content

Commit 4944157

Browse files
authored
fix the duplicates (#44)
* fix the duplicates * improve the function RunTestCase
1 parent f663b69 commit 4944157

File tree

12 files changed

+171
-61
lines changed

12 files changed

+171
-61
lines changed

cmd/run_test.go

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
"github.com/h2non/gock"
1010
"github.com/linuxsuren/api-testing/pkg/limit"
11+
"github.com/linuxsuren/api-testing/pkg/util"
1112
fakeruntime "github.com/linuxsuren/go-fake-runtime"
1213
"github.com/spf13/cobra"
1314
"github.com/stretchr/testify/assert"
@@ -41,14 +42,12 @@ func TestRunSuite(t *testing.T) {
4142
}, {
4243
name: "not found file",
4344
suiteFile: "testdata/fake.yaml",
44-
prepare: func() {},
4545
hasError: true,
4646
}}
4747
for _, tt := range tests {
4848
t.Run(tt.name, func(t *testing.T) {
4949
defer gock.Clean()
50-
51-
tt.prepare()
50+
util.MakeSureNotNil(tt.prepare)()
5251
ctx := getDefaultContext()
5352
opt := newDiskCardRunOption()
5453
opt.requestTimeout = 30 * time.Second
@@ -75,10 +74,9 @@ func TestRunCommand(t *testing.T) {
7574
},
7675
hasErr: true,
7776
}, {
78-
name: "file not found",
79-
args: []string{"--pattern", "fake"},
80-
prepare: func() {},
81-
hasErr: false,
77+
name: "file not found",
78+
args: []string{"--pattern", "fake"},
79+
hasErr: false,
8280
}, {
8381
name: "normal case",
8482
args: []string{"-p", simpleSuite},
@@ -90,8 +88,7 @@ func TestRunCommand(t *testing.T) {
9088
for _, tt := range tests {
9189
t.Run(tt.name, func(t *testing.T) {
9290
defer gock.Clean()
93-
tt.prepare()
94-
91+
util.MakeSureNotNil(tt.prepare)()
9592
root := &cobra.Command{Use: "root"}
9693
root.AddCommand(createRunCommand())
9794

cmd/server.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,5 @@ func (s *fakeGRPCServer) Serve(net.Listener) error {
7171

7272
// RegisterService is a fake method
7373
func (s *fakeGRPCServer) RegisterService(desc *grpc.ServiceDesc, impl interface{}) {
74+
// Do nothing due to this is a fake method
7475
}

cmd/service_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func TestService(t *testing.T) {
1616
assert.NotNil(t, err)
1717

1818
notLinux := NewRootCmd(fakeruntime.FakeExecer{ExpectOS: "fake"}, NewFakeGRPCServer())
19-
notLinux.SetArgs([]string{"service", "--action", "install"})
19+
notLinux.SetArgs([]string{"service", paramAction, "install"})
2020
err = notLinux.Execute()
2121
assert.NotNil(t, err)
2222

@@ -27,7 +27,7 @@ func TestService(t *testing.T) {
2727
}()
2828

2929
targetScript := NewRootCmd(fakeruntime.FakeExecer{ExpectOS: "linux"}, NewFakeGRPCServer())
30-
targetScript.SetArgs([]string{"service", "--action", "install", "--script-path", tmpFile.Name()})
30+
targetScript.SetArgs([]string{"service", paramAction, "install", "--script-path", tmpFile.Name()})
3131
err = targetScript.Execute()
3232
assert.Nil(t, err)
3333
data, err := os.ReadFile(tmpFile.Name())
@@ -67,3 +67,5 @@ func TestService(t *testing.T) {
6767
})
6868
}
6969
}
70+
71+
const paramAction = "--action"

pkg/runner/kubernetes/client_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func TestGetPod(t *testing.T) {
2727
name: "fake",
2828
},
2929
prepare: func() {
30-
gock.New("http://foo").
30+
gock.New(urlFoo).
3131
Get("/api/v1/namespaces/ns/pods/fake").
3232
Reply(http.StatusOK).
3333
JSON(`{"kind":"pod"}`)
@@ -46,7 +46,7 @@ func TestGetPod(t *testing.T) {
4646
name: "fake",
4747
},
4848
prepare: func() {
49-
gock.New("http://foo").
49+
gock.New(urlFoo).
5050
Get("/apis/apps/v1/namespaces/ns/deployments/fake").
5151
Reply(http.StatusOK).
5252
JSON(`{"kind":"deployment"}`)
@@ -60,7 +60,7 @@ func TestGetPod(t *testing.T) {
6060
t.Run(tt.name, func(t *testing.T) {
6161
defer gock.Clean()
6262
tt.prepare()
63-
reader := kubernetes.NewDefaultReader("http://foo", "")
63+
reader := kubernetes.NewDefaultReader(urlFoo, "")
6464
result, err := reader.GetResource(tt.group, tt.kind, tt.version, tt.namespacedName.namespace, tt.namespacedName.name)
6565
assert.Equal(t, tt.expect, result)
6666
assert.Nil(t, err)

pkg/runner/kubernetes/verify_test.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"github.com/antonmedv/expr"
99
"github.com/h2non/gock"
1010
"github.com/linuxsuren/api-testing/pkg/runner/kubernetes"
11+
"github.com/linuxsuren/api-testing/pkg/util"
1112
"github.com/stretchr/testify/assert"
1213
)
1314

@@ -47,7 +48,6 @@ func TestKubernetesValidatorFunc(t *testing.T) {
4748
}, {
4849
name: "no enough params",
4950
expression: `k8s('crd')`,
50-
prepare: emptyPrepare,
5151
expectBool: false,
5252
expectErr: true,
5353
}, {
@@ -73,11 +73,11 @@ func TestKubernetesValidatorFunc(t *testing.T) {
7373
}, {
7474
name: "no kind",
7575
expression: `k8s({"foo": "bar"}, "ns", "foo").Exist()`,
76-
prepare: emptyPrepare,
7776
expectErr: true,
7877
}}
7978
for _, tt := range tests {
8079
t.Run(tt.name, func(t *testing.T) {
80+
tt.prepare = util.MakeSureNotNil(tt.prepare)
8181
tt.prepare()
8282
vm, err := expr.Compile(tt.expression, kubernetes.KubernetesValidatorFunc(),
8383
kubernetes.PodValidatorFunc())
@@ -92,10 +92,6 @@ func TestKubernetesValidatorFunc(t *testing.T) {
9292
}
9393
}
9494

95-
func emptyPrepare() {
96-
// only for testing
97-
}
98-
9995
func preparePod() {
10096
gock.New(urlFoo).
10197
Get("/api/v1/namespaces/ns/pods/foo").

pkg/runner/simple.go

Lines changed: 2 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
11
package runner
22

33
import (
4-
"bytes"
54
"context"
65
"crypto/tls"
76
"encoding/json"
87
"fmt"
98
"io"
10-
"mime/multipart"
119
"net/http"
12-
"net/url"
13-
"os"
1410
"reflect"
1511
"strings"
1612
"time"
@@ -202,40 +198,14 @@ func (r *simpleTestCaseRunner) RunTestCase(testcase *testing.TestCase, dataConte
202198
}
203199

204200
var requestBody io.Reader
205-
if testcase.Request.Body != "" {
206-
requestBody = bytes.NewBufferString(testcase.Request.Body)
207-
} else if testcase.Request.BodyFromFile != "" {
208-
var data []byte
209-
if data, err = os.ReadFile(testcase.Request.BodyFromFile); err != nil {
210-
return
211-
}
212-
requestBody = bytes.NewBufferString(string(data))
201+
if requestBody, err = testcase.Request.GetBody(); err != nil {
202+
return
213203
}
214204

215205
if err = testcase.Request.Render(dataContext); err != nil {
216206
return
217207
}
218208

219-
if len(testcase.Request.Form) > 0 {
220-
if testcase.Request.Header[contentType] == "multipart/form-data" {
221-
multiBody := &bytes.Buffer{}
222-
writer := multipart.NewWriter(multiBody)
223-
for key, val := range testcase.Request.Form {
224-
writer.WriteField(key, val)
225-
}
226-
227-
_ = writer.Close()
228-
requestBody = multiBody
229-
testcase.Request.Header[contentType] = writer.FormDataContentType()
230-
} else if testcase.Request.Header[contentType] == "application/x-www-form-urlencoded" {
231-
data := url.Values{}
232-
for key, val := range testcase.Request.Form {
233-
data.Set(key, val)
234-
}
235-
requestBody = strings.NewReader(data.Encode())
236-
}
237-
}
238-
239209
var request *http.Request
240210
if request, err = http.NewRequestWithContext(ctx, testcase.Request.Method, testcase.Request.API, requestBody); err != nil {
241211
return
@@ -436,5 +406,3 @@ func jsonSchemaValidation(schema string, body []byte) (err error) {
436406
}
437407
return
438408
}
439-
440-
const contentType = "Content-Type"

pkg/runner/simple_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212

1313
"github.com/h2non/gock"
1414
atest "github.com/linuxsuren/api-testing/pkg/testing"
15+
"github.com/linuxsuren/api-testing/pkg/util"
1516
fakeruntime "github.com/linuxsuren/go-fake-runtime"
1617
"github.com/stretchr/testify/assert"
1718
)
@@ -300,7 +301,7 @@ func TestTestCase(t *testing.T) {
300301
API: urlFoo,
301302
Method: http.MethodPost,
302303
Header: map[string]string{
303-
contentType: "multipart/form-data",
304+
util.ContentType: "multipart/form-data",
304305
},
305306
Form: map[string]string{
306307
"key": "value",
@@ -319,7 +320,7 @@ func TestTestCase(t *testing.T) {
319320
API: urlFoo,
320321
Method: http.MethodPost,
321322
Header: map[string]string{
322-
contentType: "application/x-www-form-urlencoded",
323+
util.ContentType: "application/x-www-form-urlencoded",
323324
},
324325
Form: map[string]string{
325326
"key": "value",

pkg/server/remote_server_test.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,30 @@ func TestRemoteServer(t *testing.T) {
1919
})
2020
assert.NotNil(t, err)
2121

22-
gock.New("http://foo").Get("/").Reply(http.StatusOK).JSON(&server)
23-
gock.New("http://foo").Get("/").Reply(http.StatusOK).JSON(&server)
22+
gock.New(urlFoo).Get("/").Reply(http.StatusOK).JSON(&server)
23+
gock.New(urlFoo).Get("/").Reply(http.StatusOK).JSON(&server)
2424
_, err = server.Run(context.TODO(), &TestTask{
2525
Kind: "suite",
2626
Data: simpleSuite,
2727
})
2828
assert.Nil(t, err)
2929

30-
gock.New("http://bar").Get("/").Reply(http.StatusOK).JSON(&server)
30+
gock.New(urlFoo).Get("/").Reply(http.StatusOK).JSON(&server)
3131
_, err = server.Run(context.TODO(), &TestTask{
3232
Kind: "testcase",
3333
Data: simpleTestCase,
3434
})
3535
assert.Nil(t, err)
3636

37-
gock.New("http://foo").Get("/").Reply(http.StatusOK).JSON(&server)
37+
gock.New(urlFoo).Get("/").Reply(http.StatusOK).JSON(&server)
3838
_, err = server.Run(context.TODO(), &TestTask{
3939
Kind: "testcaseInSuite",
4040
Data: simpleSuite,
4141
CaseName: "get",
4242
})
4343
assert.Nil(t, err)
4444

45-
gock.New("http://foo").Get("/").Reply(http.StatusOK).JSON(&server)
45+
gock.New(urlFoo).Get("/").Reply(http.StatusOK).JSON(&server)
4646
_, err = server.Run(context.TODO(), &TestTask{
4747
Kind: "testcaseInSuite",
4848
Data: simpleSuite,
@@ -171,3 +171,5 @@ var simpleSuite string
171171

172172
//go:embed testdata/simple_testcase.yaml
173173
var simpleTestCase string
174+
175+
const urlFoo = "http://foo"

pkg/testing/parser.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package testing
22

33
import (
4+
"bytes"
45
"fmt"
6+
"io"
7+
"mime/multipart"
58
"net/http"
9+
"net/url"
610
"os"
711
"strings"
812

913
"github.com/linuxsuren/api-testing/pkg/render"
14+
"github.com/linuxsuren/api-testing/pkg/util"
1015
"gopkg.in/yaml.v2"
1116
)
1217

@@ -83,6 +88,37 @@ func (r *Request) Render(ctx interface{}) (err error) {
8388
return
8489
}
8590

91+
// GetBody returns the request body
92+
func (r *Request) GetBody() (reader io.Reader, err error) {
93+
if len(r.Form) > 0 {
94+
if r.Header[util.ContentType] == util.MultiPartFormData {
95+
multiBody := &bytes.Buffer{}
96+
writer := multipart.NewWriter(multiBody)
97+
for key, val := range r.Form {
98+
writer.WriteField(key, val)
99+
}
100+
101+
_ = writer.Close()
102+
reader = multiBody
103+
r.Header[util.ContentType] = writer.FormDataContentType()
104+
} else if r.Header[util.ContentType] == util.Form {
105+
data := url.Values{}
106+
for key, val := range r.Form {
107+
data.Set(key, val)
108+
}
109+
reader = strings.NewReader(data.Encode())
110+
}
111+
} else if r.Body != "" {
112+
reader = bytes.NewBufferString(r.Body)
113+
} else if r.BodyFromFile != "" {
114+
var data []byte
115+
if data, err = os.ReadFile(r.BodyFromFile); err == nil {
116+
reader = bytes.NewBufferString(string(data))
117+
}
118+
}
119+
return
120+
}
121+
86122
// Render renders the response
87123
func (r *Response) Render(ctx interface{}) (err error) {
88124
r.StatusCode = zeroThenDefault(r.StatusCode, http.StatusOK)

0 commit comments

Comments
 (0)