convert

package
v0.0.0-...-dd20c9c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 16, 2022 License: Apache-2.0 Imports: 20 Imported by: 0

README

hrp convert

快速上手

$ hrp convert -h
convert to JSON/YAML/gotest/pytest testcases

Usage:
  hrp convert $path... [flags]

Flags:
  -h, --help                help for convert
  -d, --output-dir string   specify output directory, default to the same dir with har file
  -p, --profile string      specify profile path to override headers (except for auto-generated headers) and cookies
      --to-gotest           convert to gotest scripts (TODO)
      --to-json             convert to JSON scripts (default true)
      --to-pytest           convert to pytest scripts
      --to-yaml             convert to YAML scripts

Global Flags:
      --log-json           set log to json format
  -l, --log-level string   set log level (default "INFO")

hrp convert 指令用于将 HAR/Postman/JMeter/Swagger 文件或 curl/Apache ab 指令转化为 JSON/YAML/gotest/pytest 形态的测试用例,同时也支持测试用例各个形态之间的相互转化。

该指令所有选项的详细说明如下:

  1. --to-json / --to-yaml / --to-gotest / --to-pytest 用于将输入转化为对应形态的测试用例,四个选项中最多只能指定一个,如果不指定则默认会将输入转化为 JSON 形态的测试用例
  2. --output-dir 后接测试用例的期望输出目录的路径,用于将转换生成的测试用例输出到对应的文件夹
  3. --profile 后接 profile 配置文件的路径,目前支持替换(不存在则会创建)或者覆盖输入的外部脚本/测试用例中的 HeadersCookies 信息,profile 文件的后缀可以为 json/yaml/yml,下面给出两类 profile 配置文件的示例:
  • 根据 profile 替换指定的 HeadersCookies 信息
headers:
  Header1: "this header will be created or updated"
cookies:
  Cookie1: "this cookie will be created or updated"
  • 根据 profile 覆盖原有的 HeadersCookies 信息
override: true
headers:
  Header1: "all original headers will be overridden"
cookies:
  Cookie1: "all original cookies will be overridden"

注意事项

  1. 输出的测试用例文件名格式为 Postman 工程文件名称(不带拓展名) + _test + .json/.yaml/.go/.py 后缀,如果该文件已经存在则会进行覆盖
  2. hrp convert 可以自动识别输入类型,因此不需要通过选项来手动制定输入类型,如遇到无法识别、不支持或转换失败的情况,则会输出错误日志并跳过,不会影响其他转换过程的正常进行
  3. 在 profile 文件中,指定 override 字段为 false/true 可以选择修改模式为替换/覆盖。需要注意的是,如果不指定该字段则 profile 的默认修改模式为替换模式
  4. 输入为 JSON/YAML 测试用例时,良好兼容 Golang/Python 双引擎的请求体、断言格式细微差异,输出的 JSON/YAML 则统一采用 Golang 引擎的风格

转换流程图

hrp convert 的转换过程流程图如下: flow chart

开发进度

hrp convert 当前的开发进度如下:

from \ to JSON YAML GoTest PyTest
HAR
Postman
JMeter
Swagger
curl
Apache ab
JSON
YAML
GoTest
PyTest

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(outputType OutputType, outputDir, profilePath string, args []string)

Types

type Browser

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"`
}

Browser that created the log

type 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"`
}

Cache contains info about a request coming from browser cache.

type CacheObject

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"`
}

CacheObject is used by both beforeRequest and afterRequest

type CaseHar

type CaseHar struct {
	Log Log `json:"log"`
}

CaseHar is a container type for deserialization

type CasePostman

type CasePostman struct {
	Info  TInfo   `json:"info"`
	Items []TItem `json:"item"`
}

CasePostman represents the postman exported file

type Content

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"`
}

Content describes details about response content (embedded in <response> object).

type ConverterHAR

type ConverterHAR struct {
	// contains filtered or unexported fields
}

func NewConverterHAR

func NewConverterHAR(converter *TCaseConverter) *ConverterHAR

func (*ConverterHAR) Struct

func (c *ConverterHAR) Struct() *TCaseConverter

func (*ConverterHAR) ToGoTest

func (c *ConverterHAR) ToGoTest() (string, error)

func (*ConverterHAR) ToJSON

func (c *ConverterHAR) ToJSON() (string, error)

func (*ConverterHAR) ToPyTest

func (c *ConverterHAR) ToPyTest() (string, error)

func (*ConverterHAR) ToYAML

func (c *ConverterHAR) ToYAML() (string, error)

type ConverterJSON

type ConverterJSON struct {
	// contains filtered or unexported fields
}

func NewConverterJSON

func NewConverterJSON(converter *TCaseConverter) *ConverterJSON

func (*ConverterJSON) MakePyTestScript

func (c *ConverterJSON) MakePyTestScript() (string, error)

func (*ConverterJSON) Struct

func (c *ConverterJSON) Struct() *TCaseConverter

func (*ConverterJSON) ToGoTest

func (c *ConverterJSON) ToGoTest() (string, error)

func (*ConverterJSON) ToJSON

func (c *ConverterJSON) ToJSON() (string, error)

func (*ConverterJSON) ToPyTest

func (c *ConverterJSON) ToPyTest() (string, error)

func (*ConverterJSON) ToYAML

func (c *ConverterJSON) ToYAML() (string, error)

type ConverterPostman

type ConverterPostman struct {
	// contains filtered or unexported fields
}

func NewConverterPostman

func NewConverterPostman(converter *TCaseConverter) *ConverterPostman

func (*ConverterPostman) Struct

func (c *ConverterPostman) Struct() *TCaseConverter

func (*ConverterPostman) ToGoTest

func (c *ConverterPostman) ToGoTest() (string, error)

func (*ConverterPostman) ToJSON

func (c *ConverterPostman) ToJSON() (string, error)

func (*ConverterPostman) ToPyTest

func (c *ConverterPostman) ToPyTest() (string, error)

func (*ConverterPostman) ToYAML

func (c *ConverterPostman) ToYAML() (string, error)

type ConverterYAML

type ConverterYAML struct {
	// contains filtered or unexported fields
}

func NewConverterYAML

func NewConverterYAML(converter *TCaseConverter) *ConverterYAML

func (*ConverterYAML) Struct

func (c *ConverterYAML) Struct() *TCaseConverter

func (*ConverterYAML) ToGoTest

func (c *ConverterYAML) ToGoTest() (string, error)

func (*ConverterYAML) ToJSON

func (c *ConverterYAML) ToJSON() (string, error)

func (*ConverterYAML) ToPyTest

func (c *ConverterYAML) ToPyTest() (string, error)

func (*ConverterYAML) ToYAML

func (c *ConverterYAML) ToYAML() (string, error)
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"`
}

Cookie contains list of all cookies (used in <request> and <response> objects).

type Creator

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"`
}

Creator contains information about the log creator application

type Entry

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"`
}

Entry is a unique, optional Reference to the parent page. Leave out this field if the application does not support grouping by pages.

type ICaseConverter

type ICaseConverter interface {
	Struct() *TCaseConverter
	ToJSON() (string, error)
	ToYAML() (string, error)
	ToGoTest() (string, error)
	ToPyTest() (string, error)
}

ICaseConverter represents all kinds of case converters which could convert case into JSON/YAML/gotest/pytest format

type InputType

type InputType int
const (
	InputTypeUnknown InputType = iota // default input type: unknown
	InputTypeHAR
	InputTypePostman
	InputTypeSwagger
	InputTypeJMeter
	InputTypeJSON
	InputTypeYAML
	InputTypeGoTest
	InputTypePyTest
)

func (InputType) String

func (inputType InputType) String() string

type Log

type Log struct {

	// 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"`
}

Log represents the root of the exported data. This object MUST be present and its name MUST be "log".

type NVP

type NVP struct {
	Name    string `json:"name"`
	Value   string `json:"value"`
	Comment string `json:"comment,omitempty"`
}

NVP is simply a name/value pair with a comment

type OutputType

type OutputType int
const (
	OutputTypeJSON OutputType = iota // default output type: JSON
	OutputTypeYAML
	OutputTypeGoTest
	OutputTypePyTest
)

func (OutputType) String

func (outputType OutputType) String() string

type Page

type Page struct {

	// 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"`
}

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 PageTiming

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"`
}

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 PageTimings

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"`
}

PageTimings describes various phases within request-response round trip. All times are specified in milliseconds.

type PostData

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"`
}

PostData describes posted data, if any (embedded in <request> object).

type PostParam

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"`
}

PostParam is a list of posted parameters, if any (embedded in <postData> object).

type Profile

type Profile struct {
	Override bool              `json:"override" yaml:"override"`
	Headers  map[string]string `json:"headers" yaml:"headers"`
	Cookies  map[string]string `json:"cookies" yaml:"cookies"`
}

Profile is used to override or update(create if not existed) original headers and cookies

type 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"`
}

Request contains detailed info about performed request.

type 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"`
}

Response contains detailed info about the response.

type TBody

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"`
}

type TCaseConverter

type TCaseConverter struct {
	InputPath   string
	OutputDir   string
	Profile     *Profile
	InputType   InputType
	OutputType  OutputType
	CaseHAR     *CaseHar
	CasePostman *CasePostman
	CaseSwagger *spec.Swagger
	TCase       *hrp.TCase
}

TCaseConverter holds the common properties of case converter

func NewTCaseConverter

func NewTCaseConverter(path string) (tCaseConverter *TCaseConverter)

func (*TCaseConverter) SetOutputDir

func (c *TCaseConverter) SetOutputDir(dir string)

func (*TCaseConverter) SetProfile

func (c *TCaseConverter) SetProfile(path string)

func (*TCaseConverter) ToGoTest

func (c *TCaseConverter) ToGoTest() (string, error)

func (*TCaseConverter) ToPyTest

func (c *TCaseConverter) ToPyTest() (string, error)

type TField

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 TInfo

type TInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Schema      string `json:"schema"`
}

TInfo gives information about the collection

type TItem

type TItem struct {
	Items     []TItem     `json:"item"`
	Name      string      `json:"name"`
	Request   TRequest    `json:"request"`
	Responses []TResponse `json:"response"`
}

TItem contains the detail information of request and expected responses item could be defined recursively

type TRequest

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

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

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 TestResult

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"`
}

TestResult contains results for an individual HTTP request

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL