提交 182eb580 编写于 作者: m0_58228130's avatar m0_58228130

Merge remote-tracking branch 'origin/main' into main

......@@ -8,7 +8,6 @@ import (
logUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
stringUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/string"
"gopkg.in/ini.v1"
"path"
"path/filepath"
"reflect"
)
......@@ -39,7 +38,7 @@ func ReadFromFile(projectPath string) (config commDomain.ProjectConf) {
func SaveToFile(config commDomain.ProjectConf, projectPath string) (err error) {
pth := filepath.Join(projectPath, commConsts.ConfigDir, commConsts.ConfigFile)
fileUtils.MkDirIfNeeded(path.Dir(pth))
fileUtils.MkDirIfNeeded(filepath.Dir(pth))
config.Version = commConsts.ConfigVersion
......
......@@ -37,7 +37,10 @@ func ExecCase(ch chan int, sendOutputMsg, sendExecMsg func(info, isRunning strin
func ExecModule(ch chan int, sendOutputMsg, sendExecMsg func(info, isRunning string, wsMsg websocket.Message), req serverDomain.WsReq, msg websocket.Message) (
report commDomain.ZtfReport, pathMaxWidth int, err error) {
cases := zentaoUtils.GetCasesByModule(stringUtils.ParseInt(req.ProductId), stringUtils.ParseInt(req.ModuleId), req.ProjectPath)
cases, err := zentaoUtils.GetCasesByModule(stringUtils.ParseInt(req.ProductId), stringUtils.ParseInt(req.ModuleId), req.ProjectPath)
if err != nil {
return
}
if req.Seq != "" {
cases = analysisUtils.FilterCaseByResult(cases, req)
......@@ -49,7 +52,7 @@ func ExecModule(ch chan int, sendOutputMsg, sendExecMsg func(info, isRunning str
func ExecSuite(ch chan int, sendOutputMsg, sendExecMsg func(info, isRunning string, wsMsg websocket.Message), req serverDomain.WsReq, msg websocket.Message) (
report commDomain.ZtfReport, pathMaxWidth int, err error) {
cases := zentaoUtils.GetCasesBySuite(stringUtils.ParseInt(req.ProductId), stringUtils.ParseInt(req.SuiteId), req.ProjectPath)
cases, err := zentaoUtils.GetCasesBySuite(stringUtils.ParseInt(req.ProductId), stringUtils.ParseInt(req.SuiteId), req.ProjectPath)
if req.Seq != "" {
cases = analysisUtils.FilterCaseByResult(cases, req)
......@@ -61,7 +64,10 @@ func ExecSuite(ch chan int, sendOutputMsg, sendExecMsg func(info, isRunning stri
func ExecTask(ch chan int, sendOutputMsg, sendExecMsg func(info, isRunning string, wsMsg websocket.Message), req serverDomain.WsReq, msg websocket.Message) (
report commDomain.ZtfReport, pathMaxWidth int, err error) {
cases := zentaoUtils.GetCasesByTask(stringUtils.ParseInt(req.ProductId), stringUtils.ParseInt(req.TaskId), req.ProjectPath)
cases, err := zentaoUtils.GetCasesByTask(stringUtils.ParseInt(req.ProductId), stringUtils.ParseInt(req.TaskId), req.ProjectPath)
if err != nil {
return
}
if req.Seq != "" {
cases = analysisUtils.FilterCaseByResult(cases, req)
......
......@@ -42,20 +42,20 @@ func CommitBug(ztfBug commDomain.ZtfBug, projectPath string) (err error) {
bug := commDomain.ZentaoBug{}
copier.Copy(&bug, ztfBug)
ret, ok := httpUtils.Post(url, bug, true)
_, err = httpUtils.Post(url, bug, true)
msg := ""
if ok {
if err == nil {
msg = i118Utils.Sprintf("success_to_report_bug", ztfBug.Case)
} else {
msg = color.RedString(string(ret))
msg = color.RedString("commit bug failed, error: %s.", err.Error())
}
if commConsts.ComeFrom == "cmd" {
msgView, _ := commConsts.Cui.View("reportBugMsg")
msgView.Clear()
if ok {
if err == nil {
color.New(color.FgGreen).Fprintf(msgView, msg)
commConsts.Cui.DeleteView("submitInput")
......@@ -140,8 +140,8 @@ func GetBugFiledOptions(req commDomain.FuncResult, projectPath string) (
// field options
config := configUtils.LoadByProjectPath(projectPath)
ok := Login(config)
if !ok {
err = Login(config)
if err != nil {
return
}
......@@ -154,8 +154,8 @@ func GetBugFiledOptions(req commDomain.FuncResult, projectPath string) (
}
url := config.Url + GenApiUri("bug", "ajaxGetBugFieldOptions", params)
bytes, ok := httpUtils.Get(url)
if ok {
bytes, err := httpUtils.Get(url)
if err == nil {
jsonData := &simplejson.Json{}
jsonData, err = simplejson.NewJson(bytes)
......
......@@ -18,10 +18,10 @@ import (
"strings"
)
func GetCasesByModule(productId int, moduleId int, projectPath string) (cases []string) {
func GetCasesByModule(productId int, moduleId int, projectPath string) (cases []string, err error) {
config := configUtils.LoadByProjectPath(projectPath)
ok := Login(config)
if !ok {
err = Login(config)
if err != nil {
return
}
......@@ -39,10 +39,10 @@ func GetCasesByModule(productId int, moduleId int, projectPath string) (cases []
return
}
func GetCasesBySuite(productId int, suiteId int, projectPath string) (cases []string) {
func GetCasesBySuite(productId int, suiteId int, projectPath string) (cases []string, err error) {
config := configUtils.LoadByProjectPath(projectPath)
ok := Login(config)
if !ok {
err = Login(config)
if err != nil {
return
}
......@@ -60,10 +60,10 @@ func GetCasesBySuite(productId int, suiteId int, projectPath string) (cases []st
return
}
func GetCasesByTask(productId int, taskId int, projectPath string) (cases []string) {
func GetCasesByTask(productId int, taskId int, projectPath string) (cases []string, err error) {
config := configUtils.LoadByProjectPath(projectPath)
ok := Login(config)
if !ok {
err = Login(config)
if err != nil {
return
}
......@@ -93,9 +93,9 @@ func ListCaseByProduct(baseUrl string, productId int) []commDomain.ZtfCase {
}
url := baseUrl + GenApiUri("testcase", "browse", params)
dataStr, ok := httpUtils.Get(url)
dataStr, err := httpUtils.Get(url)
if ok {
if err == nil {
var product commDomain.ZtfProduct
json.Unmarshal(dataStr, &product)
......@@ -127,9 +127,9 @@ func ListCaseByModule(baseUrl string, productId, moduleId int) []commDomain.ZtfC
}
url := baseUrl + GenApiUri("testcase", "browse", params)
bytes, ok := httpUtils.Get(url)
bytes, err := httpUtils.Get(url)
if ok {
if err == nil {
var module commDomain.ZtfModule
json.Unmarshal(bytes, &module)
......@@ -161,9 +161,9 @@ func ListCaseBySuite(baseUrl string, productId, suiteId int) []commDomain.ZtfCas
}
url := baseUrl + GenApiUri("testsuite", "view", params)
bytes, ok := httpUtils.Get(url)
bytes, err := httpUtils.Get(url)
if ok {
if err == nil {
var suite commDomain.ZtfSuite
json.Unmarshal(bytes, &suite)
......@@ -196,9 +196,9 @@ func ListCaseByTask(baseUrl string, productId, taskId int) []commDomain.ZtfCase
}
url := baseUrl + GenApiUri("testtask", "cases", params)
bytes, ok := httpUtils.Get(url)
bytes, err := httpUtils.Get(url)
if ok {
if err == nil {
var task commDomain.ZtfTask
json.Unmarshal(bytes, &task)
......@@ -246,9 +246,9 @@ func GetCaseById(baseUrl string, caseId string) commDomain.ZtfCase {
}
url := baseUrl + GenApiUri("testcase", "view", params)
bytes, ok := httpUtils.Get(url)
bytes, err := httpUtils.Get(url)
if ok {
if err == nil {
var csw commDomain.ZtfCaseWrapper
json.Unmarshal(bytes, &csw)
......@@ -260,11 +260,11 @@ func GetCaseById(baseUrl string, caseId string) commDomain.ZtfCase {
}
func CommitCase(caseId int, title string,
stepMap maps.Map, stepTypeMap maps.Map, expectMap maps.Map, projectPath string) {
stepMap maps.Map, stepTypeMap maps.Map, expectMap maps.Map, projectPath string) (err error) {
config := configUtils.LoadByProjectPath(projectPath)
ok := Login(config)
if !ok {
err = Login(config)
if err != nil {
return
}
......@@ -283,7 +283,10 @@ func CommitCase(caseId int, title string,
"stepType": commonUtils.LinkedMapToMap(stepTypeMap),
"expects": commonUtils.LinkedMapToMap(expectMap)}
json, _ := json.Marshal(requestObj)
json, err := json.Marshal(requestObj)
if err != nil {
return
}
if commConsts.Verbose {
logUtils.Infof(string(json))
......@@ -296,11 +299,13 @@ func CommitCase(caseId int, title string,
}
if yes {
_, ok = httpUtils.Post(url, requestObj, true)
if ok {
_, err = httpUtils.Post(url, requestObj, true)
if err == nil {
logUtils.Infof(i118Utils.Sprintf("success_to_commit_case", caseId) + "\n")
}
}
return
}
func fieldMapToListOrderByInt(mp map[string]interface{}) []commDomain.BugOption {
......
package zentaoUtils
import (
commConsts "github.com/aaronchen2k/deeptest/internal/comm/consts"
"errors"
commDomain "github.com/aaronchen2k/deeptest/internal/comm/domain"
configUtils "github.com/aaronchen2k/deeptest/internal/comm/helper/config"
httpUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/http"
......@@ -21,21 +21,22 @@ func CommitResult(report commDomain.ZtfReport, productId, taskId string, project
report.BuildUrl = os.Getenv("BUILD_URL")
// remove it, will cause zentao testtask not display
if commConsts.ComeFrom != "cmd" {
report.TestType = ""
}
//if commConsts.ComeFrom != "cmd" {
// report.TestType = ""
//}
config := configUtils.LoadByProjectPath(projectPath)
Login(config)
url := config.Url + GenApiUri("ci", "commitResult", "")
ret, ok := httpUtils.Post(url, report, false)
ret, err := httpUtils.Post(url, report, false)
msg := ""
if ok {
if err == nil {
msg = color.GreenString(i118Utils.Sprintf("success_to_submit_test_result"))
} else {
msg = color.RedString(string(ret))
msg = color.RedString("commit result failed, error: %s.", err.Error())
err = errors.New(string(ret))
}
logUtils.Info(msg)
......
......@@ -16,11 +16,11 @@ import (
"strings"
)
func Login(config commDomain.ProjectConf) bool {
ok := GetConfig(config.Url)
if !ok {
func Login(config commDomain.ProjectConf) (err error) {
err = GetConfig(config.Url)
if err != nil {
logUtils.Infof(i118Utils.Sprintf("fail_to_login"))
return false
return
}
uri := ""
......@@ -36,12 +36,12 @@ func Login(config commDomain.ProjectConf) bool {
params["password"] = config.Password
var bodyBytes []byte
bodyBytes, ok = httpUtils.PostStr(url, params)
if !ok || (ok && strings.Index(string(bodyBytes), "title") > 0) { // use PostObject to login again for new system
_, ok = httpUtils.Post(url, params, true)
bodyBytes, err = httpUtils.PostStr(url, params)
if err != nil || (err == nil && strings.Index(string(bodyBytes), "title") > 0) { // use PostObject to login again for new system
_, err = httpUtils.Post(url, params, true)
}
if ok {
if err == nil {
if commConsts.Verbose {
logUtils.Info(i118Utils.Sprintf("success_to_login"))
}
......@@ -49,18 +49,18 @@ func Login(config commDomain.ProjectConf) bool {
logUtils.Errorf(i118Utils.Sprintf("fail_to_login"))
}
return ok
return
}
func GetConfig(baseUrl string) bool {
func GetConfig(baseUrl string) (err error) {
//if commConsts.RequestType != "" {
// return true
//}
url := baseUrl + "?mode=getconfig"
bytes, ok := httpUtils.Get(url)
if !ok {
return false
bytes, err := httpUtils.Get(url)
if err != nil {
return
}
json, _ := simplejson.NewJson(bytes)
......@@ -79,12 +79,12 @@ func GetConfig(baseUrl string) bool {
uri = "index.php?m=user&f=login&t=json"
}
url = baseUrl + uri
bytes, ok = httpUtils.Get(url)
if !ok {
return false
bytes, err = httpUtils.Get(url)
if err != nil {
return
}
return true
return
}
func ListLang() (langs []serverDomain.ZentaoLang, err error) {
......@@ -102,7 +102,10 @@ func ListProduct(projectPath string) (products []serverDomain.ZentaoProduct, err
return
}
Login(config)
err = Login(config)
if err != nil {
return
}
// $productID = 0, $branch = 0, $browseType = '', $param = 0, $storyType = 'story',
// $orderBy = '', $recTotal = 0, $recPerPage = 20, $pageID = 1, $projectID = 0)
......@@ -114,15 +117,15 @@ func ListProduct(projectPath string) (products []serverDomain.ZentaoProduct, err
}
url := config.Url + GenApiUri("product", "browse", params)
bytes, ok := httpUtils.Get(url)
bytes, err := httpUtils.Get(url)
if !ok {
if err != nil {
err = errors.New("请检查项目配置")
return
}
jsn, _ := simplejson.NewJson(bytes)
productMap, _ := jsn.Get("products").Map()
productMap, err := jsn.Get("products").Map()
for key, val := range productMap {
id, _ := strconv.Atoi(key)
......@@ -134,9 +137,12 @@ func ListProduct(projectPath string) (products []serverDomain.ZentaoProduct, err
func ListModuleByProduct(productId int, projectPath string) (modules []serverDomain.ZentaoModule, err error) {
config := configUtils.LoadByProjectPath(projectPath)
Login(config)
// tree-browse-1-story.html#app=product
err = Login(config)
if err != nil {
return
}
// tree-browse-1-story.html#app=product
params := ""
if commConsts.RequestType == commConsts.PathInfo {
params = fmt.Sprintf("%d-story", productId)
......@@ -147,9 +153,8 @@ func ListModuleByProduct(productId int, projectPath string) (modules []serverDom
url := config.Url + GenApiUri("tree", "browse", params)
url += "#app=product"
bytes, ok := httpUtils.Get(url)
if !ok {
err = errors.New("tree-browse-story fail")
bytes, err := httpUtils.Get(url)
if err != nil {
return
}
......@@ -166,7 +171,10 @@ func ListModuleByProduct(productId int, projectPath string) (modules []serverDom
func ListModuleForCase(productId int, projectPath string) (modules []serverDomain.ZentaoModule, err error) {
config := configUtils.LoadByProjectPath(projectPath)
Login(config)
err = Login(config)
if err != nil {
return
}
// tree-browse-1-case-0-0-qa.html
params := ""
......@@ -179,9 +187,8 @@ func ListModuleForCase(productId int, projectPath string) (modules []serverDomai
url := config.Url + GenApiUri("tree", "browse", params)
url += "#app=product"
bytes, ok := httpUtils.Get(url)
if !ok {
err = errors.New("tree-browse-story fail")
bytes, err := httpUtils.Get(url)
if err != nil {
return
}
......@@ -218,7 +225,10 @@ func GenModuleData(mp map[string]interface{}, modules *[]serverDomain.ZentaoModu
func ListSuiteByProduct(productId int, projectPath string) (suites []serverDomain.ZentaoSuite, err error) {
config := configUtils.LoadByProjectPath(projectPath)
Login(config)
err = Login(config)
if err != nil {
return
}
// $productID = 0, $orderBy = 'id_asc', $recTotal = 0, $recPerPage = 20, $pageID = 1
params := ""
......@@ -230,8 +240,8 @@ func ListSuiteByProduct(productId int, projectPath string) (suites []serverDomai
url := config.Url + GenApiUri("testsuite", "browse", params)
bytes, ok := httpUtils.Get(url)
if !ok {
bytes, err := httpUtils.Get(url)
if err != nil {
err = errors.New("testsuite-browse fail")
return
}
......@@ -253,7 +263,10 @@ func ListSuiteByProduct(productId int, projectPath string) (suites []serverDomai
func ListTaskByProduct(productId int, projectPath string) (tasks []serverDomain.ZentaoTask, err error) {
config := configUtils.LoadByProjectPath(projectPath)
Login(config)
err = Login(config)
if err != nil {
return
}
// $productID = 0, $branch = '', $type = 'local,totalStatus', $orderBy = 'id_asc', $recTotal = 0, $recPerPage = 20, $pageID = 1, $beginTime = 0, $endTime = 0)
params := ""
......@@ -264,9 +277,9 @@ func ListTaskByProduct(productId int, projectPath string) (tasks []serverDomain.
}
url := config.Url + GenApiUri("testtask", "browse", params)
bytes, ok := httpUtils.Get(url)
bytes, err := httpUtils.Get(url)
if !ok {
if err != nil {
err = errors.New("testsuite-browse fail")
return
}
......
......@@ -121,7 +121,8 @@ func IgnoreFile(path string) bool {
path = filepath.Base(path)
if strings.Index(path, ".") == 0 ||
path == "bin" || path == "release" || path == "logs" || path == "xdoc" {
path == "bin" || path == "release" || path == "logs" || path == "xdoc" ||
path == "log" || path == "conf" {
return true
} else {
return false
......
......@@ -2,8 +2,9 @@ package fileUtils
import (
"fmt"
_i118Utils "github.com/aaronchen2k/deeptest/internal/pkg/lib/i118"
_logUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
"github.com/aaronchen2k/deeptest/internal/pkg/lib/i118"
"github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
"github.com/fatih/color"
"io/ioutil"
"net/http"
"path/filepath"
......@@ -17,11 +18,11 @@ func Download(url string, dst string) (err error) {
var data []byte
data, err = HTTPDownload(url)
if err == nil {
_logUtils.Info(_i118Utils.Sprintf("file_downloaded", url))
logUtils.Info(i118Utils.Sprintf("file_downloaded", url))
err = WriteDownloadFile(dst, data)
if err == nil {
_logUtils.Info(_i118Utils.Sprintf("file_download_saved", url, dst))
logUtils.Info(i118Utils.Sprintf("file_download_saved", url, dst))
}
}
......@@ -31,12 +32,12 @@ func Download(url string, dst string) (err error) {
func HTTPDownload(uri string) ([]byte, error) {
res, err := http.Get(uri)
if err != nil {
_logUtils.Error(err.Error())
logUtils.Infof(color.RedString("download file failed, error: %s.", err.Error()))
}
defer res.Body.Close()
d, err := ioutil.ReadAll(res.Body)
if err != nil {
_logUtils.Error(err.Error())
logUtils.Infof(color.RedString("read downloaded file failed, error: %s.", err.Error()))
}
return d, err
}
......@@ -44,7 +45,7 @@ func HTTPDownload(uri string) ([]byte, error) {
func WriteDownloadFile(dst string, d []byte) error {
err := ioutil.WriteFile(dst, d, 0444)
if err != nil {
_logUtils.Error(err.Error())
logUtils.Infof(color.RedString("write download file failed, error: %s.", err.Error()))
}
return err
}
......@@ -2,8 +2,8 @@ package fileUtils
import (
"bytes"
_i118Utils "github.com/aaronchen2k/deeptest/internal/pkg/lib/i118"
_logUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
"github.com/aaronchen2k/deeptest/internal/pkg/lib/i118"
"github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
"io"
"io/ioutil"
"mime/multipart"
......@@ -33,13 +33,13 @@ func Upload(url string, files []string, extraParams map[string]string) {
defer resp.Body.Close()
if err != nil {
_logUtils.Error(_i118Utils.Sprintf("fail_to_upload_files", err.Error()))
logUtils.Error(i118Utils.Sprintf("fail_to_upload_files", err.Error()))
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
_logUtils.Error(_i118Utils.Sprintf("fail_to_parse_upload_response", err.Error()))
logUtils.Error(i118Utils.Sprintf("fail_to_parse_upload_response", err.Error()))
}
_logUtils.Info(_i118Utils.Sprintf("upload_status", resp.Status, string(respBody)))
logUtils.Info(i118Utils.Sprintf("upload_status", resp.Status, string(respBody)))
}
......@@ -2,12 +2,14 @@ package httpUtils
import (
"encoding/json"
"errors"
"fmt"
commConsts "github.com/aaronchen2k/deeptest/internal/comm/consts"
i118Utils "github.com/aaronchen2k/deeptest/internal/pkg/lib/i118"
"github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
serverDomain "github.com/aaronchen2k/deeptest/internal/server/modules/v1/domain"
"github.com/ajg/form"
"github.com/fatih/color"
"github.com/yosssi/gohtml"
"io/ioutil"
"net/http"
......@@ -15,7 +17,7 @@ import (
"strings"
)
func Get(url string) (ret []byte, ok bool) {
func Get(url string) (ret []byte, err error) {
if strings.Index(url, "mode=getconfig") < 0 {
url = AddToken(url)
}
......@@ -25,21 +27,24 @@ func Get(url string) (ret []byte, ok bool) {
client := &http.Client{}
req, reqErr := http.NewRequest("GET", url, nil)
if reqErr != nil {
logUtils.Error(reqErr.Error())
ok = false
req, err := http.NewRequest("GET", url, nil)
if err != nil {
logUtils.Infof(color.RedString("get request failed, error: %s.", err.Error()))
return
}
resp, err := client.Do(req)
if err != nil {
logUtils.Infof(color.RedString("get request failed, error: %s.", err.Error()))
return
}
resp, respErr := client.Do(req)
if respErr != nil {
logUtils.Error(respErr.Error())
ok = false
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
logUtils.Infof(color.RedString("read response failed, error ", err.Error()))
return
}
bodyBytes, _ := ioutil.ReadAll(resp.Body)
if commConsts.Verbose {
logUtils.Infof(i118Utils.Sprintf("request_response"))
logUtils.Infof(logUtils.ConvertUnicode(bodyBytes))
......@@ -47,8 +52,8 @@ func Get(url string) (ret []byte, ok bool) {
defer resp.Body.Close()
var zentaoResp serverDomain.ZentaoResp
jsonErr := json.Unmarshal(bodyBytes, &zentaoResp)
if jsonErr != nil {
err = json.Unmarshal(bodyBytes, &zentaoResp)
if err != nil {
if strings.Index(string(bodyBytes), "<html>") > -1 {
if commConsts.Verbose {
logUtils.Errorf(i118Utils.Sprintf("request_response") + " HTML - " + gohtml.FormatWithLineNo(string(bodyBytes)))
......@@ -56,7 +61,7 @@ func Get(url string) (ret []byte, ok bool) {
return
} else {
if commConsts.Verbose {
logUtils.Infof(jsonErr.Error())
logUtils.Infof(color.RedString("unmarshal response failed, error: %s.", err.Error()))
}
return
}
......@@ -67,16 +72,17 @@ func Get(url string) (ret []byte, ok bool) {
status := zentaoResp.Status
if status == "" { // 非嵌套结构
ret = bodyBytes
ok = true
} else { // 嵌套结构
ret = []byte(zentaoResp.Data)
ok = status == "success"
if status != "success" {
err = errors.New(zentaoResp.Data)
}
}
return
}
func Post(url string, data interface{}, useFormFormat bool) (ret []byte, ok bool) {
func Post(url string, data interface{}, useFormFormat bool) (ret []byte, err error) {
url = AddToken(url)
if commConsts.Verbose {
......@@ -86,7 +92,7 @@ func Post(url string, data interface{}, useFormFormat bool) (ret []byte, ok bool
dataBytes, err := json.Marshal(data)
if err != nil {
logUtils.Error(err.Error())
logUtils.Infof(color.RedString("marshal request failed, error: %s.", err.Error()))
return
}
......@@ -103,24 +109,24 @@ func Post(url string, data interface{}, useFormFormat bool) (ret []byte, ok bool
logUtils.Infof(dataStr)
}
req, reqErr := http.NewRequest("POST", url, strings.NewReader(dataStr))
if reqErr != nil {
logUtils.Error(reqErr.Error())
req, err := http.NewRequest("POST", url, strings.NewReader(dataStr))
if err != nil {
logUtils.Infof(color.RedString("post request failed, error: %s.", err.Error()))
return
}
//req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, respErr := client.Do(req)
if respErr != nil {
logUtils.Error(respErr.Error())
resp, err := client.Do(req)
if err != nil {
logUtils.Infof(color.RedString("post request failed, error: %s.", err.Error()))
return
}
bodyBytes, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
logUtils.Error(ioErr.Error())
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
logUtils.Infof(color.RedString("read response failed, error: %s.", err.Error()))
return
}
......@@ -131,12 +137,12 @@ func Post(url string, data interface{}, useFormFormat bool) (ret []byte, ok bool
defer resp.Body.Close()
ret, ok = GetRespErr(bodyBytes, url)
ret, err = GetRespErr(bodyBytes, url)
return
}
func PostStr(url string, params map[string]string) (ret []byte, ok bool) {
func PostStr(url string, params map[string]string) (ret []byte, err error) {
url = AddToken(url)
if commConsts.Verbose {
......@@ -159,28 +165,31 @@ func PostStr(url string, params map[string]string) (ret []byte, ok bool) {
logUtils.Infof(paramStr)
}
req, reqErr := http.NewRequest("POST", url, strings.NewReader(paramStr))
if reqErr != nil {
req, err := http.NewRequest("POST", url, strings.NewReader(paramStr))
if err != nil {
if commConsts.Verbose {
logUtils.Infof(reqErr.Error())
logUtils.Infof(color.RedString("post string failed, error: %s.", err.Error()))
}
ok = false
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("cookie", commConsts.SessionVar+"="+commConsts.SessionId)
resp, respErr := client.Do(req)
if respErr != nil {
resp, err := client.Do(req)
if err != nil {
if commConsts.Verbose {
logUtils.Infof(respErr.Error())
logUtils.Infof(color.RedString("post string failed, error: %s.", err.Error()))
}
ok = false
return
}
bodyBytes, _ := ioutil.ReadAll(resp.Body)
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
logUtils.Infof(color.RedString("read response failed, error ", err.Error()))
return
}
if commConsts.Verbose {
logUtils.Infof(i118Utils.Sprintf("request_response"))
logUtils.Infof(logUtils.ConvertUnicode(bodyBytes))
......@@ -235,7 +244,7 @@ func AddToken(url string) (ret string) {
return
}
func GetRespErr(bytes []byte, url string) (ret []byte, ok bool) {
func GetRespErr(bytes []byte, url string) (ret []byte, err error) {
ret = bytes
if len(bytes) == 0 {
......@@ -243,14 +252,14 @@ func GetRespErr(bytes []byte, url string) (ret []byte, ok bool) {
}
var zentaoResp serverDomain.ZentaoResp
jsonErr := json.Unmarshal(bytes, &zentaoResp)
if jsonErr != nil {
err = json.Unmarshal(bytes, &zentaoResp)
if err != nil {
err = errors.New("Wrong Zentao response, unmarshal to serverDomain.ZentaoResp failed, error " + err.Error())
if commConsts.Verbose {
if strings.Index(url, "login") < 0 { // jsonErr caused by login request return a html
logUtils.Infof(jsonErr.Error())
logUtils.Infof(color.RedString(err.Error()))
}
}
ok = false
return
}
......@@ -258,18 +267,18 @@ func GetRespErr(bytes []byte, url string) (ret []byte, ok bool) {
status := zentaoResp.Status
if status != "" {
ret = []byte(zentaoResp.Data)
ok = status == "success"
if status == "success" {
err = errors.New(zentaoResp.Data)
}
return
}
// 非嵌套结构,map[result:success]
var respData = serverDomain.ZentaoRespData{}
err := json.Unmarshal(bytes, &respData)
err = json.Unmarshal(bytes, &respData)
if err == nil && (respData.Result != "" && respData.Result != "success") {
ok = false
} else {
ok = true
err = errors.New(string(bytes))
}
return
......
......@@ -63,7 +63,7 @@ func ExeShellInDirWithPid(cmdStr string, dir string) (ret string, err error, pid
err = cmd.Run()
if err != nil {
logUtils.Error(i118Utils.Sprintf("fail_to_exec_command", cmdStr, cmd.Dir, err))
logUtils.Errorf(i118Utils.Sprintf("fail_to_exec_command", cmdStr, cmd.Dir, err))
}
pid = cmd.Process.Pid
......
......@@ -41,6 +41,43 @@ func InitLog() {
}
}
// 执行日志,用于具体的测试执行
func InitExecLog(projectPath string) {
commConsts.ExecLogDir = logUtils.GetLogDir(projectPath)
config := getLogConfig()
config.EncoderConfig.EncodeLevel = nil
// print to test log file
logPath := filepath.Join(commConsts.ExecLogDir, commConsts.LogText)
if commonUtils.IsWin() {
logPath = filepath.Join("winfile:///", logPath)
zap.RegisterSink("winfile", newWinFileSink)
}
config.OutputPaths = []string{logPath}
var err error
logUtils.LoggerExecFile, err = config.Build()
if err != nil {
log.Println("init exec file logger fail " + err.Error())
}
config.DisableCaller = true
config.DisableStacktrace = true
config.EncoderConfig.TimeKey = ""
// print to test result file
logPathResult := filepath.Join(commConsts.ExecLogDir, commConsts.ResultText)
if commonUtils.IsWin() {
logPathResult = filepath.Join("winfile:///", logPathResult)
zap.RegisterSink("winfile", newWinFileSink)
}
config.OutputPaths = []string{logPathResult}
logUtils.LoggerExecResult, err = config.Build()
if err != nil {
log.Println("init exec result logger fail " + err.Error())
}
}
func getLogConfig() (config zap.Config) {
var level zapcore.Level
......@@ -103,33 +140,6 @@ func getLogConfig() (config zap.Config) {
return
}
// 执行日志,用于具体的测试执行
func InitExecLog(projectPath string) {
config := getLogConfig()
commConsts.ExecLogDir = logUtils.GetLogDir(projectPath)
// print to exec log file
config.EncoderConfig.EncodeLevel = nil
config.OutputPaths = []string{filepath.Join(commConsts.ExecLogDir, commConsts.LogText)}
var err error
logUtils.LoggerExecFile, err = config.Build()
if err != nil {
log.Println("init exec file logger fail " + err.Error())
}
config.DisableCaller = true
config.DisableStacktrace = true
config.EncoderConfig.TimeKey = ""
// print to test result file
config.OutputPaths = []string{filepath.Join(commConsts.ExecLogDir, commConsts.ResultText)}
logUtils.LoggerExecResult, err = config.Build()
if err != nil {
log.Println("init exec result logger fail " + err.Error())
}
}
func newWinFileSink(u *url.URL) (zap.Sink, error) {
// Remove leading slash left by url.Parse()
var name string
......
......@@ -4,6 +4,7 @@ import (
"github.com/aaronchen2k/deeptest/internal/comm/consts"
"github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
"github.com/aaronchen2k/deeptest/internal/server/modules/v1/model"
"github.com/fatih/color"
"gorm.io/driver/sqlite"
"gorm.io/gorm/schema"
"gorm.io/plugin/dbresolver"
......@@ -38,7 +39,7 @@ func GetDB() *gorm.DB {
})
if err != nil {
logUtils.Info(err.Error())
logUtils.Infof(color.RedString("open db failed, error: %s.", err.Error()))
}
_ = db.Use(
......@@ -56,7 +57,7 @@ func GetDB() *gorm.DB {
model.Models...,
)
if err != nil {
logUtils.Info(err.Error())
logUtils.Infof(color.RedString("migrate models failed, error: %s.", err.Error()))
}
return db
......
......@@ -3,13 +3,9 @@ package repo
import (
"errors"
"fmt"
"github.com/aaronchen2k/deeptest/internal/pkg/domain"
commonUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/common"
logUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
"github.com/aaronchen2k/deeptest/internal/server/core/dao"
serverDomain "github.com/aaronchen2k/deeptest/internal/server/modules/v1/domain"
"github.com/aaronchen2k/deeptest/internal/server/modules/v1/model"
"go.uber.org/zap"
"github.com/fatih/color"
"gorm.io/gorm"
)
......@@ -21,46 +17,13 @@ func NewProjectRepo() *ProjectRepo {
return &ProjectRepo{}
}
func (r *ProjectRepo) Paginate(req serverDomain.ProjectReqPaginate) (data domain.PageData, err error) {
var count int64
db := r.DB.Model(&model.Project{}).Where("NOT deleted")
if req.Keywords != "" {
db = db.Where("name LIKE ?", fmt.Sprintf("%%%s%%", req.Keywords))
}
if req.Enabled != "" {
db = db.Where("disabled = ?", commonUtils.IsDisable(req.Enabled))
}
err = db.Count(&count).Error
if err != nil {
logUtils.Errorf("count project error", zap.String("error:", err.Error()))
return
}
pos := make([]*model.Project, 0)
err = db.
Scopes(dao.PaginateScope(req.Page, req.PageSize, req.Order, req.Field)).
Find(&pos).Error
if err != nil {
logUtils.Errorf("query project error", zap.String("error:", err.Error()))
return
}
data.Populate(pos, count, req.Page, req.PageSize)
return
}
func (r *ProjectRepo) FindById(id uint) (po model.Project, err error) {
err = r.DB.Model(&model.Project{}).
Where("id = ?", id).
Where("NOT deleted").
First(&po).Error
if err != nil {
logUtils.Errorf("find project by id error", zap.String("error:", err.Error()))
logUtils.Errorf(color.RedString("find project by id failed, error: %s.", err.Error()))
return
}
......@@ -75,7 +38,7 @@ func (r *ProjectRepo) Create(project model.Project) (id uint, err error) {
err = r.DB.Model(&model.Project{}).Create(&project).Error
if err != nil {
logUtils.Errorf("add project error", zap.String("error:", err.Error()))
logUtils.Errorf(color.RedString("create project failed, error: %s.", err.Error()))
return 0, err
}
......@@ -87,7 +50,7 @@ func (r *ProjectRepo) Create(project model.Project) (id uint, err error) {
func (r *ProjectRepo) Update(id uint, project model.Project) error {
err := r.DB.Model(&model.Project{}).Where("id = ?", id).Updates(&project).Error
if err != nil {
logUtils.Errorf("update project error", zap.String("error:", err.Error()))
logUtils.Errorf(color.RedString("update project failed, error: %s.", err.Error()))
return err
}
......@@ -99,7 +62,7 @@ func (r *ProjectRepo) DeleteByPath(pth string) (err error) {
Delete(&model.Project{}).
Error
if err != nil {
logUtils.Errorf("delete project by id error", zap.String("error:", err.Error()))
logUtils.Errorf(color.RedString("delete project failed, error: %s.", err.Error()))
return
}
......@@ -114,10 +77,6 @@ func (r *ProjectRepo) FindByName(name string, ids ...uint) (po model.Project, er
db.Where("id != ?", ids[0])
}
err = db.First(&po).Error
if err != nil {
logUtils.Errorf("find project by name error", zap.String("name:", name), zap.Uints("ids:", ids), zap.String("error:", err.Error()))
return
}
return
}
......
......@@ -6,6 +6,7 @@ import (
fileUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/file"
logUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
serverDomain "github.com/aaronchen2k/deeptest/internal/server/modules/v1/domain"
"github.com/fatih/color"
"io/ioutil"
"mime/multipart"
"path/filepath"
......@@ -14,7 +15,6 @@ import (
"github.com/kataras/iris/v12"
"github.com/snowlyg/helper/dir"
"github.com/snowlyg/helper/str"
"go.uber.org/zap"
)
var (
......@@ -38,12 +38,12 @@ func (s *FileService) UploadFile(ctx iris.Context, fh *multipart.FileHeader) (ir
path := filepath.Join(dir.GetCurrentAbPath(), "static", "upload", "images")
err = dir.InsureDir(path)
if err != nil {
logUtils.Errorf("文件上传失败", zap.String("dir.InsureDir", err.Error()))
logUtils.Infof(color.RedString("file upload failed, error: %s.", err.Error()))
return nil, err
}
_, err = ctx.SaveFormFile(fh, filepath.Join(path, filename))
if err != nil {
logUtils.Errorf("文件上传失败", zap.String("ctx.SaveFormFile", "保存文件到本地"))
logUtils.Infof(color.RedString("file upload failed, error: %s.", err.Error()))
return nil, err
}
......@@ -103,13 +103,13 @@ func (s *FileService) addDir(pth string, parent *serverDomain.TestAsset) (dirNod
func GetFileName(name string) (string, error) {
fns := strings.Split(strings.TrimLeft(name, "./"), ".")
if len(fns) != 2 {
logUtils.Errorf("文件上传失败", zap.String("trings.Split", name))
logUtils.Infof(color.RedString("file upload failed, error: wrong file name %s.", name))
return "", ErrEmpty
}
ext := fns[1]
md5, err := dir.MD5(name)
if err != nil {
logUtils.Errorf("文件上传失败", zap.String("dir.MD5", err.Error()))
logUtils.Errorf(color.RedString("file upload failed, error: %s.", name))
return "", err
}
return str.Join(md5, ".", ext), nil
......
......@@ -7,7 +7,6 @@ import (
commDomain "github.com/aaronchen2k/deeptest/internal/comm/domain"
configUtils "github.com/aaronchen2k/deeptest/internal/comm/helper/config"
scriptUtils "github.com/aaronchen2k/deeptest/internal/comm/helper/script"
"github.com/aaronchen2k/deeptest/internal/pkg/domain"
commonUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/common"
fileUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/file"
logUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
......@@ -25,17 +24,6 @@ func NewProjectService() *ProjectService {
return &ProjectService{}
}
func (s *ProjectService) Paginate(req serverDomain.ProjectReqPaginate) (ret domain.PageData, err error) {
ret, err = s.ProjectRepo.Paginate(req)
if err != nil {
return
}
return
}
func (s *ProjectService) FindById(id uint) (model.Project, error) {
return s.ProjectRepo.FindById(id)
}
......
......@@ -10,6 +10,7 @@ import (
i118Utils "github.com/aaronchen2k/deeptest/internal/pkg/lib/i118"
langUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/lang"
logUtils "github.com/aaronchen2k/deeptest/internal/pkg/lib/log"
"github.com/fatih/color"
"path/filepath"
"strconv"
)
......@@ -48,7 +49,7 @@ func (s *SyncService) SyncFromZentao(settings commDomain.SyncSettings, projectPa
if err == nil {
logUtils.Infof(i118Utils.Sprintf("success_to_generate", count, targetDir))
} else {
logUtils.Infof(err.Error())
logUtils.Infof(color.RedString(err.Error()))
}
} else {
if !loginFail {
......
......@@ -18,8 +18,8 @@ func (s *TestCaseService) LoadTestCases(productId, moduleId, suiteId, taskId int
config := configUtils.LoadByProjectPath(projectPath)
ok := zentaoUtils.Login(config)
if !ok {
err := zentaoUtils.Login(config)
if err != nil {
loginFail = true
return
}
......
limit:
disable: true
limit: 0
burst: 5
max-size: 1024
maxsize: 1024
system:
version: 3.0
language: zh
level: debug
addr: :8085
static-prefix: /upload
static-path: /static/upload
web-path: ./static/dist
time-format: "2006-01-02 15:04:05"
zap:
level: info
format: console
prefix: '[OP-ONLINE] '
director: log
link-name: latest_log
show-line: true
encode-level: ""
stacktrace-key: stacktrace
log-in-console: true
......@@ -11,8 +11,6 @@
"svgo": "svgo -f src/assets/iconsvg --config=src/assets/iconsvg/svgo.yml"
},
"dependencies": {
"@ckeditor/ckeditor5-build-decoupled-document": "^23.1.0",
"@ckeditor/ckeditor5-vue": "^2.0.1",
"@toast-ui/editor": "^2.5.3",
"ant-design-vue": "^2.2.8",
"axios": "^0.21.4",
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册