Skip to content

Commit 6f2fed9

Browse files
authored
feat: Support to generator JavaScript code from a HTTP testCase. (#400)
* feat: Support to generator JavaScript code from a HTTP testCase. * more friendly prompts in JavaScript code generator.
1 parent eb1973a commit 6f2fed9

10 files changed

+362
-5
lines changed

pkg/generator/code_generator_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,12 @@ func TestGenerators(t *testing.T) {
6969
assert.Equal(t, expectedPythonCode, result)
7070
})
7171

72+
t.Run("javascript", func(t *testing.T) {
73+
result, err := generator.GetCodeGenerator("JavaScript").Generate(nil, testcase)
74+
assert.NoError(t, err)
75+
assert.Equal(t, expectedJavaScriptCode, result)
76+
})
77+
7278
formRequest := &atest.TestCase{Request: testcase.Request}
7379
formRequest.Request.Form = map[string]string{
7480
"key": "value",
@@ -91,6 +97,12 @@ func TestGenerators(t *testing.T) {
9197
assert.Equal(t, expectedFormRequestPythonCode, result, result)
9298
})
9399

100+
t.Run("javascript form HTTP request", func(t *testing.T) {
101+
result, err := generator.GetCodeGenerator("JavaScript").Generate(nil, formRequest)
102+
assert.NoError(t, err)
103+
assert.Equal(t, expectedFormRequestJavaScriptCode, result)
104+
})
105+
94106
cookieRequest := &atest.TestCase{Request: formRequest.Request}
95107
cookieRequest.Request.Cookie = map[string]string{
96108
"name": "value",
@@ -113,6 +125,12 @@ func TestGenerators(t *testing.T) {
113125
assert.Equal(t, expectedCookieRequestPythonCode, result, result)
114126
})
115127

128+
t.Run("javascript cookie HTTP request", func(t *testing.T) {
129+
result, err := generator.GetCodeGenerator("JavaScript").Generate(nil, cookieRequest)
130+
assert.NoError(t, err)
131+
assert.Equal(t, expectedCookieRequestJavaScriptCode, result, result)
132+
})
133+
116134
bodyRequest := &atest.TestCase{Request: testcase.Request}
117135
bodyRequest.Request.Body.Value = `{"key": "value"}`
118136

@@ -121,6 +139,12 @@ func TestGenerators(t *testing.T) {
121139
assert.NoError(t, err)
122140
assert.Equal(t, expectedBodyRequestGoCode, result, result)
123141
})
142+
143+
t.Run("javascript body HTTP request", func(t *testing.T) {
144+
result, err := generator.GetCodeGenerator("JavaScript").Generate(nil, bodyRequest)
145+
assert.NoError(t, err)
146+
assert.Equal(t, expectedBodyRequestJavaScriptCode, result, result)
147+
})
124148
}
125149

126150
//go:embed testdata/expected_go_code.txt
@@ -152,3 +176,15 @@ var expectedCookieRequestPythonCode string
152176

153177
//go:embed testdata/expected_go_body_request_code.txt
154178
var expectedBodyRequestGoCode string
179+
180+
//go:embed testdata/expected_javascript_code.txt
181+
var expectedJavaScriptCode string
182+
183+
//go:embed testdata/expected_javascript_form_request_code.txt
184+
var expectedFormRequestJavaScriptCode string
185+
186+
//go:embed testdata/expected_javascript_cookie_request_code.txt
187+
var expectedCookieRequestJavaScriptCode string
188+
189+
//go:embed testdata/expected_javascript_body_request_code.txt
190+
var expectedBodyRequestJavaScriptCode string
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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+
14+
async function makeRequest() {
15+
{{- if gt (len .Request.Header) 0 }}
16+
const headers = new Headers();
17+
{{- range $key, $val := .Request.Header}}
18+
headers.append("{{$key}}", "{{$val}}");
19+
{{- end}}
20+
{{- end}}
21+
22+
{{- if gt (len .Request.Cookie) 0 }}
23+
const cookieHeader = [
24+
{{- range $key, $val := .Request.Cookie}}
25+
"{{$key}}={{$val}}",
26+
{{- end}}
27+
].join("; ");
28+
headers.append("Cookie", cookieHeader);
29+
{{- end}}
30+
31+
const requestOptions = {
32+
method: "{{.Request.Method}}",
33+
{{- if gt (len .Request.Header) 0 }}
34+
headers: headers,
35+
{{- end}}
36+
redirect: "follow"
37+
};
38+
39+
{{- if ne .Request.Body.String "" }}
40+
console.log('the body is ignored because this is a GET request')
41+
/*
42+
{{- else if gt (len .Request.Form) 0 }}
43+
console.log('the body is ignored because this is a GET request')
44+
/*
45+
{{- end}}
46+
{{- if gt (len .Request.Form) 0 }}
47+
const formData = new URLSearchParams();
48+
{{- range $key, $val := .Request.Form}}
49+
formData.append("{{$key}}", "{{$val}}");
50+
{{- end}}
51+
let body = formData;
52+
requestOptions.body = body;
53+
{{- else if ne .Request.Body.String ""}}
54+
let body = `{{.Request.Body.String | safeString}}`;
55+
requestOptions.body = body;
56+
{{- end}}
57+
{{- if ne .Request.Body.String "" }}
58+
*/
59+
{{- else if gt (len .Request.Form) 0 }}
60+
*/
61+
{{- end}}
62+
63+
try {
64+
const response = await fetch("{{.Request.API}}", requestOptions);
65+
if (response.ok) { // Check if HTTP status code is 200/OK
66+
const text = await response.text();
67+
console.log(text);
68+
} else {
69+
throw new Error('Network response was not ok. Status code: ' + response.status);
70+
}
71+
} catch (error) {
72+
console.error('Fetch error:', error);
73+
}
74+
}
75+
76+
makeRequest();

pkg/generator/golang_generator.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,6 @@ func (g *golangGenerator) Generate(testSuite *testing.TestSuite, testcase *testi
4646
return
4747
}
4848

49-
func safeString(str string) template.HTML {
50-
return template.HTML(str)
51-
}
52-
5349
func init() {
5450
RegisterCodeGenerator("golang", NewGolangGenerator())
5551
}

pkg/generator/helper.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
"html/template"
20+
)
21+
22+
func safeString(str string) template.HTML {
23+
return template.HTML(str)
24+
}
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 javascriptGenerator struct {
29+
}
30+
31+
func NewJavaScriptGenerator() CodeGenerator {
32+
return &javascriptGenerator{}
33+
}
34+
35+
func (g *javascriptGenerator) 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("javascript template").Funcs(template.FuncMap{"safeString": safeString}).Parse(javascriptTemplate); 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("JavaScript", NewJavaScriptGenerator())
51+
}
52+
53+
//go:embed data/main.javascript.tpl
54+
var javascriptTemplate string
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
14+
async function makeRequest() {
15+
const headers = new Headers();
16+
headers.append("User-Agent", "atest");
17+
18+
const requestOptions = {
19+
method: "GET",
20+
headers: headers,
21+
redirect: "follow"
22+
};
23+
console.log('the body is ignored because this is a GET request')
24+
/*
25+
let body = `{"key": "value"}`;
26+
requestOptions.body = body;
27+
*/
28+
29+
try {
30+
const response = await fetch("https://www.baidu.com", requestOptions);
31+
if (response.ok) { // Check if HTTP status code is 200/OK
32+
const text = await response.text();
33+
console.log(text);
34+
} else {
35+
throw new Error('Network response was not ok. Status code: ' + response.status);
36+
}
37+
} catch (error) {
38+
console.error('Fetch error:', error);
39+
}
40+
}
41+
42+
makeRequest();
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+
14+
async function makeRequest() {
15+
const headers = new Headers();
16+
headers.append("User-Agent", "atest");
17+
18+
const requestOptions = {
19+
method: "GET",
20+
headers: headers,
21+
redirect: "follow"
22+
};
23+
24+
try {
25+
const response = await fetch("https://www.baidu.com", requestOptions);
26+
if (response.ok) { // Check if HTTP status code is 200/OK
27+
const text = await response.text();
28+
console.log(text);
29+
} else {
30+
throw new Error('Network response was not ok. Status code: ' + response.status);
31+
}
32+
} catch (error) {
33+
console.error('Fetch error:', error);
34+
}
35+
}
36+
37+
makeRequest();
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
14+
async function makeRequest() {
15+
const headers = new Headers();
16+
headers.append("User-Agent", "atest");
17+
const cookieHeader = [
18+
"name=value",
19+
].join("; ");
20+
headers.append("Cookie", cookieHeader);
21+
22+
const requestOptions = {
23+
method: "GET",
24+
headers: headers,
25+
redirect: "follow"
26+
};
27+
console.log('the body is ignored because this is a GET request')
28+
/*
29+
const formData = new URLSearchParams();
30+
formData.append("key", "value");
31+
let body = formData;
32+
requestOptions.body = body;
33+
*/
34+
35+
try {
36+
const response = await fetch("https://www.baidu.com", requestOptions);
37+
if (response.ok) { // Check if HTTP status code is 200/OK
38+
const text = await response.text();
39+
console.log(text);
40+
} else {
41+
throw new Error('Network response was not ok. Status code: ' + response.status);
42+
}
43+
} catch (error) {
44+
console.error('Fetch error:', error);
45+
}
46+
}
47+
48+
makeRequest();

0 commit comments

Comments
 (0)