-
Notifications
You must be signed in to change notification settings - Fork 61
feat: support write the report to a HTTP server #367
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
Merged
LinuxSuRen
merged 1 commit into
LinuxSuRen:master
from
hahahashen:feat/addHttpResultWriter
Apr 22, 2024
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
/* | ||
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. | ||
*/ | ||
|
||
package runner | ||
|
||
import ( | ||
"bytes" | ||
_ "embed" | ||
"fmt" | ||
"html/template" | ||
"io" | ||
"log" | ||
"net/http" | ||
"os" | ||
|
||
"github.com/linuxsuren/api-testing/pkg/apispec" | ||
) | ||
|
||
type httpResultWriter struct { | ||
requestMethod string | ||
targetUrl string | ||
parameters map[string]string | ||
templateFile *TemplateOption | ||
} | ||
|
||
type TemplateOption struct { | ||
filename string | ||
fileType string | ||
} | ||
|
||
// NewHTTPResultWriter creates a new httpResultWriter | ||
func NewHTTPResultWriter(requestType string, url string, parameters map[string]string, templateFile *TemplateOption) ReportResultWriter { | ||
return &httpResultWriter{ | ||
requestMethod: requestType, | ||
targetUrl: url, | ||
parameters: parameters, | ||
templateFile: templateFile, | ||
} | ||
} | ||
|
||
func NewTemplateOption(filename string, fileType string) *TemplateOption { | ||
return &TemplateOption{ | ||
filename: filename, | ||
fileType: fileType, | ||
} | ||
} | ||
|
||
// Output writes the JSON base report to target writer | ||
func (w *httpResultWriter) Output(result []ReportResult) (err error) { | ||
url := w.targetUrl | ||
for key, value := range w.parameters { | ||
if url == w.targetUrl { | ||
url = fmt.Sprintf("%s?%s=%s", url, key, value) | ||
} else { | ||
url = fmt.Sprintf("%s&%s=%s", url, key, value) | ||
} | ||
} | ||
log.Println("will send report to:" + url) | ||
|
||
var tmpl *template.Template | ||
if w.templateFile == nil { | ||
// use the default template file to serialize the data to JSON format | ||
tmpl, err = template.New("HTTP report template").Parse(defaultTemplate) | ||
if err != nil { | ||
log.Fatalf("Failed to parse template: %v", err) | ||
} | ||
} else { | ||
content, err := os.ReadFile(w.templateFile.filename) | ||
if err != nil { | ||
log.Println("Error reading file:", err) | ||
return err | ||
} | ||
|
||
tmpl, err = template.New("HTTP report template").Parse(string(content)) | ||
if err != nil { | ||
log.Println("Error parsing template:", err) | ||
return err | ||
} | ||
} | ||
|
||
buf := new(bytes.Buffer) | ||
err = tmpl.Execute(buf, result) | ||
if err != nil { | ||
log.Printf("Failed to render template: %v", err) | ||
return | ||
} | ||
req, err := http.NewRequest(w.requestMethod, url, buf) | ||
if err != nil { | ||
log.Println("Error creating request:", err) | ||
return | ||
} | ||
|
||
var contentType string | ||
if w.templateFile != nil { | ||
switch w.templateFile.fileType { | ||
case "html": | ||
contentType = "text/html" | ||
case "yaml": | ||
contentType = "application/yaml" | ||
case "xml": | ||
contentType = "application/xml" | ||
default: | ||
contentType = "application/json" | ||
} | ||
} else { | ||
contentType = "application/json" | ||
} | ||
req.Header.Set("Content-Type", contentType) | ||
|
||
var resp *http.Response | ||
if resp, err = http.DefaultClient.Do(req); err != nil { | ||
log.Println("error when client do", err) | ||
return | ||
} | ||
if resp.StatusCode == http.StatusOK { | ||
var data []byte | ||
if data, err = io.ReadAll(resp.Body); err != nil { | ||
log.Println("error when ReadAll", err) | ||
return | ||
} | ||
log.Println("getting response back", data) | ||
} | ||
return | ||
} | ||
|
||
//go:embed writer_templates/example.tpl | ||
var defaultTemplate string | ||
|
||
// WithAPIConverage sets the api coverage | ||
func (w *httpResultWriter) WithAPIConverage(apiConverage apispec.APIConverage) ReportResultWriter { | ||
return w | ||
} | ||
|
||
func (w *httpResultWriter) WithResourceUsage([]ResourceUsage) ReportResultWriter { | ||
return w | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
/* | ||
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. | ||
*/ | ||
|
||
package runner | ||
|
||
import ( | ||
"net/http" | ||
"testing" | ||
|
||
"github.com/h2non/gock" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestHTTPResultWriter(t *testing.T) { | ||
t.Run("test get request", func(t *testing.T) { | ||
defer gock.Off() | ||
gock.New("https://test.com").Get("/result/get").Reply(http.StatusOK).JSON([]comment{}) | ||
|
||
writer := NewHTTPResultWriter("GET", "https://test.com/result/get", nil, nil) | ||
|
||
err := writer.Output([]ReportResult{{ | ||
API: "/api", | ||
}}) | ||
assert.NoError(t, err) | ||
}) | ||
|
||
t.Run("test post request", func(t *testing.T) { | ||
defer gock.Off() | ||
gock.New("https://test.com").Post("/result/post").Reply(http.StatusOK).JSON([]comment{}) | ||
|
||
writer := NewHTTPResultWriter("POST", "https://test.com/result/post", nil, nil) | ||
|
||
err := writer.Output([]ReportResult{{ | ||
API: "/api", | ||
}}) | ||
assert.NoError(t, err) | ||
}) | ||
|
||
t.Run("test parameters", func(t *testing.T) { | ||
defer gock.Off() | ||
gock.New("https://test.com/result/post?username=1&pwd=2").Post("").Reply(http.StatusOK).JSON([]comment{}) | ||
|
||
parameters := map[string]string{ | ||
"username": "1", | ||
"pwd": "2", | ||
} | ||
|
||
writer := NewHTTPResultWriter("POST", "https://test.com/result/post", parameters, nil) | ||
|
||
err := writer.Output([]ReportResult{{ | ||
API: "/api", | ||
}}) | ||
assert.NoError(t, err) | ||
}) | ||
|
||
t.Run("test user does not send template file", func(t *testing.T) { | ||
defer gock.Off() | ||
gock.New("https://test.com/result/post?username=1&pwd=2").Post("").Reply(http.StatusOK).JSON([]comment{}) | ||
|
||
parameters := map[string]string{ | ||
"username": "1", | ||
"pwd": "2", | ||
} | ||
|
||
writer := NewHTTPResultWriter("POST", "https://test.com/result/post", parameters, nil) | ||
|
||
err := writer.Output([]ReportResult{{ | ||
Name: "test", | ||
API: "/api", | ||
Count: 1, | ||
}}) | ||
assert.NoError(t, err) | ||
}) | ||
|
||
t.Run("test user send template file", func(t *testing.T) { | ||
defer gock.Off() | ||
gock.New("https://test.com/result/post?username=1&pwd=2").Post("").Reply(http.StatusOK).JSON([]comment{}) | ||
|
||
parameters := map[string]string{ | ||
"username": "1", | ||
"pwd": "2", | ||
} | ||
templateOption := NewTemplateOption("./writer_templates/example.tpl", "json") | ||
writer := NewHTTPResultWriter("POST", "https://test.com/result/post", parameters, templateOption) | ||
|
||
err := writer.Output([]ReportResult{{ | ||
Name: "test", | ||
API: "/api", | ||
Count: 1, | ||
}}) | ||
assert.NoError(t, err) | ||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
[ | ||
{{range $index, $result := .}} | ||
{ | ||
"Name": "{{$result.Name}}", | ||
"API": "{{$result.API}}", | ||
"Count": {{$result.Count}}, | ||
"Average": "{{$result.Average}}", | ||
"Max": "{{$result.Max}}", | ||
"Min": "{{$result.Min}}", | ||
"QPS": {{$result.QPS}}, | ||
"Error": {{$result.Error}}, | ||
"LastErrorMessage": "{{$result.LastErrorMessage}}" | ||
} | ||
{{end}} | ||
] |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.