rushlink/internal/db/paste_test.go

101 lines
2.3 KiB
Go
Raw Normal View History

2020-10-25 17:33:51 +01:00
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
}
2020-12-17 15:14:45 +01:00
migrate := Gormigrate(db)
if err := migrate.Migrate(); err != nil {
return nil, err
}
return db, nil
}
2020-10-25 17:33:51 +01:00
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)
}
}
}