ktgo/pkg/testlib/testlib.go
2024-02-19 16:53:07 +03:00

127 строки
2,5 КиБ
Go

package testlib
import (
"context"
"fmt"
"math"
"net"
"strconv"
"time"
"github.com/cucumber/godog"
. "github.com/onsi/gomega"
)
var Be = Equal
func NoErr(err error) {
ExpectWithOffset(1, err).NotTo(HaveOccurred())
}
func NoErr2(err error, ошибка string) bool {
if ошибка == "" {
ExpectWithOffset(1, err).To(BeNil(), ошибка)
return false
} else {
ExpectWithOffset(1, err.Error()).To(Be(ошибка), ошибка)
return true
}
}
var Ok = NoErr
var Ok2 = NoErr2
func Yes(b bool) {
ExpectWithOffset(1, b).To(BeTrue())
}
func YesText(b bool, text string) {
ExpectWithOffset(1, b).To(BeTrue(), text)
}
var TestResult error
func InitializeGomegaForGodog(ctx *godog.ScenarioContext) {
ctx.StepContext().Before(func(ctx context.Context, st *godog.Step) (context.Context, error) {
TestResult = nil
return ctx, nil
})
ctx.StepContext().After(func(ctx context.Context, st *godog.Step, status godog.StepResultStatus, err error) (context.Context, error) {
return ctx, TestResult
})
RegisterFailHandler(func(message string, callerSkip ...int) {
// remember only the expectation failed first
// anything thereafter is not to be believed
if TestResult == nil {
TestResult = fmt.Errorf(message)
}
})
}
func Sleep(m time.Duration) {
time.Sleep(m * time.Millisecond)
}
func Atoi(in string) int {
res, err := strconv.Atoi(in)
Ok(err)
return res
}
func Atof(in string) float64 {
res, err := strconv.ParseFloat(in, 64)
Ok(err)
res = RoundPlusMinus(res)
return res
}
func RoundPlusMinus(number float64) float64 {
return RoundFloat(number, 4)
}
func RoundFloat(number float64, roundingTempDigitsCount int) float64 {
temp := math.Pow(10, float64(roundingTempDigitsCount))
return math.Round(number*temp) / temp
}
func Stof(znak string, s1, s2 int) float64 {
l := fmt.Sprintf("%v.%v", s1, s2)
r := Atof(l)
if znak == "-" {
r = -r
}
return r
}
func WaitForOpenPort(sp string) {
start_time_limit := time.Now().Add(5 * time.Second)
for {
time.Sleep(5 * time.Millisecond)
Conn, err := net.Dial("tcp4", "localhost:"+sp)
if err == nil {
Conn.Close()
break
}
if start_time_limit.Before(time.Now()) {
Ω(false).To(BeTrue(), "Timeout to wait for process port: "+sp)
}
}
}
func WaitForOpenPortInt(p int) {
sp := fmt.Sprint(p)
WaitForOpenPort(sp)
}
func IsTrue(in string) bool {
switch in {
case "t", "true", "+", "да":
return true
}
return false
}
func Истина(in string) bool {
switch in {
case "t", "true", "+", "да":
return true
}
return false
}