Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support to generator Java code from a HTTP testCase #369

Merged
merged 5 commits into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions pkg/generator/code_generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ func TestGenerators(t *testing.T) {
assert.Equal(t, expectedGoCode, result)
})

t.Run("java", func(t *testing.T) {
result, err := generator.GetCodeGenerator("java").Generate(nil, testcase)
assert.NoError(t, err)
assert.Equal(t, expectedJavaCode, result)
})

formRequest := &atest.TestCase{Request: testcase.Request}
formRequest.Request.Form = map[string]string{
"key": "value",
Expand All @@ -67,6 +73,12 @@ func TestGenerators(t *testing.T) {
assert.Equal(t, expectedFormRequestGoCode, result, result)
})

t.Run("java form HTTP request", func(t *testing.T) {
result, err := generator.GetCodeGenerator("java").Generate(nil, formRequest)
assert.NoError(t, err)
assert.Equal(t, expectedFormRequestJavaCode, result, result)
})

cookieRequest := &atest.TestCase{Request: formRequest.Request}
cookieRequest.Request.Cookie = map[string]string{
"name": "value",
Expand All @@ -76,13 +88,28 @@ func TestGenerators(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, expectedCookieRequestGoCode, result, result)
})

t.Run("java cookie HTTP request", func(t *testing.T) {
result, err := generator.GetCodeGenerator("java").Generate(nil, cookieRequest)
assert.NoError(t, err)
assert.Equal(t, expectedCookieRequestJavaCode, result, result)
})
}

//go:embed testdata/expected_go_code.txt
var expectedGoCode string

//go:embed testdata/expected_java_code.txt
var expectedJavaCode string

//go:embed testdata/expected_go_form_request_code.txt
var expectedFormRequestGoCode string

//go:embed testdata/expected_java_form_request_code.txt
var expectedFormRequestJavaCode string

//go:embed testdata/expected_go_cookie_request_code.txt
var expectedCookieRequestGoCode string

//go:embed testdata/expected_java_cookie_request_code.txt
var expectedCookieRequestJavaCode string
66 changes: 66 additions & 0 deletions pkg/generator/data/main.java.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
Copyright 2024 API Testing Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.BufferedReader;
LinuxSuRen marked this conversation as resolved.
Show resolved Hide resolved
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Main {
public static void main(String[] args) throws Exception {
{{- if gt (len .Request.Form) 0 }}
StringBuilder postData = new StringBuilder();
{{- range $key, $val := .Request.Form}}
postData.append(URLEncoder.encode("{{$key}}", "UTF-8"));
postData.append("=");
postData.append(URLEncoder.encode("{{$val}}", "UTF-8"));
postData.append("&");
{{- end}}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
{{- else}}
String body = "{{.Request.Body.String}}";
byte[] postDataBytes = body.getBytes("UTF-8");
{{- end }}

URL url = new URL("{{.Request.API}}");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("{{.Request.Method}}");

{{- range $key, $val := .Request.Header}}
conn.setRequestProperty("{{$key}}", "{{$val}}");
{{- end}}

{{- if gt (len .Request.Cookie) 0 }}
{{- range $key, $val := .Request.Cookie}}
conn.setRequestProperty("Cookie", "{{$key}}={{$val}}");
{{- end}}
{{- end}}

conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();

System.out.println(response);

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("status code is not 200");
}
}
}
53 changes: 53 additions & 0 deletions pkg/generator/java_generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
Copyright 2024 API Testing Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
LinuxSuRen marked this conversation as resolved.
Show resolved Hide resolved
package generator

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

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

type javaGenerator struct {
}

func NewJavaGenerator() CodeGenerator {
return &javaGenerator{}
}

func (g *javaGenerator) Generate(testSuite *testing.TestSuite, 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("java template").Parse(javaTemplate); err == nil {
buf := new(bytes.Buffer)
if err = tpl.Execute(buf, testcase); err == nil {
result = buf.String()
}
}
return
}

func init() {
RegisterCodeGenerator("java", NewJavaGenerator())
}

//go:embed data/main.java.tpl
var javaTemplate string
46 changes: 46 additions & 0 deletions pkg/generator/testdata/expected_java_code.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Copyright 2024 API Testing Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Main {
public static void main(String[] args) throws Exception {
String body = "";
byte[] postDataBytes = body.getBytes("UTF-8");

URL url = new URL("https://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "atest");

conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();

System.out.println(response);

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("status code is not 200");
}
}
}
51 changes: 51 additions & 0 deletions pkg/generator/testdata/expected_java_cookie_request_code.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Copyright 2024 API Testing Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Main {
public static void main(String[] args) throws Exception {
StringBuilder postData = new StringBuilder();
postData.append(URLEncoder.encode("key", "UTF-8"));
postData.append("=");
postData.append(URLEncoder.encode("value", "UTF-8"));
postData.append("&");
byte[] postDataBytes = postData.toString().getBytes("UTF-8");

URL url = new URL("https://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "atest");
conn.setRequestProperty("Cookie", "name=value");

conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();

System.out.println(response);

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("status code is not 200");
}
}
}
50 changes: 50 additions & 0 deletions pkg/generator/testdata/expected_java_form_request_code.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2024 API Testing Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Main {
public static void main(String[] args) throws Exception {
StringBuilder postData = new StringBuilder();
postData.append(URLEncoder.encode("key", "UTF-8"));
postData.append("=");
postData.append(URLEncoder.encode("value", "UTF-8"));
postData.append("&");
byte[] postDataBytes = postData.toString().getBytes("UTF-8");

URL url = new URL("https://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "atest");

conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();

System.out.println(response);

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("status code is not 200");
}
}
}
2 changes: 1 addition & 1 deletion pkg/server/remote_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ func TestCodeGenerator(t *testing.T) {
t.Run("ListCodeGenerator", func(t *testing.T) {
generators, err := server.ListCodeGenerator(ctx, &Empty{})
assert.NoError(t, err)
assert.Equal(t, 3, len(generators.Data))
assert.Equal(t, 4, len(generators.Data))
})

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