feat: data-driven.

This commit is contained in:
徐聪
2021-12-29 15:25:57 +08:00
parent 83923affa8
commit 11ea588ee2
2 changed files with 39 additions and 38 deletions

View File

@@ -2,15 +2,12 @@ package hrp
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v3"
"io/ioutil"
"path/filepath"
)
func (tc *TCase) Dump2JSON(path string) error {
@@ -96,36 +93,6 @@ func loadFromYAML(path string) (*TCase, error) {
return tc, err
}
func LoadFromCSV(path string) []map[string]string {
path, err := filepath.Abs(path)
if err != nil {
log.Error().Str("path", path).Err(err).Msg("convert absolute path failed")
panic(err)
}
log.Info().Str("path", path).Msg("load csv file")
file, err := ioutil.ReadFile(path)
if err != nil {
log.Error().Err(err).Msg("load csv file failed")
panic(err)
}
r := csv.NewReader(strings.NewReader(string(file)))
content, err := r.ReadAll()
if err != nil {
log.Error().Err(err).Msg("parse csv file failed")
panic(err)
}
var result []map[string]string
for i := 1; i < len(content); i++ {
row := make(map[string]string)
for j := 0; j < len(content[i]); j++ {
row[content[0][j]] = content[i][j]
}
result = append(result, row)
}
return result
}
func (tc *TCase) ToTestCase() (*TestCase, error) {
testCase := &TestCase{
Config: &Config{cfg: tc.Config},

View File

@@ -2,10 +2,14 @@ package builtin
import (
"crypto/md5"
"encoding/csv"
"encoding/hex"
"github.com/httprunner/hrp"
"github.com/rs/zerolog/log"
"io/ioutil"
"math"
"math/rand"
"path/filepath"
"strings"
"time"
)
@@ -15,8 +19,8 @@ var Functions = map[string]interface{}{
"gen_random_string": genRandomString, // call with one argument
"max": math.Max, // call with two arguments
"md5": MD5,
"parameterize": hrp.LoadFromCSV,
"P": hrp.LoadFromCSV,
"parameterize": LoadFromCSV,
"P": LoadFromCSV,
}
func init() {
@@ -47,3 +51,33 @@ func MD5(str string) string {
hasher.Write([]byte(str))
return hex.EncodeToString(hasher.Sum(nil))
}
func LoadFromCSV(path string) []map[string]string {
path, err := filepath.Abs(path)
if err != nil {
log.Error().Str("path", path).Err(err).Msg("convert absolute path failed")
panic(err)
}
log.Info().Str("path", path).Msg("load csv file")
file, err := ioutil.ReadFile(path)
if err != nil {
log.Error().Err(err).Msg("load csv file failed")
panic(err)
}
r := csv.NewReader(strings.NewReader(string(file)))
content, err := r.ReadAll()
if err != nil {
log.Error().Err(err).Msg("parse csv file failed")
panic(err)
}
var result []map[string]string
for i := 1; i < len(content); i++ {
row := make(map[string]string)
for j := 0; j < len(content[i]); j++ {
row[content[0][j]] = content[i][j]
}
result = append(result, row)
}
return result
}