/
db.go
94 lines (71 loc) · 2.07 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// SPDX-License-Identifier: AGPL-3.0-only
package tests
import (
"database/sql/driver"
"encoding/hex"
"strings"
"testing"
"time"
"github.com/brainupdaters/drlm-core/context"
"github.com/DATA-DOG/go-sqlmock"
"github.com/jinzhu/gorm"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
// import the gorm postgres dialect
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// GenerateDB generates a new Mock DB
func GenerateDB(t *testing.T, ctx *context.Context) sqlmock.Sqlmock {
require := require.New(t)
d, mock, err := sqlmock.New()
require.NoError(err)
ctx.DB, err = gorm.Open("postgres", d)
require.NoError(err)
ctx.DB.LogMode(false)
return mock
}
// DBAnyTime is used to mock time.Time in the DB
type DBAnyTime struct{}
// Match is the function responsible for returning whether the mock expression matches or not the expectations
func (a DBAnyTime) Match(v driver.Value) bool {
_, ok := v.(time.Time)
return ok
}
// DBAnyEncryptedPassword is used to mock encrypted passwords using bcrypt
type DBAnyEncryptedPassword struct{}
// Match is the function responsible for returning whether the mock expression matches or not the expectations
func (p DBAnyEncryptedPassword) Match(v driver.Value) bool {
s, ok := v.(string)
if !ok {
return false
}
_, err := bcrypt.Cost([]byte(s))
if err != nil {
return false
}
return true
}
// DBAnyBucketName is used to mock bucket names (since they have a UID part)
type DBAnyBucketName struct{}
// Match is the function responsible for returning whether the mock expression matches or not the expectations
func (b DBAnyBucketName) Match(v driver.Value) bool {
bName, ok := v.(string)
if !ok {
return false
}
return strings.HasPrefix(bName, "drlm-")
}
// DBAnySecret is used to mock a secret
type DBAnySecret struct{}
// Match is the function responsible for returning whether the mock expression matches or not the expectations
func (b DBAnySecret) Match(v driver.Value) bool {
s, ok := v.(string)
if !ok {
return false
}
_, err := hex.DecodeString(s)
if err != nil {
return false
}
return len(s) == 32
}