feat: replace log with logrus

This commit is contained in:
debugtalk
2021-10-17 11:51:49 +08:00
parent ef535a6f6b
commit 2fd45a5d63
10 changed files with 59 additions and 59 deletions

View File

@@ -5,9 +5,9 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"path/filepath"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
@@ -24,14 +24,14 @@ func (tc *TestCase) ToTCase() (*TCase, error) {
func (tc *TCase) Dump2JSON(path string) error {
path, err := filepath.Abs(path)
if err != nil {
log.Printf("convert absolute path error: %v, path: %v", err, path)
log.Errorf("convert absolute path error: %v, path: %v", err, path)
return err
}
log.Printf("dump testcase to json path: %s", path)
log.Infof("dump testcase to json path: %s", path)
file, _ := json.MarshalIndent(tc, "", " ")
err = ioutil.WriteFile(path, file, 0644)
if err != nil {
log.Printf("dump json path error: %v", err)
log.Errorf("dump json path error: %v", err)
return err
}
return nil
@@ -40,10 +40,10 @@ func (tc *TCase) Dump2JSON(path string) error {
func (tc *TCase) Dump2YAML(path string) error {
path, err := filepath.Abs(path)
if err != nil {
log.Printf("convert absolute path error: %v, path: %v", err, path)
log.Errorf("convert absolute path error: %v, path: %v", err, path)
return err
}
log.Printf("dump testcase to yaml path: %s", path)
log.Infof("dump testcase to yaml path: %s", path)
// init yaml encoder
buffer := new(bytes.Buffer)
@@ -58,7 +58,7 @@ func (tc *TCase) Dump2YAML(path string) error {
err = ioutil.WriteFile(path, buffer.Bytes(), 0644)
if err != nil {
log.Printf("dump yaml path error: %v", err)
log.Errorf("dump yaml path error: %v", err)
return err
}
return nil
@@ -67,14 +67,14 @@ func (tc *TCase) Dump2YAML(path string) error {
func loadFromJSON(path string) (*TCase, error) {
path, err := filepath.Abs(path)
if err != nil {
log.Printf("convert absolute path error: %v, path: %v", err, path)
log.Errorf("convert absolute path error: %v, path: %v", err, path)
return nil, err
}
log.Printf("load testcase from json path: %s", path)
log.Infof("load testcase from json path: %s", path)
file, err := ioutil.ReadFile(path)
if err != nil {
log.Printf("dump json path error: %v", err)
log.Errorf("dump json path error: %v", err)
return nil, err
}
@@ -88,14 +88,14 @@ func loadFromJSON(path string) (*TCase, error) {
func loadFromYAML(path string) (*TCase, error) {
path, err := filepath.Abs(path)
if err != nil {
log.Printf("convert absolute path error: %v, path: %v", err, path)
log.Errorf("convert absolute path error: %v, path: %v", err, path)
return nil, err
}
log.Printf("load testcase from yaml path: %s", path)
log.Infof("load testcase from yaml path: %s", path)
file, err := ioutil.ReadFile(path)
if err != nil {
log.Printf("dump yaml path error: %v", err)
log.Errorf("dump yaml path error: %v", err)
return nil, err
}
@@ -118,7 +118,7 @@ func (tc *TCase) ToTestCase() (*TestCase, error) {
step: step,
})
} else {
log.Printf("[convertTestCase] unexpected step: %+v", step)
log.Warnf("[convertTestCase] unexpected step: %+v", step)
}
}
return testCase, nil

View File

@@ -1,7 +1,6 @@
package cmd
import (
"log"
"testing"
"github.com/spf13/cobra/doc"
@@ -13,6 +12,6 @@ import (
func TestGenMarkdownTree(t *testing.T) {
err := doc.GenMarkdownTree(cmd.RootCmd, "./cmd/")
if err != nil {
log.Fatal(err)
t.Fatal(err)
}
}

1
go.mod
View File

@@ -13,6 +13,7 @@ require (
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pkg/errors v0.9.1
github.com/shirou/gopsutil v3.21.8+incompatible // indirect
github.com/sirupsen/logrus v1.8.1
github.com/spf13/cobra v1.2.1
github.com/stretchr/testify v1.7.0
github.com/tklauser/go-sysconf v0.3.9 // indirect

3
go.sum
View File

@@ -231,6 +231,8 @@ github.com/shirou/gopsutil v3.21.8+incompatible h1:sh0foI8tMRlCidUJR+KzqWYWxrkuu
github.com/shirou/gopsutil v3.21.8+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
@@ -397,6 +399,7 @@ golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

View File

@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
@@ -13,6 +12,7 @@ import (
"strings"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/httprunner/hrp"
)
@@ -120,7 +120,7 @@ func (h *HAR) prepareTestSteps() ([]*hrp.TStep, error) {
}
func (h *HAR) prepareTestStep(entry *Entry) (*hrp.TStep, error) {
log.Printf("[prepareTestStep] %v %v", entry.Request.Method, entry.Request.URL)
log.Infof("[prepareTestStep] %v %v", entry.Request.Method, entry.Request.URL)
tStep := &TStep{
TStep: hrp.TStep{
Request: &hrp.TRequest{},
@@ -164,7 +164,7 @@ func (s *TStep) makeRequestURL(entry *Entry) error {
u, err := url.Parse(entry.Request.URL)
if err != nil {
log.Printf("makeRequestURL error: %v", err)
log.Errorf("makeRequestURL error: %v", err)
return err
}
s.Request.URL = fmt.Sprintf("%s://%s", u.Scheme, u.Hostname()+u.Path)
@@ -211,7 +211,7 @@ func (s *TStep) makeRequestBody(entry *Entry) error {
var body interface{}
err := json.Unmarshal([]byte(entry.Request.PostData.Text), &body)
if err != nil {
log.Printf("makeRequestBody error: %v", err)
log.Errorf("makeRequestBody error: %v", err)
return err
}
s.Request.Body = body

View File

@@ -1,7 +1,6 @@
package har2case
import (
"log"
"testing"
"github.com/stretchr/testify/assert"
@@ -14,7 +13,6 @@ var (
func TestGenJSON(t *testing.T) {
jsonPath, err := NewHAR(harPath).GenJSON()
log.Printf("jsonPath: %v, err: %v", jsonPath, err)
if !assert.NoError(t, err) {
t.Fail()
}
@@ -25,7 +23,6 @@ func TestGenJSON(t *testing.T) {
func TestGenYAML(t *testing.T) {
yamlPath, err := NewHAR(harPath2).GenYAML()
log.Printf("yamlPath: %v, err: %v", yamlPath, err)
if !assert.NoError(t, err) {
t.Fail()
}

View File

@@ -1,8 +1,7 @@
package cmd
import (
"log"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/httprunner/hrp/har2case"
@@ -38,7 +37,7 @@ var har2caseCmd = &cobra.Command{
}
outputFiles = append(outputFiles, outputPath)
}
log.Printf("output: %v", outputFiles)
log.Infof("output: %v", outputFiles)
return nil
},
}

View File

@@ -3,14 +3,15 @@ package hrp
import (
"encoding/json"
"fmt"
"log"
"net/url"
"reflect"
"regexp"
"strings"
"github.com/httprunner/hrp/builtin"
"github.com/maja42/goval"
log "github.com/sirupsen/logrus"
"github.com/httprunner/hrp/builtin"
)
func parseStep(step IStep, config *TConfig) *TStep {
@@ -22,13 +23,13 @@ func parseStep(step IStep, config *TConfig) *TStep {
func buildURL(baseURL, stepURL string) string {
uConfig, err := url.Parse(baseURL)
if err != nil {
log.Fatalf("[buildURL] baseURL: %v, error: %v", baseURL, err)
log.Errorf("[buildURL] baseURL: %v, error: %v", baseURL, err)
return ""
}
uStep, err := uConfig.Parse(stepURL)
if err != nil {
log.Fatalf("[buildURL] baseURL: %v, error: %v", baseURL, err)
log.Errorf("[buildURL] baseURL: %v, error: %v", baseURL, err)
return ""
}
@@ -184,7 +185,7 @@ func parseString(raw string, variablesMapping map[string]interface{}) (interface
matchStartPosition += len(funcMatched[0])
parsedString += fmt.Sprintf("%v", result)
remainedString = raw[matchStartPosition:]
log.Printf("[parseString] parsedString: %v, matchStartPosition: %v", parsedString, matchStartPosition)
log.Infof("[parseString] parsedString: %v, matchStartPosition: %v", parsedString, matchStartPosition)
continue
}
@@ -210,7 +211,7 @@ func parseString(raw string, variablesMapping map[string]interface{}) (interface
matchStartPosition += len(varMatched[0])
parsedString += fmt.Sprintf("%v", varValue)
remainedString = raw[matchStartPosition:]
log.Printf("[parseString] parsedString: %v, matchStartPosition: %v", parsedString, matchStartPosition)
log.Infof("[parseString] parsedString: %v, matchStartPosition: %v", parsedString, matchStartPosition)
continue
}
@@ -283,21 +284,21 @@ func callFunc(funcName string, arguments ...interface{}) (interface{}, error) {
// function argument type not match and not convertible
err := fmt.Errorf("function %s argument %d type is neither match nor convertible, expect %v, actual %v",
funcName, index, expectArgumentType, actualArgumentType)
log.Printf("[callFunction] error: %s", err.Error())
log.Errorf("[callFunction] error: %s", err.Error())
return nil, err
}
// convert argument to expect type
argumentsValue[index] = argumentValue.Convert(expectArgumentType)
}
log.Printf("[callFunction] func: %v, input arguments: %v", funcName, arguments)
log.Infof("[callFunction] func: %v, input arguments: %v", funcName, arguments)
resultValues := funcValue.Call(argumentsValue)
log.Printf("[callFunction] output values: %v", resultValues)
log.Infof("[callFunction] output values: %v", resultValues)
if len(resultValues) > 1 {
// function should return at most one value
err := fmt.Errorf("function %s should return at most one value", funcName)
log.Printf("[callFunction] error: %s", err.Error())
log.Errorf("[callFunction] error: %s", err.Error())
return nil, err
}
@@ -309,7 +310,7 @@ func callFunc(funcName string, arguments ...interface{}) (interface{}, error) {
// return one value
// convert reflect.Value to interface{}
result := resultValues[0].Interface()
log.Printf("[callFunction] output result: %+v(%T)", result, result)
log.Infof("[callFunction] output result: %+v(%T)", result, result)
return result, nil
}
@@ -327,7 +328,7 @@ func literalEval(raw string) (interface{}, error) {
// eval string to number
result, err := eval.Evaluate(raw, nil, nil)
if err != nil {
log.Printf("[literalEval] eval %s error: %s", raw, err.Error())
log.Errorf("[literalEval] eval %s error: %s", raw, err.Error())
return raw, err
}
return result, nil
@@ -378,7 +379,7 @@ func parseVariables(variables map[string]interface{}) (map[string]interface{}, e
// variables = {"token": "abc$token"}
// variables = {"key": ["$key", 2]}
if _, ok := extractVarsSet[varName]; ok {
log.Printf("[parseVariables] variable self reference error: %v", variables)
log.Errorf("[parseVariables] variable self reference error: %v", variables)
return variables, fmt.Errorf("variable self reference: %v", varName)
}
@@ -393,7 +394,7 @@ func parseVariables(variables map[string]interface{}) (map[string]interface{}, e
}
}
if len(undefinedVars) > 0 {
log.Printf("[parseVariables] variable not defined error: %v", undefinedVars)
log.Errorf("[parseVariables] variable not defined error: %v", undefinedVars)
return variables, fmt.Errorf("variable not defined: %v", undefinedVars)
}
@@ -406,7 +407,7 @@ func parseVariables(variables map[string]interface{}) (map[string]interface{}, e
traverseRounds += 1
// check if circular reference exists
if traverseRounds > len(variables) {
log.Printf("[parseVariables] circular reference error, break infinite loop!")
log.Errorf("[parseVariables] circular reference error, break infinite loop!")
return variables, fmt.Errorf("circular reference")
}
}

View File

@@ -2,12 +2,12 @@ package hrp
import (
"encoding/json"
"log"
"strings"
"testing"
"github.com/imroc/req"
"github.com/jmespath/go-jmespath"
log "github.com/sirupsen/logrus"
"github.com/httprunner/hrp/builtin"
)
@@ -45,7 +45,7 @@ func NewResponseObject(t *testing.T, resp *req.Resp) (*ResponseObject, error) {
respObjMetaBytes, _ := json.Marshal(respObjMeta)
var data interface{}
if err := json.Unmarshal(respObjMetaBytes, &data); err != nil {
log.Printf("[NewResponseObject] convert respObjMeta to interface{} error: %v, respObjMeta: %v",
log.Errorf("[NewResponseObject] convert respObjMeta to interface{} error: %v, respObjMeta: %v",
err, string(respObjMetaBytes))
return nil, err
}
@@ -77,8 +77,8 @@ func (v *ResponseObject) Extract(extractors map[string]string) map[string]interf
extractMapping := make(map[string]interface{})
for key, value := range extractors {
extractedValue := v.searchJmespath(value)
log.Printf("[extract] %s => %v", value, extractedValue)
log.Printf("[setVariable] %s = %v", key, extractedValue)
log.Infof("[extract] %s => %v", value, extractedValue)
log.Infof("[setVariable] %s = %v", key, extractedValue)
extractMapping[key] = extractedValue
}
@@ -112,7 +112,7 @@ func (v *ResponseObject) Validate(validators []TValidator, variablesMapping map[
// do assertion
result := assertFunc(v.t, expectValue, checkValue)
log.Printf("[assert] %s <%s> %v => %v", checkItem, assertMethod, expectValue, result)
log.Infof("[assert] %s <%s> %v => %v", checkItem, assertMethod, expectValue, result)
if !result {
v.t.Fail()
}
@@ -123,7 +123,7 @@ func (v *ResponseObject) Validate(validators []TValidator, variablesMapping map[
func (v *ResponseObject) searchJmespath(expr string) interface{} {
checkValue, err := jmespath.Search(expr, v.respObjMeta)
if err != nil {
log.Printf("[searchJmespath] jmespath.Search error: %v", err)
log.Errorf("[searchJmespath] jmespath.Search error: %v", err)
return expr // jmespath not found, return the expression
}
return checkValue

View File

@@ -1,12 +1,12 @@
package hrp
import (
"log"
"net/http"
"testing"
"github.com/imroc/req"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// run API test with default configs
@@ -29,19 +29,19 @@ type Runner struct {
}
func (r *Runner) WithTestingT(t *testing.T) *Runner {
log.Printf("[init] WithTestingT: %v", t)
log.Infof("[init] WithTestingT: %v", t)
r.t = t
return r
}
func (r *Runner) SetDebug(debug bool) *Runner {
log.Printf("[init] SetDebug: %v", debug)
log.Infof("[init] SetDebug: %v", debug)
r.debug = debug
return r
}
func (r *Runner) SetProxyUrl(proxyUrl string) *Runner {
log.Printf("[init] SetProxyUrl: %s", proxyUrl)
log.Infof("[init] SetProxyUrl: %s", proxyUrl)
r.client.SetProxyUrl(proxyUrl)
return r
}
@@ -50,11 +50,11 @@ func (r *Runner) Run(testcases ...ITestCase) error {
for _, iTestCase := range testcases {
testcase, err := iTestCase.ToTestCase()
if err != nil {
log.Printf("[Run] testcase.ToStruct() error: %v", err)
log.Errorf("[Run] testcase.ToStruct() error: %v", err)
return err
}
if err := r.runCase(testcase); err != nil {
log.Printf("[Run] runCase error: %v", err)
log.Errorf("[Run] runCase error: %v", err)
return err
}
}
@@ -67,7 +67,7 @@ func (r *Runner) runCase(testcase *TestCase) error {
return err
}
log.Printf("Start to run testcase: %v", config.Name)
log.Infof("Start to run testcase: %v", config.Name)
extractedVariables := make(map[string]interface{})
@@ -81,7 +81,7 @@ func (r *Runner) runCase(testcase *TestCase) error {
// parse step variables
parsedVariables, err := parseVariables(stepVariables)
if err != nil {
log.Printf("[parseConfig] parse variables: %v, error: %v", config.Variables, err)
log.Errorf("[parseConfig] parse variables: %v, error: %v", config.Variables, err)
return err
}
step.ToStruct().Variables = parsedVariables
@@ -100,10 +100,10 @@ func (r *Runner) runCase(testcase *TestCase) error {
}
func (r *Runner) runStep(step IStep, config *TConfig) (stepData *StepData, err error) {
log.Printf("run step [%v] begin >>>>>>", step.Name())
log.Infof("run step [%v] begin >>>>>>", step.Name())
if tc, ok := step.(*testcaseWithOptionalArgs); ok {
// run referenced testcase
log.Printf("run referenced testcase: %v", tc.step.Name)
log.Infof("run referenced testcase: %v", tc.step.Name)
// TODO: override testcase config
stepData, err = r.runStepTestCase(tc.step)
if err != nil {
@@ -117,7 +117,7 @@ func (r *Runner) runStep(step IStep, config *TConfig) (stepData *StepData, err e
return
}
}
log.Printf("run step [%v] end, success: %v, responseLength: %v <<<<<<\n",
log.Infof("run step [%v] end, success: %v, responseLength: %v <<<<<<\n",
step.Name(), stepData.Success, stepData.ResponseLength)
return
}
@@ -213,7 +213,7 @@ func (r *Runner) parseConfig(config *TConfig) error {
// parse config variables
parsedVariables, err := parseVariables(config.Variables)
if err != nil {
log.Printf("[parseConfig] parse variables: %v, error: %v", config.Variables, err)
log.Errorf("[parseConfig] parse variables: %v, error: %v", config.Variables, err)
return err
}
config.Variables = parsedVariables