Skip to content

Commit

Permalink
feat: support generate code from TestCase (#154)
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen authored Aug 1, 2023
1 parent 556d58f commit a799208
Show file tree
Hide file tree
Showing 12 changed files with 988 additions and 139 deletions.
26 changes: 26 additions & 0 deletions console/atest-ui/src/views/TestCase.vue
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,31 @@ function sendRequest() {
})
}
function generateCode() {
const name = props.name
const suite = props.suite
const requestOptions = {
method: 'POST',
body: JSON.stringify({
TestSuite: suite,
TestCase: name,
Generator: "golang"
})
}
fetch('/server.Runner/GenerateCode', requestOptions)
.then((response) => response.json())
.then((e) => {
ElMessage({
message: 'Code generated!',
type: 'success'
})
testResult.value.output = e.message
})
.catch((e) => {
ElMessage.error('Oops, ' + e)
})
}
const queryBodyFields = (queryString: string, cb: any) => {
if (!testResult.value.bodyObject || !FlattenObject(testResult.value.bodyObject)) {
cb([])
Expand Down Expand Up @@ -408,6 +433,7 @@ const queryPupularHeaders = (queryString: string, cb: (arg: any) => void) => {
</el-autocomplete>

<el-button type="primary" @click="sendRequest" :loading="requestLoading">Send</el-button>
<el-button type="primary" @click="generateCode">Generator Code</el-button>
</el-header>

<el-main>
Expand Down
51 changes: 51 additions & 0 deletions pkg/generator/code_generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
MIT License
Copyright (c) 2023 API Testing Authors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package generator

import "github.com/linuxsuren/api-testing/pkg/testing"

// CodeGenerator is the interface of code generator
type CodeGenerator interface {
Generate(testcase *testing.TestCase) (result string, err error)
}

var codeGenerators = map[string]CodeGenerator{}

func GetCodeGenerator(name string) CodeGenerator {
return codeGenerators[name]
}

func RegisterCodeGenerator(name string, generator CodeGenerator) {
codeGenerators[name] = generator
}

func GetCodeGenerators() (result map[string]CodeGenerator) {
// returns an immutable map
result = make(map[string]CodeGenerator, len(codeGenerators))
for k, v := range codeGenerators {
result[k] = v
}
return
}
68 changes: 68 additions & 0 deletions pkg/generator/code_generator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
MIT License
Copyright (c) 2023 API Testing Authors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package generator_test

import (
"testing"

_ "embed"

"github.com/linuxsuren/api-testing/pkg/generator"
atest "github.com/linuxsuren/api-testing/pkg/testing"
"github.com/stretchr/testify/assert"
)

func TestCodeGeneratorManager(t *testing.T) {
t.Run("GetCodeGenerators", func(t *testing.T) {
// should returns a mutable map
generators := generator.GetCodeGenerators()
count := len(generators)

generators["a-new-fake"] = nil
assert.Equal(t, count, len(generator.GetCodeGenerators()))
})

t.Run("GetCodeGenerator", func(t *testing.T) {
instance := generator.NewGolangGenerator()
generator.RegisterCodeGenerator("fake", instance)
assert.Equal(t, instance, generator.GetCodeGenerator("fake"))
})
}

func TestGenerators(t *testing.T) {
testcase := &atest.TestCase{
Request: atest.Request{
API: "https://www.baidu.com",
},
}
t.Run("golang", func(t *testing.T) {
result, err := generator.GetCodeGenerator("golang").Generate(testcase)
assert.NoError(t, err)
assert.Equal(t, expectedGoCode, result)
})
}

//go:embed testdata/expected_go_code.txt
var expectedGoCode string
39 changes: 39 additions & 0 deletions pkg/generator/data/main.go.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

import (
"io"
"net/http"
)

func main() {
{{- if lt (len .Request.Form) 0 }}
data := url.Values{}
{{- range $key, $val := .Request.Form}}
data.Set("$key", "$val")
{{end}}
reader := strings.NewReader(data.Encode())
{{- else}}
body := bytes.NewBufferString("{{.Request.Body}}")
{{- end }}

req, err := http.NewRequest("{{.Request.Method}}," "{{.Request.API}}", body)
if err != nil {
panic(err)
}

{{- range $key, $val := .Request.Header}}
req.Header.Set("$key", "$val")
{{end}}

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}

if resp.StatusCode != http.StatusOK {
panic("status code is not 200")
}

data, err := io.ReadAll(resp.Body)
println(string(data))
}
63 changes: 63 additions & 0 deletions pkg/generator/golang_generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
MIT License
Copyright (c) 2023 API Testing Authors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package generator

import (
"bytes"
"html/template"
"net/http"

_ "embed"

"github.com/linuxsuren/api-testing/pkg/testing"
)

type golangGenerator struct {
}

func NewGolangGenerator() CodeGenerator {
return &golangGenerator{}
}

func (g *golangGenerator) Generate(testcase *testing.TestCase) (result string, err error) {
if testcase.Request.Method == "" {
testcase.Request.Method = http.MethodGet
}
var tpl *template.Template
if tpl, err = template.New("golang template").Parse(golangTemplate); err == nil {
buf := new(bytes.Buffer)
if err = tpl.Execute(buf, testcase); err == nil {
result = buf.String()
}
}
return
}

func init() {
RegisterCodeGenerator("golang", NewGolangGenerator())
}

//go:embed data/main.go.tpl
var golangTemplate string
27 changes: 27 additions & 0 deletions pkg/generator/testdata/expected_go_code.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"io"
"net/http"
)

func main() {
body := bytes.NewBufferString("")

req, err := http.NewRequest("GET," "https://www.baidu.com", body)
if err != nil {
panic(err)
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}

if resp.StatusCode != http.StatusOK {
panic("status code is not 200")
}

data, err := io.ReadAll(resp.Body)
println(string(data))
}
39 changes: 39 additions & 0 deletions pkg/server/remote_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
_ "embed"

"github.com/linuxsuren/api-testing/pkg/apispec"
"github.com/linuxsuren/api-testing/pkg/generator"
"github.com/linuxsuren/api-testing/pkg/render"
"github.com/linuxsuren/api-testing/pkg/runner"
"github.com/linuxsuren/api-testing/pkg/testing"
Expand Down Expand Up @@ -462,6 +463,43 @@ func (s *server) DeleteTestCase(ctx context.Context, in *TestCaseIdentity) (repl
return
}

// code generator
func (s *server) ListCodeGenerator(ctx context.Context, in *Empty) (reply *SimpleList, err error) {
reply = &SimpleList{}

generators := generator.GetCodeGenerators()
for name := range generators {
reply.Data = append(reply.Data, &Pair{
Key: name,
})
}
return
}

func (s *server) GenerateCode(ctx context.Context, in *CodeGenerateRequest) (reply *CommonResult, err error) {
reply = &CommonResult{}

instance := generator.GetCodeGenerator(in.Generator)
if instance == nil {
reply.Success = false
reply.Message = fmt.Sprintf("generator '%s' not found", in.Generator)
} else {
var result testing.TestCase
loader := s.getLoader(ctx)
if result, err = loader.GetTestCase(in.TestSuite, in.TestCase); err == nil {
output, genErr := instance.Generate(&result)
if genErr != nil {
reply.Success = false
reply.Message = genErr.Error()
} else {
reply.Success = true
reply.Message = output
}
}
}
return
}

// Sample returns a sample of the test task
func (s *server) Sample(ctx context.Context, in *Empty) (reply *HelloReply, err error) {
reply = &HelloReply{Message: sample.TestSuiteGitLab}
Expand Down Expand Up @@ -529,6 +567,7 @@ func (s *server) FunctionsQuery(ctx context.Context, in *SimpleQuery) (reply *Pa
}
return
}

// FunctionsQueryStream works like FunctionsQuery but is implemented in bidirectional streaming
func (s *server) FunctionsQueryStream(srv Runner_FunctionsQueryStreamServer) error {
ctx := srv.Context()
Expand Down
Loading

0 comments on commit a799208

Please sign in to comment.