Skip to content

Commit

Permalink
fix: the code smells from sonarqube (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen authored Apr 18, 2023
1 parent f6d271b commit 6aed29e
Show file tree
Hide file tree
Showing 12 changed files with 149 additions and 137 deletions.
5 changes: 5 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"linuxsuren.api-testing"
]
}
14 changes: 12 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
FROM golang:1.18 as builder
FROM golang:1.18 AS builder

WORKDIR /workspace
COPY . .
COPY cmd/ cmd/
COPY pkg/ pkg/
COPY sample/ sample/
COPY go.mod go.mod
COPY go.sum go.sum
COPY main.go main.go
COPY README.md README.md
COPY LICENSE LICENSE

RUN go mod download
RUN CGO_ENABLE=0 go build -ldflags "-w -s" -o atest .

Expand All @@ -19,5 +27,7 @@ LABEL "maintainer"="Rick <linuxsuren@gmail.com>"
LABEL "Name"="API testing"

COPY --from=builder /workspace/atest /usr/local/bin/atest
COPY --from=builder /workspace/LICENSE /LICENSE
COPY --from=builder /workspace/README.md /README.md

CMD ["atest", "server"]
2 changes: 1 addition & 1 deletion cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
exec "github.com/linuxsuren/go-fake-runtime"
)

func Test_setRelativeDir(t *testing.T) {
func TestSetRelativeDir(t *testing.T) {
type args struct {
configFile string
testcase *atesting.TestCase
Expand Down
19 changes: 11 additions & 8 deletions cmd/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,19 @@ func TestRunSuite(t *testing.T) {
hasError bool
}{{
name: "simple",
suiteFile: "testdata/simple-suite.yaml",
suiteFile: simpleSuite,
prepare: func() {
gock.New("http://foo").
gock.New(urlFoo).
Get("/bar").
Reply(http.StatusOK).
JSON("{}")
},
hasError: false,
}, {
name: "response is not JSON",
suiteFile: "testdata/simple-suite.yaml",
suiteFile: simpleSuite,
prepare: func() {
gock.New("http://foo").
gock.New(urlFoo).
Get("/bar").
Reply(http.StatusOK)
},
Expand Down Expand Up @@ -69,9 +69,9 @@ func TestRunCommand(t *testing.T) {
hasErr bool
}{{
name: "status code is not match",
args: []string{"-p", "testdata/simple-suite.yaml"},
args: []string{"-p", simpleSuite},
prepare: func() {
gock.New("http://foo").Get("/bar")
gock.New(urlFoo).Get("/bar")
},
hasErr: true,
}, {
Expand All @@ -81,9 +81,9 @@ func TestRunCommand(t *testing.T) {
hasErr: false,
}, {
name: "normal case",
args: []string{"-p", "testdata/simple-suite.yaml"},
args: []string{"-p", simpleSuite},
prepare: func() {
gock.New("http://foo").Get("/bar").Reply(http.StatusOK).JSON("{}")
gock.New(urlFoo).Get("/bar").Reply(http.StatusOK).JSON("{}")
},
hasErr: false,
}}
Expand Down Expand Up @@ -177,3 +177,6 @@ func TestPreRunE(t *testing.T) {
})
}
}

const urlFoo = "http://foo"
const simpleSuite = "testdata/simple-suite.yaml"
29 changes: 17 additions & 12 deletions pkg/runner/kubernetes/verify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

func TestKubernetesValidatorFunc(t *testing.T) {
os.Setenv("KUBERNETES_SERVER", "http://foo")
os.Setenv("KUBERNETES_SERVER", urlFoo)
os.Setenv("KUBERNETES_TOKEN", "token")
gock.InterceptClient(kubernetes.GetClient())
defer gock.RestoreClient(http.DefaultClient)
Expand Down Expand Up @@ -92,44 +92,49 @@ func TestKubernetesValidatorFunc(t *testing.T) {
}
}

func emptyPrepare() {}
func emptyPrepare() {
// only for testing
}

func preparePod() {
gock.New("http://foo").
gock.New(urlFoo).
Get("/api/v1/namespaces/ns/pods/foo").
MatchHeader("Authorization", "Bearer token").
MatchHeader("Authorization", defaultToken).
Reply(http.StatusOK).
JSON(`{"kind":"pod"}`)
}

func prepareDeploy() {
gock.New("http://foo").
gock.New(urlFoo).
Get("/apis/apps/v1/namespaces/ns/deployments/foo").
MatchHeader("Authorization", "Bearer token").
MatchHeader("Authorization", defaultToken).
Reply(http.StatusOK).
JSON(`{"kind":"deploy"}`)
}

func prepareStatefulset() {
gock.New("http://foo").
gock.New(urlFoo).
Get("/apis/apps/v1/namespaces/ns/statefulsets/foo").
MatchHeader("Authorization", "Bearer token").
MatchHeader("Authorization", defaultToken).
Reply(http.StatusOK).
JSON(`{"kind":"statefulset"}`)
}

func prepareDaemonset() {
gock.New("http://foo").
gock.New(urlFoo).
Get("/apis/apps/v1/namespaces/ns/daemonsets/foo").
MatchHeader("Authorization", "Bearer token").
MatchHeader("Authorization", defaultToken).
Reply(http.StatusOK).
JSON(`{"kind":"daemonset"}`)
}

func prepareCRDVM() {
gock.New("http://foo").
gock.New(urlFoo).
Get("/apis/bar/v2/namespaces/ns/vms/foo").
MatchHeader("Authorization", "Bearer token").
MatchHeader("Authorization", defaultToken).
Reply(http.StatusOK).
JSON(`{"kind":"vm"}`)
}

const urlFoo = "http://foo"
const defaultToken = "Bearer token"
4 changes: 3 additions & 1 deletion pkg/runner/reporter_discard.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ func NewDiscardTestReporter() TestReporter {
}

// PutRecord does nothing
func (r *discardTestReporter) PutRecord(*ReportRecord) {}
func (r *discardTestReporter) PutRecord(*ReportRecord) {
// Do nothing which is the design purpose
}

// GetAllRecords does nothing
func (r *discardTestReporter) GetAllRecords() []*ReportRecord {
Expand Down
19 changes: 12 additions & 7 deletions pkg/runner/reporter_memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ func (r *memoryTestReporter) GetAllRecords() []*ReportRecord {
return r.records
}

func getMaxAndMin(max, min, duration time.Duration) (time.Duration, time.Duration) {
if max < duration {
max = duration
}

if min > duration {
min = duration
}
return max, min
}

// ExportAllReportResults exports all the report results
func (r *memoryTestReporter) ExportAllReportResults() (result ReportResultSlice, err error) {
resultWithTotal := map[string]*ReportResultWithTotal{}
Expand All @@ -42,13 +53,7 @@ func (r *memoryTestReporter) ExportAllReportResults() (result ReportResultSlice,
duration := record.Duration()

if item, ok := resultWithTotal[api]; ok {
if item.Max < duration {
item.Max = duration
}

if item.Min > duration {
item.Min = duration
}
item.Max, item.Min = getMaxAndMin(item.Max, item.Min, duration)
item.Error += record.ErrorCount()
item.Total += duration
item.Count += 1
Expand Down
14 changes: 9 additions & 5 deletions pkg/runner/reporter_memory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import (
"github.com/stretchr/testify/assert"
)

const urlFoo = "http://foo"
const urlBar = "http://bar"
const urlFake = "http://fake"

func TestExportAllReportResults(t *testing.T) {
now := time.Now()

Expand All @@ -24,28 +28,28 @@ func TestExportAllReportResults(t *testing.T) {
}, {
name: "normal",
records: []*runner.ReportRecord{{
API: "http://foo",
API: urlFoo,
Method: http.MethodGet,
BeginTime: now,
EndTime: now.Add(time.Second * 3),
}, {
API: "http://foo",
API: urlFoo,
Method: http.MethodGet,
BeginTime: now,
EndTime: now.Add(time.Second * 4),
Error: errors.New("fake"),
}, {
API: "http://foo",
API: urlFoo,
Method: http.MethodGet,
BeginTime: now,
EndTime: now.Add(time.Second * 2),
}, {
API: "http://bar",
API: urlBar,
Method: http.MethodGet,
BeginTime: now,
EndTime: now.Add(time.Second),
}, {
API: "http://fake",
API: urlFake,
Method: http.MethodGet,
BeginTime: now,
EndTime: now.Add(time.Second * 5),
Expand Down
8 changes: 5 additions & 3 deletions pkg/runner/simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ func (r *simpleTestCaseRunner) RunTestCase(testcase *testing.TestCase, dataConte
}

if len(testcase.Request.Form) > 0 {
if testcase.Request.Header["Content-Type"] == "multipart/form-data" {
if testcase.Request.Header[contentType] == "multipart/form-data" {
multiBody := &bytes.Buffer{}
writer := multipart.NewWriter(multiBody)
for key, val := range testcase.Request.Form {
Expand All @@ -226,8 +226,8 @@ func (r *simpleTestCaseRunner) RunTestCase(testcase *testing.TestCase, dataConte

_ = writer.Close()
requestBody = multiBody
testcase.Request.Header["Content-Type"] = writer.FormDataContentType()
} else if testcase.Request.Header["Content-Type"] == "application/x-www-form-urlencoded" {
testcase.Request.Header[contentType] = writer.FormDataContentType()
} else if testcase.Request.Header[contentType] == "application/x-www-form-urlencoded" {
data := url.Values{}
for key, val := range testcase.Request.Form {
data.Set(key, val)
Expand Down Expand Up @@ -436,3 +436,5 @@ func jsonSchemaValidation(schema string, body []byte) (err error) {
}
return
}

const contentType = "Content-Type"
Loading

0 comments on commit 6aed29e

Please sign in to comment.