Skip to content

Commit e997437

Browse files
authored
feat: support to generator Python code from a HTTP testCase
1 parent 02dd80f commit e997437

File tree

7 files changed

+246
-3
lines changed

7 files changed

+246
-3
lines changed

pkg/generator/code_generator_test.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Copyright 2023 API Testing Authors.
2+
Copyright 2024 API Testing Authors.
33
44
Licensed under the Apache License, Version 2.0 (the "License");
55
you may not use this file except in compliance with the License.
@@ -63,6 +63,12 @@ func TestGenerators(t *testing.T) {
6363
assert.Equal(t, expectedJavaCode, result)
6464
})
6565

66+
t.Run("python", func(t *testing.T) {
67+
result, err := generator.GetCodeGenerator("python").Generate(nil, testcase)
68+
assert.NoError(t, err)
69+
assert.Equal(t, expectedPythonCode, result)
70+
})
71+
6672
formRequest := &atest.TestCase{Request: testcase.Request}
6773
formRequest.Request.Form = map[string]string{
6874
"key": "value",
@@ -79,6 +85,12 @@ func TestGenerators(t *testing.T) {
7985
assert.Equal(t, expectedFormRequestJavaCode, result, result)
8086
})
8187

88+
t.Run("python form HTTP request", func(t *testing.T) {
89+
result, err := generator.GetCodeGenerator("python").Generate(nil, formRequest)
90+
assert.NoError(t, err)
91+
assert.Equal(t, expectedFormRequestPythonCode, result, result)
92+
})
93+
8294
cookieRequest := &atest.TestCase{Request: formRequest.Request}
8395
cookieRequest.Request.Cookie = map[string]string{
8496
"name": "value",
@@ -95,6 +107,12 @@ func TestGenerators(t *testing.T) {
95107
assert.Equal(t, expectedCookieRequestJavaCode, result, result)
96108
})
97109

110+
t.Run("python cookie HTTP request", func(t *testing.T) {
111+
result, err := generator.GetCodeGenerator("python").Generate(nil, cookieRequest)
112+
assert.NoError(t, err)
113+
assert.Equal(t, expectedCookieRequestPythonCode, result, result)
114+
})
115+
98116
bodyRequest := &atest.TestCase{Request: testcase.Request}
99117
bodyRequest.Request.Body.Value = `{"key": "value"}`
100118

@@ -123,5 +141,14 @@ var expectedCookieRequestGoCode string
123141
//go:embed testdata/expected_java_cookie_request_code.txt
124142
var expectedCookieRequestJavaCode string
125143

144+
//go:embed testdata/expected_python_code.txt
145+
var expectedPythonCode string
146+
147+
//go:embed testdata/expected_python_form_request_code.txt
148+
var expectedFormRequestPythonCode string
149+
150+
//go:embed testdata/expected_python_cookie_request_code.txt
151+
var expectedCookieRequestPythonCode string
152+
126153
//go:embed testdata/expected_go_body_request_code.txt
127154
var expectedBodyRequestGoCode string

pkg/generator/data/main.python.tpl

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Copyright 2024 API Testing Authors.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
import io
14+
import requests
15+
from urllib.parse import urlencode
16+
17+
def main():
18+
{{- if gt (len .Request.Form) 0 }}
19+
data = {}
20+
{{- range $key, $val := .Request.Form}}
21+
data["{{$key}}"] = "{{$val}}"
22+
encoded_data = urlencode(data)
23+
{{- end}}
24+
body = io.BytesIO(encoded_data.encode("utf-8"))
25+
{{- else}}
26+
body = io.BytesIO(b"{{.Request.Body.String}}")
27+
{{- end}}
28+
{{- range $key, $val := .Request.Header}}
29+
headers = {"{{$key}}": "{{$val}}"}
30+
{{- end}}
31+
{{- if gt (len .Request.Cookie) 0 }}
32+
{{- range $key, $val := .Request.Cookie}}
33+
cookies = {"{{$key}}": "{{$val}}"}
34+
{{- end}}
35+
{{- end}}
36+
{{- if gt (len .Request.Cookie) 0 }}
37+
try:
38+
req = requests.Request("{{.Request.Method}}", "{{.Request.API}}", headers=headers, cookies=cookies, data=body)
39+
except requests.RequestException as e:
40+
raise e
41+
{{- else}}
42+
try:
43+
req = requests.Request("{{.Request.Method}}", "{{.Request.API}}", headers=headers, data=body)
44+
except requests.RequestException as e:
45+
raise e
46+
{{- end}}
47+
48+
resp = requests.Session().send(req.prepare())
49+
if resp.status_code != 200:
50+
raise Exception("status code is not 200")
51+
52+
data = resp.content
53+
print(data.decode("utf-8"))
54+
55+
if __name__ == "__main__":
56+
main()

pkg/generator/python_generator.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Copyright 2024 API Testing Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package generator
17+
18+
import (
19+
"bytes"
20+
"html/template"
21+
"net/http"
22+
23+
_ "embed"
24+
25+
"github.com/linuxsuren/api-testing/pkg/testing"
26+
)
27+
28+
type pythonGenerator struct {
29+
}
30+
31+
func NewPythonGenerator() CodeGenerator {
32+
return &pythonGenerator{}
33+
}
34+
35+
func (g *pythonGenerator) Generate(testSuite *testing.TestSuite, testcase *testing.TestCase) (result string, err error) {
36+
if testcase.Request.Method == "" {
37+
testcase.Request.Method = http.MethodGet
38+
}
39+
var tpl *template.Template
40+
if tpl, err = template.New("python template").Parse(pythonTemplate); err == nil {
41+
buf := new(bytes.Buffer)
42+
if err = tpl.Execute(buf, testcase); err == nil {
43+
result = buf.String()
44+
}
45+
}
46+
return
47+
}
48+
49+
func init() {
50+
RegisterCodeGenerator("python", NewPythonGenerator())
51+
}
52+
53+
//go:embed data/main.python.tpl
54+
var pythonTemplate string
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Copyright 2024 API Testing Authors.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
import io
14+
import requests
15+
from urllib.parse import urlencode
16+
17+
def main():
18+
body = io.BytesIO(b"")
19+
headers = {"User-Agent": "atest"}
20+
try:
21+
req = requests.Request("GET", "https://www.baidu.com", headers=headers, data=body)
22+
except requests.RequestException as e:
23+
raise e
24+
25+
resp = requests.Session().send(req.prepare())
26+
if resp.status_code != 200:
27+
raise Exception("status code is not 200")
28+
29+
data = resp.content
30+
print(data.decode("utf-8"))
31+
32+
if __name__ == "__main__":
33+
main()
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Copyright 2024 API Testing Authors.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
import io
14+
import requests
15+
from urllib.parse import urlencode
16+
17+
def main():
18+
data = {}
19+
data["key"] = "value"
20+
encoded_data = urlencode(data)
21+
body = io.BytesIO(encoded_data.encode("utf-8"))
22+
headers = {"User-Agent": "atest"}
23+
cookies = {"name": "value"}
24+
try:
25+
req = requests.Request("GET", "https://www.baidu.com", headers=headers, cookies=cookies, data=body)
26+
except requests.RequestException as e:
27+
raise e
28+
29+
resp = requests.Session().send(req.prepare())
30+
if resp.status_code != 200:
31+
raise Exception("status code is not 200")
32+
33+
data = resp.content
34+
print(data.decode("utf-8"))
35+
36+
if __name__ == "__main__":
37+
main()
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Copyright 2024 API Testing Authors.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
import io
14+
import requests
15+
from urllib.parse import urlencode
16+
17+
def main():
18+
data = {}
19+
data["key"] = "value"
20+
encoded_data = urlencode(data)
21+
body = io.BytesIO(encoded_data.encode("utf-8"))
22+
headers = {"User-Agent": "atest"}
23+
try:
24+
req = requests.Request("GET", "https://www.baidu.com", headers=headers, data=body)
25+
except requests.RequestException as e:
26+
raise e
27+
28+
resp = requests.Session().send(req.prepare())
29+
if resp.status_code != 200:
30+
raise Exception("status code is not 200")
31+
32+
data = resp.content
33+
print(data.decode("utf-8"))
34+
35+
if __name__ == "__main__":
36+
main()

pkg/server/remote_server_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Copyright 2023 API Testing Authors.
2+
Copyright 2024 API Testing Authors.
33
44
Licensed under the Apache License, Version 2.0 (the "License");
55
you may not use this file except in compliance with the License.
@@ -593,7 +593,7 @@ func TestCodeGenerator(t *testing.T) {
593593
t.Run("ListCodeGenerator", func(t *testing.T) {
594594
generators, err := server.ListCodeGenerator(ctx, &Empty{})
595595
assert.NoError(t, err)
596-
assert.Equal(t, 4, len(generators.Data))
596+
assert.Equal(t, 5, len(generators.Data))
597597
})
598598

599599
t.Run("GenerateCode, no generator found", func(t *testing.T) {

0 commit comments

Comments
 (0)