add unittest; add --patch options

This commit is contained in:
buyuxiang
2022-05-17 16:03:45 +08:00
parent dd9f8878b2
commit 76bf2309ed
18 changed files with 604 additions and 248 deletions
@@ -1,4 +1,4 @@
package convert
package case2script
import (
_ "embed"
+9
View File
@@ -0,0 +1,9 @@
# har2case
Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner and HttpRunner+.
## Install
## Quick Start
## Examples
+424
View File
@@ -0,0 +1,424 @@
package har2case
import (
"encoding/base64"
"fmt"
"net/url"
"path/filepath"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v4/hrp"
"github.com/httprunner/httprunner/v4/hrp/internal/builtin"
"github.com/httprunner/httprunner/v4/hrp/internal/json"
"github.com/httprunner/httprunner/v4/hrp/internal/sdk"
)
const (
suffixJSON = ".json"
suffixYAML = ".yaml"
)
const (
configProfile = "profile"
configPatch = "patch"
keyHeaders = "headers"
keyCookies = "cookies"
)
func NewHAR(path string) *har {
return &har{
path: path,
}
}
type har struct {
path string
filterStr string
excludeStr string
profile map[string]interface{}
patch map[string]interface{}
outputDir string
}
func (h *har) SetProfile(path string) {
log.Info().Str("path", path).Msg("set profile")
h.profile = make(map[string]interface{})
err := builtin.LoadFile(path, h.profile)
if err != nil {
log.Warn().Str("path", path).
Msg("invalid profile format, ignore!")
}
}
func (h *har) SetPatch(path string) {
log.Info().Str("path", path).Msg("set patch")
h.patch = make(map[string]interface{})
err := builtin.LoadFile(path, h.patch)
if err != nil {
log.Warn().Str("path", path).
Msg("invalid patch format, ignore!")
}
}
func (h *har) SetOutputDir(dir string) {
log.Info().Str("dir", dir).Msg("set output directory")
h.outputDir = dir
}
func (h *har) GenJSON() (jsonPath string, err error) {
event := sdk.EventTracking{
Category: "ConvertTests",
Action: "hrp har2case --to-json",
}
// report start event
go sdk.SendEvent(event)
// report running timing event
defer sdk.SendEvent(event.StartTiming("execution"))
tCase, err := h.makeTestCase()
if err != nil {
return "", err
}
jsonPath = h.genOutputPath(suffixJSON)
err = builtin.Dump2JSON(tCase, jsonPath)
return
}
func (h *har) GenYAML() (yamlPath string, err error) {
event := sdk.EventTracking{
Category: "ConvertTests",
Action: "hrp har2case --to-yaml",
}
// report start event
go sdk.SendEvent(event)
// report running timing event
defer sdk.SendEvent(event.StartTiming("execution"))
tCase, err := h.makeTestCase()
if err != nil {
return "", err
}
yamlPath = h.genOutputPath(suffixYAML)
err = builtin.Dump2YAML(tCase, yamlPath)
return
}
func (h *har) makeTestCase() (*hrp.TCase, error) {
teststeps, err := h.prepareTestSteps()
if err != nil {
return nil, err
}
tCase := &hrp.TCase{
Config: h.prepareConfig(),
TestSteps: teststeps,
}
return tCase, nil
}
func (h *har) load() (*Har, error) {
har := &Har{}
err := builtin.LoadFile(h.path, har)
if err != nil {
return nil, errors.Wrap(err, "load har failed")
}
return har, nil
}
func (h *har) prepareConfig() *hrp.TConfig {
return hrp.NewConfig("testcase description").
SetVerifySSL(false)
}
func (h *har) prepareTestSteps() ([]*hrp.TStep, error) {
har, err := h.load()
if err != nil {
return nil, err
}
var steps []*hrp.TStep
for _, entry := range har.Log.Entries {
step, err := h.prepareTestStep(&entry)
if err != nil {
return nil, err
}
steps = append(steps, step)
}
return steps, nil
}
func (h *har) prepareTestStep(entry *Entry) (*hrp.TStep, error) {
log.Info().
Str("method", entry.Request.Method).
Str("url", entry.Request.URL).
Msg("convert teststep")
step := &tStep{
TStep: hrp.TStep{
Request: &hrp.Request{},
Validators: make([]interface{}, 0),
},
profile: h.profile,
patch: h.patch,
}
if err := step.makeRequestMethod(entry); err != nil {
return nil, err
}
if err := step.makeRequestURL(entry); err != nil {
return nil, err
}
if err := step.makeRequestParams(entry); err != nil {
return nil, err
}
if err := step.makeRequestCookies(entry); err != nil {
return nil, err
}
if err := step.makeRequestHeaders(entry); err != nil {
return nil, err
}
if err := step.makeRequestBody(entry); err != nil {
return nil, err
}
if err := step.makeValidate(entry); err != nil {
return nil, err
}
return &step.TStep, nil
}
type tStep struct {
hrp.TStep
profile map[string]interface{}
patch map[string]interface{}
}
func (s *tStep) makeRequestMethod(entry *Entry) error {
s.Request.Method = hrp.HTTPMethod(entry.Request.Method)
return nil
}
func (s *tStep) makeRequestURL(entry *Entry) error {
u, err := url.Parse(entry.Request.URL)
if err != nil {
log.Error().Err(err).Msg("make request url failed")
return err
}
s.Request.URL = fmt.Sprintf("%s://%s", u.Scheme, u.Host+u.Path)
return nil
}
func (s *tStep) makeRequestParams(entry *Entry) error {
s.Request.Params = make(map[string]interface{})
for _, param := range entry.Request.QueryString {
s.Request.Params[param.Name] = param.Value
}
return nil
}
func (s *tStep) updateRequestInfo(config string, key string) bool {
var m map[string]interface{}
switch config {
case configProfile:
m = s.profile
case configPatch:
m = s.patch
default:
return false
}
iRequestMap, existed := m[key]
if existed {
requestMap, ok := iRequestMap.(map[string]interface{})
if ok {
for k, v := range requestMap {
switch key {
case keyHeaders:
s.Request.Headers[k] = fmt.Sprintf("%v", v)
case keyCookies:
s.Request.Cookies[k] = fmt.Sprintf("%v", v)
}
}
return true
}
log.Warn().Interface(key, iRequestMap).Msgf("%v from %v is not a map, ignore!", key, config)
}
return false
}
func (s *tStep) makeRequestCookies(entry *Entry) error {
s.Request.Cookies = make(map[string]string)
// override all cookies according to the profile
if s.updateRequestInfo(configProfile, keyCookies) {
return nil
}
// use cookies from har
for _, cookie := range entry.Request.Cookies {
s.Request.Cookies[cookie.Name] = cookie.Value
}
// create or update the cookies indicated in the patch
s.updateRequestInfo(configPatch, keyCookies)
return nil
}
func (s *tStep) makeRequestHeaders(entry *Entry) error {
s.Request.Headers = make(map[string]string)
// override all headers according to the profile
if s.updateRequestInfo(configProfile, keyHeaders) {
return nil
}
// use headers from har
for _, header := range entry.Request.Headers {
if strings.EqualFold(header.Name, "cookie") {
continue
}
s.Request.Headers[header.Name] = header.Value
}
// create or update the headers indicated in the patch
s.updateRequestInfo(configPatch, keyHeaders)
return nil
}
func (s *tStep) makeRequestBody(entry *Entry) error {
mimeType := entry.Request.PostData.MimeType
if mimeType == "" {
// GET/HEAD/DELETE without body
return nil
}
// POST/PUT with body
if strings.HasPrefix(mimeType, "application/json") {
// post json
var body interface{}
if entry.Request.PostData.Text == "" {
body = nil
} else {
err := json.Unmarshal([]byte(entry.Request.PostData.Text), &body)
if err != nil {
log.Error().Err(err).Msg("make request body failed")
return err
}
}
s.Request.Body = body
} else if strings.HasPrefix(mimeType, "application/x-www-form-urlencoded") {
// post form
var paramsList []string
for _, param := range entry.Request.PostData.Params {
paramsList = append(paramsList, fmt.Sprintf("%s=%s", param.Name, param.Value))
}
s.Request.Body = strings.Join(paramsList, "&")
} else if strings.HasPrefix(mimeType, "text/plain") {
// post raw data
s.Request.Body = entry.Request.PostData.Text
} else {
// TODO
log.Error().Msgf("makeRequestBody: Not implemented for mimeType %s", mimeType)
}
return nil
}
func (s *tStep) makeValidate(entry *Entry) error {
// make validator for response status code
s.Validators = append(s.Validators, hrp.Validator{
Check: "status_code",
Assert: "equals",
Expect: entry.Response.Status,
Message: "assert response status code",
})
// make validators for response headers
for _, header := range entry.Response.Headers {
// assert Content-Type
if strings.EqualFold(header.Name, "Content-Type") {
s.Validators = append(s.Validators, hrp.Validator{
Check: "headers.\"Content-Type\"",
Assert: "equals",
Expect: header.Value,
Message: "assert response header Content-Type",
})
}
}
// make validators for response body
respBody := entry.Response.Content
if respBody.Text == "" {
// response body is empty
return nil
}
if strings.HasPrefix(respBody.MimeType, "application/json") {
var data []byte
var err error
// response body is json
if respBody.Encoding == "base64" {
// decode base64 text
data, err = base64.StdEncoding.DecodeString(respBody.Text)
if err != nil {
return errors.Wrap(err, "decode base64 error")
}
} else if respBody.Encoding == "" {
// no encoding
data = []byte(respBody.Text)
} else {
// other encoding type
return nil
}
// convert to json
var body interface{}
if err = json.Unmarshal(data, &body); err != nil {
return errors.Wrap(err, "json.Unmarshal body error")
}
jsonBody, ok := body.(map[string]interface{})
if !ok {
return fmt.Errorf("response body is not json, not matched with MimeType")
}
// response body is json
keys := make([]string, 0, len(jsonBody))
for k := range jsonBody {
keys = append(keys, k)
}
// sort map keys to keep validators in stable order
sort.Strings(keys)
for _, key := range keys {
value := jsonBody[key]
switch v := value.(type) {
case map[string]interface{}:
continue
case []interface{}:
continue
default:
s.Validators = append(s.Validators, hrp.Validator{
Check: fmt.Sprintf("body.%s", key),
Assert: "equals",
Expect: v,
Message: fmt.Sprintf("assert response body %s", key),
})
}
}
}
return nil
}
func (h *har) genOutputPath(suffix string) string {
file := getFilenameWithoutExtension(h.path) + suffix
if h.outputDir != "" {
return filepath.Join(h.outputDir, file)
} else {
return filepath.Join(filepath.Dir(h.path), file)
}
}
func getFilenameWithoutExtension(path string) string {
base := filepath.Base(path)
ext := filepath.Ext(base)
return base[0 : len(base)-len(ext)]
}
+413
View File
@@ -0,0 +1,413 @@
package har2case
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/httprunner/httprunner/v4/hrp"
)
var (
harPath = "../../../../examples/data/har/demo.har"
harPath2 = "../../../../examples/data/har/postman-echo.har"
profilePath = "../../../../examples/data/har/profile.yml"
)
func TestGenJSON(t *testing.T) {
jsonPath, err := NewHAR(harPath).GenJSON()
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.NotEmpty(t, jsonPath) {
t.Fatal()
}
}
func TestGenYAML(t *testing.T) {
yamlPath, err := NewHAR(harPath2).GenYAML()
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.NotEmpty(t, yamlPath) {
t.Fatal()
}
}
func TestLoadHAR(t *testing.T) {
har := NewHAR(harPath)
h, err := har.load()
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, "GET", h.Log.Entries[0].Request.Method) {
t.Fatal()
}
if !assert.Equal(t, "POST", h.Log.Entries[1].Request.Method) {
t.Fatal()
}
}
func TestLoadHARWithProfile(t *testing.T) {
har := NewHAR(harPath)
har.SetProfile(profilePath)
_, err := har.load()
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t,
map[string]interface{}{"Content-Type": "application/x-www-form-urlencoded"},
har.profile["headers"]) {
t.Fatal()
}
if !assert.Equal(t,
map[string]interface{}{"UserName": "debugtalk"},
har.profile["cookies"]) {
t.Fatal()
}
}
func TestMakeTestCase(t *testing.T) {
har := NewHAR(harPath)
tCase, err := har.makeTestCase()
if !assert.NoError(t, err) {
t.Fatal()
}
// make request method
if !assert.EqualValues(t, "GET", tCase.TestSteps[0].Request.Method) {
t.Fatal()
}
if !assert.EqualValues(t, "POST", tCase.TestSteps[1].Request.Method) {
t.Fatal()
}
// make request url
if !assert.Equal(t, "https://postman-echo.com/get", tCase.TestSteps[0].Request.URL) {
t.Fatal()
}
if !assert.Equal(t, "https://postman-echo.com/post", tCase.TestSteps[1].Request.URL) {
t.Fatal()
}
// make request params
if !assert.Equal(t, "HDnY8", tCase.TestSteps[0].Request.Params["foo1"]) {
t.Fatal()
}
// make request cookies
if !assert.NotEmpty(t, tCase.TestSteps[1].Request.Cookies["sails.sid"]) {
t.Fatal()
}
// make request headers
if !assert.Equal(t, "HttpRunnerPlus", tCase.TestSteps[0].Request.Headers["User-Agent"]) {
t.Fatal()
}
if !assert.Equal(t, "postman-echo.com", tCase.TestSteps[0].Request.Headers["Host"]) {
t.Fatal()
}
// make request data
if !assert.Equal(t, nil, tCase.TestSteps[0].Request.Body) {
t.Fatal()
}
if !assert.Equal(t, map[string]interface{}{"foo1": "HDnY8", "foo2": 12.3}, tCase.TestSteps[1].Request.Body) {
t.Fatal()
}
if !assert.Equal(t, "foo1=HDnY8&foo2=12.3", tCase.TestSteps[2].Request.Body) {
t.Fatal()
}
// make validators
validator, ok := tCase.TestSteps[0].Validators[0].(hrp.Validator)
if !ok || !assert.Equal(t, "status_code", validator.Check) {
t.Fatal()
}
validator, ok = tCase.TestSteps[0].Validators[1].(hrp.Validator)
if !ok || !assert.Equal(t, "headers.\"Content-Type\"", validator.Check) {
t.Fatal()
}
validator, ok = tCase.TestSteps[0].Validators[2].(hrp.Validator)
if !ok || !assert.Equal(t, "body.url", validator.Check) {
t.Fatal()
}
}
func TestGetFilenameWithoutExtension(t *testing.T) {
filename := getFilenameWithoutExtension(harPath2)
if !assert.Equal(t, "postman-echo", filename) {
t.Fatal()
}
}
func TestMakeRequestURL(t *testing.T) {
har := NewHAR("")
entry := &Entry{
Request: Request{
URL: "http://127.0.0.1:8080/api/login",
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, "http://127.0.0.1:8080/api/login", step.Request.URL) {
t.Fatal()
}
}
func TestMakeRequestHeaders(t *testing.T) {
har := NewHAR("")
entry := &Entry{
Request: Request{
Method: "POST",
Headers: []NVP{
{Name: "Content-Type", Value: "application/json; charset=utf-8"},
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, map[string]string{
"Content-Type": "application/json; charset=utf-8",
}, step.Request.Headers) {
t.Fatal()
}
}
func TestMakeRequestHeadersWithProfile(t *testing.T) {
har := NewHAR("")
har.SetProfile(profilePath)
entry := &Entry{
Request: Request{
Method: "POST",
Headers: []NVP{
{Name: "Content-Type", Value: "application/json; charset=utf-8"},
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
}, step.Request.Headers) {
t.Fatal()
}
}
func TestMakeRequestCookies(t *testing.T) {
har := NewHAR("")
entry := &Entry{
Request: Request{
Method: "POST",
Cookies: []Cookie{
{Name: "abc", Value: "123"},
{Name: "UserName", Value: "leolee"},
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, map[string]string{
"abc": "123",
"UserName": "leolee",
}, step.Request.Cookies) {
t.Fatal()
}
}
func TestMakeRequestCookiesWithProfile(t *testing.T) {
har := NewHAR("")
har.SetProfile(profilePath)
entry := &Entry{
Request: Request{
Method: "POST",
Cookies: []Cookie{
{Name: "abc", Value: "123"},
{Name: "UserName", Value: "leolee"},
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, map[string]string{
"UserName": "debugtalk",
}, step.Request.Cookies) {
t.Fatal()
}
}
func TestMakeRequestDataParams(t *testing.T) {
har := NewHAR("")
entry := &Entry{
Request: Request{
Method: "POST",
PostData: PostData{
MimeType: "application/x-www-form-urlencoded; charset=utf-8",
Params: []PostParam{
{Name: "a", Value: "1"},
{Name: "b", Value: "2"},
},
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, "a=1&b=2", step.Request.Body) {
t.Fatal()
}
}
func TestMakeRequestDataJSON(t *testing.T) {
har := NewHAR("")
entry := &Entry{
Request: Request{
Method: "POST",
PostData: PostData{
MimeType: "application/json; charset=utf-8",
Text: "{\"a\":\"1\",\"b\":\"2\"}",
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, map[string]interface{}{"a": "1", "b": "2"}, step.Request.Body) {
t.Fatal()
}
}
func TestMakeRequestDataTextEmpty(t *testing.T) {
har := NewHAR("")
entry := &Entry{
Request: Request{
Method: "POST",
PostData: PostData{
MimeType: "application/json; charset=utf-8",
Text: "",
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.Equal(t, nil, step.Request.Body) { // TODO
t.Fatal()
}
}
func TestMakeValidate(t *testing.T) {
har := NewHAR("")
entry := &Entry{
Response: Response{
Status: 200,
Headers: []NVP{
{Name: "Content-Type", Value: "application/json; charset=utf-8"},
},
Content: Content{
Size: 71,
MimeType: "application/json; charset=utf-8",
// map[Code:200 IsSuccess:true Message:<nil> Value:map[BlnResult:true]]
Text: "eyJJc1N1Y2Nlc3MiOnRydWUsIkNvZGUiOjIwMCwiTWVzc2FnZSI6bnVsbCwiVmFsdWUiOnsiQmxuUmVzdWx0Ijp0cnVlfX0=",
Encoding: "base64",
},
},
}
step, err := har.prepareTestStep(entry)
if !assert.NoError(t, err) {
t.Fatal()
}
validator, ok := step.Validators[0].(hrp.Validator)
if !ok {
t.Fatal()
}
if !assert.Equal(t, validator,
hrp.Validator{
Check: "status_code",
Expect: 200,
Assert: "equals",
Message: "assert response status code",
}) {
t.Fatal()
}
validator, ok = step.Validators[1].(hrp.Validator)
if !ok {
t.Fatal()
}
if !assert.Equal(t, validator,
hrp.Validator{
Check: "headers.\"Content-Type\"",
Expect: "application/json; charset=utf-8",
Assert: "equals",
Message: "assert response header Content-Type",
}) {
t.Fatal()
}
validator, ok = step.Validators[2].(hrp.Validator)
if !ok {
t.Fatal()
}
if !assert.Equal(t, validator,
hrp.Validator{
Check: "body.Code",
Expect: float64(200), // TODO
Assert: "equals",
Message: "assert response body Code",
}) {
t.Fatal()
}
}
func Test_tStep_makeRequestCookies(t *testing.T) {
type fields struct {
TStep hrp.TStep
profile map[string]interface{}
patch map[string]interface{}
}
type args struct {
entry *Entry
}
tests := []struct {
name string
fields fields
args args
wantErr assert.ErrorAssertionFunc
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &tStep{
TStep: tt.fields.TStep,
profile: tt.fields.profile,
patch: tt.fields.patch,
}
tt.wantErr(t, s.makeRequestCookies(tt.args.entry), fmt.Sprintf("makeRequestCookies(%v)", tt.args.entry))
})
}
}
+340
View File
@@ -0,0 +1,340 @@
package har2case
import "time"
/*
HTTP Archive (HAR) format
https://w3c.github.io/web-performance/specs/HAR/Overview.html
this file is copied from https://github.com/mrichman/hargo/blob/master/types.go
*/
// Har is a container type for deserialization
type Har struct {
Log Log `json:"log"`
}
// Log represents the root of the exported data. This object MUST be present and its name MUST be "log".
type Log struct {
// The object contains the following name/value pairs:
// Required. Version number of the format.
Version string `json:"version"`
// Required. An object of type creator that contains the name and version
// information of the log creator application.
Creator Creator `json:"creator"`
// Optional. An object of type browser that contains the name and version
// information of the user agent.
Browser Browser `json:"browser"`
// Optional. An array of objects of type page, each representing one exported
// (tracked) page. Leave out this field if the application does not support
// grouping by pages.
Pages []Page `json:"pages,omitempty"`
// Required. An array of objects of type entry, each representing one
// exported (tracked) HTTP request.
Entries []Entry `json:"entries"`
// Optional. A comment provided by the user or the application. Sorting
// entries by startedDateTime (starting from the oldest) is preferred way how
// to export data since it can make importing faster. However the reader
// application should always make sure the array is sorted (if required for
// the import).
Comment string `json:"comment"`
}
// Creator contains information about the log creator application
type Creator struct {
// Required. The name of the application that created the log.
Name string `json:"name"`
// Required. The version number of the application that created the log.
Version string `json:"version"`
// Optional. A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// Browser that created the log
type Browser struct {
// Required. The name of the browser that created the log.
Name string `json:"name"`
// Required. The version number of the browser that created the log.
Version string `json:"version"`
// Optional. A comment provided by the user or the browser.
Comment string `json:"comment"`
}
// Page object for every exported web page and one <entry> object for every HTTP request.
// In case when an HTTP trace tool isn't able to group requests by a page,
// the <pages> object is empty and individual requests doesn't have a parent page.
type Page struct {
/* There is one <page> object for every exported web page and one <entry>
object for every HTTP request. In case when an HTTP trace tool isn't able to
group requests by a page, the <pages> object is empty and individual
requests doesn't have a parent page.
*/
// Date and time stamp for the beginning of the page load
// (ISO 8601 YYYY-MM-DDThh:mm:ss.sTZD, e.g. 2009-07-24T19:20:30.45+01:00).
StartedDateTime string `json:"startedDateTime"`
// Unique identifier of a page within the . Entries use it to refer the parent page.
ID string `json:"id"`
// Page title.
Title string `json:"title"`
// Detailed timing info about page load.
PageTiming PageTiming `json:"pageTiming"`
// (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// PageTiming describes timings for various events (states) fired during the page load.
// All times are specified in milliseconds. If a time info is not available appropriate field is set to -1.
type PageTiming struct {
// Content of the page loaded. Number of milliseconds since page load started
// (page.startedDateTime). Use -1 if the timing does not apply to the current
// request.
// Depeding on the browser, onContentLoad property represents DOMContentLoad
// event or document.readyState == interactive.
OnContentLoad int `json:"onContentLoad"`
// Page is loaded (onLoad event fired). Number of milliseconds since page
// load started (page.startedDateTime). Use -1 if the timing does not apply
// to the current request.
OnLoad int `json:"onLoad"`
// (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment"`
}
// Entry is a unique, optional Reference to the parent page.
// Leave out this field if the application does not support grouping by pages.
type Entry struct {
Pageref string `json:"pageref,omitempty"`
// Date and time stamp of the request start
// (ISO 8601 YYYY-MM-DDThh:mm:ss.sTZD).
StartedDateTime string `json:"startedDateTime"`
// Total elapsed time of the request in milliseconds. This is the sum of all
// timings available in the timings object (i.e. not including -1 values) .
Time float32 `json:"time"`
// Detailed info about the request.
Request Request `json:"request"`
// Detailed info about the response.
Response Response `json:"response"`
// Info about cache usage.
Cache Cache `json:"cache"`
// Detailed timing info about request/response round trip.
PageTimings PageTimings `json:"pageTimings"`
// optional (new in 1.2) IP address of the server that was connected
// (result of DNS resolution).
ServerIPAddress string `json:"serverIPAddress,omitempty"`
// optional (new in 1.2) Unique ID of the parent TCP/IP connection, can be
// the client port number. Note that a port number doesn't have to be unique
// identifier in cases where the port is shared for more connections. If the
// port isn't available for the application, any other unique connection ID
// can be used instead (e.g. connection index). Leave out this field if the
// application doesn't support this info.
Connection string `json:"connection,omitempty"`
// (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// Request contains detailed info about performed request.
type Request struct {
// Request method (GET, POST, ...).
Method string `json:"method"`
// Absolute URL of the request (fragments are not included).
URL string `json:"url"`
// Request HTTP Version.
HTTPVersion string `json:"httpVersion"`
// List of cookie objects.
Cookies []Cookie `json:"cookies"`
// List of header objects.
Headers []NVP `json:"headers"`
// List of query parameter objects.
QueryString []NVP `json:"queryString"`
// Posted data.
PostData PostData `json:"postData"`
// Total number of bytes from the start of the HTTP request message until
// (and including) the double CRLF before the body. Set to -1 if the info
// is not available.
HeaderSize int `json:"headerSize"`
// Size of the request body (POST data payload) in bytes. Set to -1 if the
// info is not available.
BodySize int `json:"bodySize"`
// (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment"`
}
// Response contains detailed info about the response.
type Response struct {
// Response status.
Status int `json:"status"`
// Response status description.
StatusText string `json:"statusText"`
// Response HTTP Version.
HTTPVersion string `json:"httpVersion"`
// List of cookie objects.
Cookies []Cookie `json:"cookies"`
// List of header objects.
Headers []NVP `json:"headers"`
// Details about the response body.
Content Content `json:"content"`
// Redirection target URL from the Location response header.
RedirectURL string `json:"redirectURL"`
// Total number of bytes from the start of the HTTP response message until
// (and including) the double CRLF before the body. Set to -1 if the info is
// not available.
// The size of received response-headers is computed only from headers that
// are really received from the server. Additional headers appended by the
// browser are not included in this number, but they appear in the list of
// header objects.
HeadersSize int `json:"headersSize"`
// Size of the received response body in bytes. Set to zero in case of
// responses coming from the cache (304). Set to -1 if the info is not
// available.
BodySize int `json:"bodySize"`
// optional (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// Cookie contains list of all cookies (used in <request> and <response> objects).
type Cookie struct {
// The name of the cookie.
Name string `json:"name"`
// The cookie value.
Value string `json:"value"`
// optional The path pertaining to the cookie.
Path string `json:"path,omitempty"`
// optional The host of the cookie.
Domain string `json:"domain,omitempty"`
// optional Cookie expiration time.
// (ISO 8601 YYYY-MM-DDThh:mm:ss.sTZD, e.g. 2009-07-24T19:20:30.123+02:00).
Expires string `json:"expires,omitempty"`
// optional Set to true if the cookie is HTTP only, false otherwise.
HTTPOnly bool `json:"httpOnly,omitempty"`
// optional (new in 1.2) True if the cookie was transmitted over ssl, false
// otherwise.
Secure bool `json:"secure,omitempty"`
// optional (new in 1.2) A comment provided by the user or the application.
Comment bool `json:"comment,omitempty"`
}
// NVP is simply a name/value pair with a comment
type NVP struct {
Name string `json:"name"`
Value string `json:"value"`
Comment string `json:"comment,omitempty"`
}
// PostData describes posted data, if any (embedded in <request> object).
type PostData struct {
// Mime type of posted data.
MimeType string `json:"mimeType"`
// List of posted parameters (in case of URL encoded parameters).
Params []PostParam `json:"params"`
// Plain text posted data
Text string `json:"text"`
// optional (new in 1.2) A comment provided by the user or the
// application.
Comment string `json:"comment,omitempty"`
}
// PostParam is a list of posted parameters, if any (embedded in <postData> object).
type PostParam struct {
// name of a posted parameter.
Name string `json:"name"`
// optional value of a posted parameter or content of a posted file.
Value string `json:"value,omitempty"`
// optional name of a posted file.
FileName string `json:"fileName,omitempty"`
// optional content type of a posted file.
ContentType string `json:"contentType,omitempty"`
// optional (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// Content describes details about response content (embedded in <response> object).
type Content struct {
// Length of the returned content in bytes. Should be equal to
// response.bodySize if there is no compression and bigger when the content
// has been compressed.
Size int `json:"size"`
// optional Number of bytes saved. Leave out this field if the information
// is not available.
Compression int `json:"compression,omitempty"`
// MIME type of the response text (value of the Content-Type response
// header). The charset attribute of the MIME type is included (if
// available).
MimeType string `json:"mimeType"`
// optional Response body sent from the server or loaded from the browser
// cache. This field is populated with textual content only. The text field
// is either HTTP decoded text or a encoded (e.g. "base64") representation of
// the response body. Leave out this field if the information is not
// available.
Text string `json:"text,omitempty"`
// optional (new in 1.2) Encoding used for response text field e.g
// "base64". Leave out this field if the text field is HTTP decoded
// (decompressed & unchunked), than trans-coded from its original character
// set into UTF-8.
Encoding string `json:"encoding,omitempty"`
// optional (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// Cache contains info about a request coming from browser cache.
type Cache struct {
// optional State of a cache entry before the request. Leave out this field
// if the information is not available.
BeforeRequest CacheObject `json:"beforeRequest,omitempty"`
// optional State of a cache entry after the request. Leave out this field if
// the information is not available.
AfterRequest CacheObject `json:"afterRequest,omitempty"`
// optional (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// CacheObject is used by both beforeRequest and afterRequest
type CacheObject struct {
// optional - Expiration time of the cache entry.
Expires string `json:"expires,omitempty"`
// The last time the cache entry was opened.
LastAccess string `json:"lastAccess"`
// Etag
ETag string `json:"eTag"`
// The number of times the cache entry has been opened.
HitCount int `json:"hitCount"`
// optional (new in 1.2) A comment provided by the user or the application.
Comment string `json:"comment,omitempty"`
}
// PageTimings describes various phases within request-response round trip.
// All times are specified in milliseconds.
type PageTimings struct {
Blocked int `json:"blocked,omitempty"`
// optional - Time spent in a queue waiting for a network connection. Use -1
// if the timing does not apply to the current request.
DNS int `json:"dns,omitempty"`
// optional - DNS resolution time. The time required to resolve a host name.
// Use -1 if the timing does not apply to the current request.
Connect int `json:"connect,omitempty"`
// optional - Time required to create TCP connection. Use -1 if the timing
// does not apply to the current request.
Send int `json:"send"`
// Time required to send HTTP request to the server.
Wait int `json:"wait"`
// Waiting for a response from the server.
Receive int `json:"receive"`
// Time required to read entire response from the server (or cache).
Ssl int `json:"ssl,omitempty"`
// optional (new in 1.2) - Time required for SSL/TLS negotiation. If this
// field is defined then the time is also included in the connect field (to
// ensure backward compatibility with HAR 1.1). Use -1 if the timing does not
// apply to the current request.
Comment string `json:"comment,omitempty"`
// optional (new in 1.2) - A comment provided by the user or the application.
}
// TestResult contains results for an individual HTTP request
type TestResult struct {
URL string `json:"url"`
Status int `json:"status"` // 200, 500, etc.
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime"`
Latency int `json:"latency"` // milliseconds
Method string `json:"method"`
HarFile string `json:"harfile"`
}
@@ -0,0 +1,74 @@
package postman2case
/*
Postman Collection format reference:
https://schema.postman.com/json/collection/v2.0.0/collection.json
https://schema.postman.com/json/collection/v2.1.0/collection.json
*/
// TCollection represents the postman exported file
type TCollection struct {
Info TInfo `json:"info"`
Items []TItem `json:"item"`
}
// TInfo gives information about the collection
type TInfo struct {
Name string `json:"name"`
Description string `json:"description"`
Schema string `json:"schema"`
}
// TItem contains the detail information of request and expected responses
// item could be defined recursively
type TItem struct {
Items []TItem `json:"item"`
Name string `json:"name"`
Request TRequest `json:"request"`
Responses []TResponse `json:"response"`
}
type TRequest struct {
Method string `json:"method"`
Headers []TField `json:"header"`
Body TBody `json:"body"`
URL TUrl `json:"url"`
Description string `json:"description"`
}
type TResponse struct {
Name string `json:"name"`
OriginalRequest TRequest `json:"originalRequest"`
Status string `json:"status"`
Code int `json:"code"`
Headers []TField `json:"headers"`
Body string `json:"body"`
}
type TUrl struct {
Raw string `json:"raw"`
Protocol string `json:"protocol"`
Path []string `json:"path"`
Description string `json:"description"`
Query []TField `json:"query"`
Variable []TField `json:"variable"`
}
type TField struct {
Key string `json:"key"`
Value string `json:"value"`
Src string `json:"src"`
Description string `json:"description"`
Type string `json:"type"`
Disabled bool `json:"disabled"`
Enable bool `json:"enable"`
}
type TBody struct {
Mode string `json:"mode"`
FormData []TField `json:"formdata"`
URLEncoded []TField `json:"urlencoded"`
Raw string `json:"raw"`
Disabled bool `json:"disabled"`
Options interface{} `json:"options"`
}
+465
View File
@@ -0,0 +1,465 @@
package postman2case
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v4/hrp"
"github.com/httprunner/httprunner/v4/hrp/internal/builtin"
"github.com/httprunner/httprunner/v4/hrp/internal/json"
)
const (
enumBodyRaw = "raw"
enumBodyUrlEncoded = "urlencoded"
enumBodyFormData = "formdata"
enumBodyFile = "file"
enumBodyGraphQL = "graphql"
)
const (
enumFieldTypeText = "text"
enumFieldTypeFile = "file"
)
const (
suffixName = ".converted" // distinguish the converted json(testcase) from the origin json(collection)
extensionJSON = ".json"
extensionYAML = ".yaml"
)
const (
configProfile = "profile"
configPatch = "patch"
keyHeaders = "headers"
keyCookies = "cookies"
)
var contentTypeMap = map[string]string{
"text": "text/plain",
"javascript": "application/javascript",
"json": "application/json",
"html": "text/html",
"xml": "application/xml",
}
func NewCollection(path string) *collection {
return &collection{
path: path,
}
}
type collection struct {
path string
profile map[string]interface{}
patch map[string]interface{}
outputDir string
}
func (c *collection) SetProfile(path string) {
log.Info().Str("path", path).Msg("set profile")
c.profile = make(map[string]interface{})
err := builtin.LoadFile(path, c.profile)
if err != nil {
log.Warn().Str("path", path).
Msg("invalid profile format, ignore!")
}
}
func (c *collection) SetPatch(path string) {
log.Info().Str("path", path).Msg("set patch")
c.patch = make(map[string]interface{})
err := builtin.LoadFile(path, c.patch)
if err != nil {
log.Warn().Str("path", path).
Msg("invalid patch format, ignore!")
}
}
func (c *collection) SetOutputDir(dir string) {
log.Info().Str("dir", dir).Msg("set output directory")
c.outputDir = dir
}
func (c *collection) GenJSON() (jsonPath string, err error) {
testCase, err := c.makeTestCase()
if err != nil {
return "", err
}
jsonPath = c.genOutputPath(extensionJSON)
err = builtin.Dump2JSON(testCase, jsonPath)
return
}
func (c *collection) GenYAML() (yamlPath string, err error) {
testCase, err := c.makeTestCase()
if err != nil {
return "", err
}
yamlPath = c.genOutputPath(extensionYAML)
err = builtin.Dump2YAML(testCase, yamlPath)
return
}
func (c *collection) genOutputPath(suffix string) string {
file := getFilenameWithoutExtension(c.path) + suffix
if c.outputDir != "" {
return filepath.Join(c.outputDir, file)
} else {
return filepath.Join(filepath.Dir(c.path), file)
}
}
func getFilenameWithoutExtension(path string) string {
base := filepath.Base(path)
ext := filepath.Ext(base)
return base[0:len(base)-len(ext)] + suffixName
}
func (c *collection) makeTestCase() (*hrp.TCase, error) {
tCollection, err := c.load()
if err != nil {
return nil, err
}
teststeps, err := c.prepareTestSteps(tCollection)
if err != nil {
return nil, err
}
tCase := &hrp.TCase{
Config: c.prepareConfig(tCollection),
TestSteps: teststeps,
}
return tCase, nil
}
func (c *collection) load() (*TCollection, error) {
collection := &TCollection{}
err := builtin.LoadFile(c.path, collection)
if err != nil {
return nil, errors.Wrap(err, "load postman collection failed")
}
return collection, nil
}
func (c *collection) prepareConfig(tCollection *TCollection) *hrp.TConfig {
return hrp.NewConfig(tCollection.Info.Name).
SetVerifySSL(false)
}
func (c *collection) prepareTestSteps(tCollection *TCollection) ([]*hrp.TStep, error) {
// recursively convert collection items into a list
var itemList []TItem
for _, item := range tCollection.Items {
extractItemList(item, &itemList)
}
var steps []*hrp.TStep
for _, item := range itemList {
step, err := c.prepareTestStep(&item)
if err != nil {
return nil, err
}
steps = append(steps, step)
}
return steps, nil
}
func extractItemList(item TItem, itemList *[]TItem) {
// current item contains no other items and request is not empty
if len(item.Items) == 0 {
if !reflect.DeepEqual(item.Request, TRequest{}) {
*itemList = append(*itemList, item)
}
return
}
// look up all items inside
for _, i := range item.Items {
// append item name
i.Name = fmt.Sprintf("%s - %s", item.Name, i.Name)
extractItemList(i, itemList)
}
}
func (c *collection) prepareTestStep(item *TItem) (*hrp.TStep, error) {
log.Info().
Str("method", item.Request.Method).
Str("url", item.Request.URL.Raw).
Msg("convert teststep")
step := &tStep{
TStep: hrp.TStep{
Request: &hrp.Request{},
Validators: make([]interface{}, 0),
},
profile: c.profile,
patch: c.patch,
}
if err := step.makeRequestName(item); err != nil {
return nil, err
}
if err := step.makeRequestMethod(item); err != nil {
return nil, err
}
if err := step.makeRequestURL(item); err != nil {
return nil, err
}
if err := step.makeRequestParams(item); err != nil {
return nil, err
}
if err := step.makeRequestHeaders(item); err != nil {
return nil, err
}
if err := step.makeRequestCookies(item); err != nil {
return nil, err
}
if err := step.makeRequestBody(item); err != nil {
return nil, err
}
return &step.TStep, nil
}
type tStep struct {
hrp.TStep
profile map[string]interface{}
patch map[string]interface{}
}
// makeRequestName indicates the step name the same as item name
func (s *tStep) makeRequestName(item *TItem) error {
s.Name = item.Name
return nil
}
func (s *tStep) makeRequestMethod(item *TItem) error {
s.Request.Method = hrp.HTTPMethod(item.Request.Method)
return nil
}
func (s *tStep) makeRequestURL(item *TItem) error {
rawUrl := item.Request.URL.Raw
// parse path variables like ":path" in https://postman-echo.com/:path?k1=v1&k2=v2
for _, field := range item.Request.URL.Variable {
pathVar := ":" + field.Key
rawUrl = strings.Replace(rawUrl, pathVar, field.Value, -1)
}
u, err := url.Parse(rawUrl)
if err != nil {
return errors.Wrap(err, "parse URL error")
}
s.Request.URL = fmt.Sprintf("%s://%s", u.Scheme, u.Host+u.Path)
return nil
}
func (s *tStep) makeRequestParams(item *TItem) error {
s.Request.Params = make(map[string]interface{})
for _, field := range item.Request.URL.Query {
if field.Disabled {
continue
}
s.Request.Params[field.Key] = field.Value
}
return nil
}
func (s *tStep) updateRequestInfo(config string, key string) bool {
var m map[string]interface{}
switch config {
case configProfile:
m = s.profile
case configPatch:
m = s.patch
default:
return false
}
iRequestMap, existed := m[key]
if existed {
requestMap, ok := iRequestMap.(map[string]interface{})
if ok {
for k, v := range requestMap {
switch key {
case keyHeaders:
s.Request.Headers[k] = fmt.Sprintf("%v", v)
case keyCookies:
s.Request.Cookies[k] = fmt.Sprintf("%v", v)
}
}
return true
}
log.Warn().Interface(key, iRequestMap).Msgf("%v from %v is not a map, ignore!", key, config)
}
return false
}
func (s *tStep) makeRequestHeaders(item *TItem) error {
s.Request.Headers = make(map[string]string)
// override all headers according to the profile
if s.updateRequestInfo(configProfile, keyHeaders) {
return nil
}
// headers defined in postman collection
for _, field := range item.Request.Headers {
if field.Disabled || strings.EqualFold(field.Key, "cookie") {
continue
}
s.Request.Headers[field.Key] = field.Value
}
// create or update the headers indicated in the patch
s.updateRequestInfo(configPatch, keyHeaders)
return nil
}
func (s *tStep) makeRequestCookies(item *TItem) error {
s.Request.Cookies = make(map[string]string)
// override all cookies according to the profile
if s.updateRequestInfo(configProfile, keyCookies) {
return nil
}
// cookies defined in postman collection
for _, field := range item.Request.Headers {
if field.Disabled || !strings.EqualFold(field.Key, "cookie") {
continue
}
s.parseRequestCookiesMap(field.Value)
}
// create or update the cookies indicated in the patch
s.updateRequestInfo(configPatch, keyCookies)
return nil
}
func (s *tStep) parseRequestCookiesMap(cookies string) {
for _, cookie := range strings.Split(cookies, ";") {
cookie = strings.TrimSpace(cookie)
index := strings.Index(cookie, "=")
if index == -1 {
log.Warn().Str("cookie", cookie).Msg("cookie format invalid")
continue
}
s.Request.Cookies[cookie[0:index]] = cookie[index+1:]
}
}
func (s *tStep) makeRequestBody(item *TItem) error {
mode := item.Request.Body.Mode
if mode == "" {
return nil
}
switch mode {
case enumBodyRaw:
return s.makeRequestBodyRaw(item)
case enumBodyFormData:
return s.makeRequestBodyFormData(item)
case enumBodyUrlEncoded:
return s.makeRequestBodyUrlEncoded(item)
case enumBodyFile, enumBodyGraphQL:
return errors.Errorf("unsupported body type: %v", mode)
}
return nil
}
func (s *tStep) makeRequestBodyRaw(item *TItem) (err error) {
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("make request body raw failed: %v", p)
}
}()
// extract language type
iOptions := item.Request.Body.Options
iLanguage := iOptions.(map[string]interface{})["raw"]
languageType := iLanguage.(map[string]interface{})["language"].(string)
// make request body and indicate Content-Type
rawBody := item.Request.Body.Raw
if languageType == "json" {
var iBody interface{}
err = json.Unmarshal([]byte(rawBody), &iBody)
if err != nil {
return errors.Wrap(err, "make request body raw failed")
}
s.Request.Body = iBody
} else {
s.Request.Body = rawBody
}
s.Request.Headers["Content-Type"] = contentTypeMap[languageType]
return
}
func (s *tStep) makeRequestBodyFormData(item *TItem) (err error) {
defer func() {
if err != nil {
err = errors.Wrap(err, "make request body form-data failed")
}
}()
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
for _, field := range item.Request.Body.FormData {
if field.Disabled {
continue
}
// form data could be text or file
if field.Type == enumFieldTypeText {
err = writer.WriteField(field.Key, field.Value)
if err != nil {
return
}
} else if field.Type == enumFieldTypeFile {
err = writeFormDataFile(writer, &field)
if err != nil {
return
}
}
}
err = writer.Close()
s.Request.Body = payload.String()
s.Request.Headers["Content-Type"] = writer.FormDataContentType()
return
}
func writeFormDataFile(writer *multipart.Writer, field *TField) error {
file, err := os.Open(field.Src)
if err != nil {
return err
}
defer file.Close()
formFile, err := writer.CreateFormFile(field.Key, filepath.Base(field.Src))
if err != nil {
return err
}
_, err = io.Copy(formFile, file)
return err
}
func (s *tStep) makeRequestBodyUrlEncoded(item *TItem) error {
payloadMap := make(map[string]string)
for _, field := range item.Request.Body.URLEncoded {
if field.Disabled {
continue
}
payloadMap[field.Key] = field.Value
}
s.Request.Body = payloadMap
s.Request.Headers["Content-Type"] = "application/x-www-form-urlencoded"
return nil
}
// TODO makeValidate from example response
func (s *tStep) makeValidate(item *TItem) error {
return nil
}
@@ -0,0 +1,155 @@
package postman2case
import (
"testing"
"github.com/stretchr/testify/assert"
)
var (
collectionPath = "../../../../examples/data/postman2case/demo.json"
profilePath = "../../../../examples/data/postman2case/profile.yml"
patchPath = "../../../../examples/data/postman2case/patch.yml"
)
func TestGenJSON(t *testing.T) {
jsonPath, err := NewCollection(collectionPath).GenJSON()
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.NotEmpty(t, jsonPath) {
t.Fatal()
}
}
func TestGenYAML(t *testing.T) {
yamlPath, err := NewCollection(collectionPath).GenYAML()
if !assert.NoError(t, err) {
t.Fatal()
}
if !assert.NotEmpty(t, yamlPath) {
t.Fatal()
}
}
func TestLoadCollection(t *testing.T) {
tCollection, err := NewCollection(collectionPath).load()
if !assert.NoError(t, err) {
t.Fatal(err)
}
if !assert.Equal(t, "postman collection demo", tCollection.Info.Name) {
t.Fatal()
}
}
func TestMakeTestCase(t *testing.T) {
tCase, err := NewCollection(collectionPath).makeTestCase()
if !assert.NoError(t, err) {
t.Fatal()
}
// check name
if !assert.Equal(t, "postman collection demo", tCase.Config.Name) {
t.Fatal()
}
// check method
if !assert.EqualValues(t, "GET", tCase.TestSteps[0].Request.Method) {
t.Fatal()
}
if !assert.EqualValues(t, "POST", tCase.TestSteps[1].Request.Method) {
t.Fatal()
}
// check url
if !assert.Equal(t, "https://postman-echo.com/get", tCase.TestSteps[0].Request.URL) {
t.Fatal()
}
if !assert.Equal(t, "https://postman-echo.com/post", tCase.TestSteps[1].Request.URL) {
t.Fatal()
}
// check params
if !assert.Equal(t, "v1", tCase.TestSteps[0].Request.Params["k1"]) {
t.Fatal()
}
// check cookies (pass, postman collection doesn't contains cookies)
// check headers
if !assert.Contains(t, tCase.TestSteps[1].Request.Headers["Content-Type"], "multipart/form-data") {
t.Fatal()
}
if !assert.Equal(t, "application/x-www-form-urlencoded", tCase.TestSteps[2].Request.Headers["Content-Type"]) {
t.Fatal()
}
if !assert.Equal(t, "application/json", tCase.TestSteps[3].Request.Headers["Content-Type"]) {
t.Fatal()
}
if !assert.Equal(t, "text/plain", tCase.TestSteps[4].Request.Headers["Content-Type"]) {
t.Fatal()
}
if !assert.Equal(t, "HttpRunner", tCase.TestSteps[5].Request.Headers["User-Agent"]) {
t.Fatal()
}
// check body
if !assert.Equal(t, nil, tCase.TestSteps[0].Request.Body) {
t.Fatal()
}
if !assert.NotEmpty(t, tCase.TestSteps[1].Request.Body) {
t.Fatal()
}
if !assert.Equal(t, map[string]string{"k1": "v1", "k2": "v2"}, tCase.TestSteps[2].Request.Body) {
t.Fatal()
}
if !assert.Equal(t, map[string]interface{}{"k1": "v1", "k2": "v2"}, tCase.TestSteps[3].Request.Body) {
t.Fatal()
}
if !assert.Equal(t, "have a nice day", tCase.TestSteps[4].Request.Body) {
t.Fatal()
}
if !assert.Equal(t, nil, tCase.TestSteps[5].Request.Body) {
t.Fatal()
}
}
func TestMakeTestCaseWithProfile(t *testing.T) {
c := NewCollection(collectionPath)
c.SetProfile(profilePath)
tCase, err := c.makeTestCase()
if !assert.NoError(t, err) {
t.Fatal()
}
for _, step := range tCase.TestSteps {
if step.Request.Method == "GET" && !assert.Len(t, step.Request.Headers, 1) {
t.Fatal()
}
if step.Request.Method == "POST" && !assert.Len(t, step.Request.Headers, 2) {
t.Fatal()
}
if !assert.Equal(t, "all original headers will be overridden", step.Request.Headers["Header1"]) {
t.Fatal()
}
if !assert.Len(t, step.Request.Cookies, 1) {
t.Fatal()
}
if !assert.Equal(t, "all original cookies will be overridden", step.Request.Cookies["Cookie1"]) {
t.Fatal()
}
}
}
func TestMakeTestCaseWithPatch(t *testing.T) {
c := NewCollection(collectionPath)
c.SetPatch(patchPath)
tCase, err := c.makeTestCase()
if !assert.NoError(t, err) {
t.Fatal()
}
// create cookies Cookie1 indicated in patch
if !assert.Equal(t, "this cookie will be created or updated", tCase.TestSteps[0].Request.Cookies["Cookie1"]) {
t.Fatal()
}
// update header User-Agent indicated in patch
if !assert.Equal(t, "this header will be created or updated", tCase.TestSteps[5].Request.Headers["User-Agent"]) {
t.Fatal()
}
// pass header Connection which is not indicated in patch
if !assert.Equal(t, "close", tCase.TestSteps[5].Request.Headers["Connection"]) {
t.Fatal()
}
}