util/util_test.go

50 lines
1.6 KiB
Go
Raw Normal View History

2024-10-11 09:57:41 +08:00
package util_test
import (
"bytes"
"fmt"
"testing"
"time"
"apigo.cc/gojs"
_ "apigo.cc/gojs/util"
"github.com/ssgo/u"
)
func TestHash(t *testing.T) {
vm := gojs.New()
vm.RunCode("import util from 'apigo.cc/gojs/util'")
testIsSame(vm, t, "util.md5('hello 123')", u.MD5([]byte("hello 123")))
testIsSame(vm, t, "util.base64(util.md5('hello 123'))", u.MD5Base64("hello 123"))
testIsSame(vm, t, "util.hex(util.md5('hello 123'))", u.MD5String("hello 123"))
testIsSame(vm, t, "util.sha1('hello 123')", u.Sha1([]byte("hello 123")))
testIsSame(vm, t, "util.sha256('hello 123')", u.Sha256([]byte("hello 123")))
testIsSame(vm, t, "util.sha512('hello 123')", u.Sha512([]byte("hello 123")))
testIsSame(vm, t, "util.json('hello 123')", u.Json("hello 123"))
testIsSame(vm, t, "util.yaml('hello 123')", u.Yaml("hello 123"))
testIsSame(vm, t, "util.aes('hello 123','12345678901234567','12345678901234567')", u.EncryptAes("hello 123", []byte("12345678901234567"), []byte("12345678901234567")))
testIsSame(vm, t, "util.gzip('hello 123')", u.GzipN([]byte("hello 123")))
tm, _ := time.ParseInLocation("2006-01-02 15:04:05", "2024-01-01 00:00:00", time.Local)
testIsSame(vm, t, "util.fromDatetime('2024-01-01 00:00:00')", tm.UnixMilli())
}
func testIsSame(vm *gojs.Runtime, t *testing.T, code string, checkValue any) {
r, err := vm.RunCode(code)
if err != nil {
t.Fatal(code, err)
return
}
if data, ok := r.([]byte); ok {
if !bytes.Equal(data, u.Bytes(r)) {
t.Fatal(code, r)
return
}
} else {
if r != checkValue {
t.Fatal(code, r, checkValue)
return
}
}
fmt.Println(u.Green(code))
}