forked from electricdusk/rushlink
101 lines
2.3 KiB
Go
101 lines
2.3 KiB
Go
package db
|
|
|
|
import (
|
|
"testing"
|
|
"testing/quick"
|
|
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func OpenTemporaryDB() (*Database, error) {
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gormConfig)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
migrate := Gormigrate(db)
|
|
if err := migrate.Migrate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
func TestValidatePasteKey(t *testing.T) {
|
|
tests := []struct {
|
|
key string
|
|
wantErr bool
|
|
errKind error
|
|
}{
|
|
{"xd42__", false, nil},
|
|
{"xd42_*", true, ErrKeyInvalidChar},
|
|
{"xd42_/", true, ErrKeyInvalidChar},
|
|
{"xd42_=", true, ErrKeyInvalidChar},
|
|
{"xd42_", true, ErrKeyInvalidLength},
|
|
{"xd42", true, ErrKeyInvalidLength},
|
|
{"xd4", true, ErrKeyInvalidLength},
|
|
{"xd", true, ErrKeyInvalidLength},
|
|
{"x", true, ErrKeyInvalidLength},
|
|
{"", true, ErrKeyInvalidLength},
|
|
|
|
{"KoJ5", false, nil},
|
|
|
|
{"__dGSJIIbBpr-SD0", false, nil},
|
|
{"__dGSJIIbBpr-SD", true, ErrKeyInvalidLength},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.key, func(t *testing.T) {
|
|
err := ValidatePasteKey(tt.key)
|
|
if (err != nil) != tt.wantErr {
|
|
t.Errorf("ValidatePasteKey() got error = %v, want error %v", err != nil, tt.wantErr)
|
|
}
|
|
if (err != nil) && err != tt.errKind {
|
|
t.Errorf("ValidatePasteKey() error = %v, want errKind %v", err, tt.errKind)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGeneratedKeysAreValid(t *testing.T) {
|
|
db, err := OpenTemporaryDB()
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
var minimumEntropy int
|
|
checkGeneratedKeyValid := func() bool {
|
|
key, err := GeneratePasteKey(db, minimumEntropy)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return ValidatePasteKey(key) == nil
|
|
}
|
|
|
|
for minimumEntropy = 0; minimumEntropy <= 80; minimumEntropy++ {
|
|
if err = quick.Check(checkGeneratedKeyValid, nil); err != nil {
|
|
t.Error(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestTruncatedKeysAreInvalid(t *testing.T) {
|
|
db, err := OpenTemporaryDB()
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
var minimumEntropy int
|
|
checkTruncatedKeysInvalid := func(truncRand uint) bool {
|
|
key, err := GeneratePasteKey(db, minimumEntropy)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
trunc := int(truncRand % uint(len(key)-1))
|
|
key = key[:trunc]
|
|
return ValidatePasteKey(key) == ErrKeyInvalidLength
|
|
}
|
|
|
|
for minimumEntropy = 0; minimumEntropy <= 80; minimumEntropy++ {
|
|
if err = quick.Check(checkTruncatedKeysInvalid, nil); err != nil {
|
|
t.Error(err)
|
|
}
|
|
}
|
|
}
|