/
transaction_store.go
98 lines (80 loc) · 2.2 KB
/
transaction_store.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
95
96
97
98
package match
import (
"sync"
"github.com/jmartin82/mmock/v3/pkg/mock"
)
type TransactionStorer interface {
Save(Transaction)
Reset()
ResetMatch(mock.Request)
GetAll() []Transaction
Get(limit int, offset int) []Transaction
}
//InMemoryTransactionStore stores all received request and their matches in memory until the last reset
type InMemoryTransactionStore struct {
matches []Transaction
sync.Mutex
checker Matcher
limit int
}
//Save store a match information
func (mrs *InMemoryTransactionStore) Save(req Transaction) {
mrs.Lock()
if mrs.limit > 0 && mrs.limit == len(mrs.matches) {
mrs.matches[0] = Transaction{}
mrs.matches = mrs.matches[1:]
}
mrs.matches = append(mrs.matches, req)
mrs.Unlock()
}
//Reset clean the request stored in memory
func (mrs *InMemoryTransactionStore) Reset() {
mrs.Lock()
mrs.matches = make([]Transaction, 0, mrs.limit)
mrs.Unlock()
}
//ResetMatch clean the request stored in memory that matches a particular criteria
func (mrs *InMemoryTransactionStore) ResetMatch(req mock.Request) {
matches := mrs.GetAll()
mrs.Lock()
var r = []Transaction{}
for _, e := range matches {
if c, _ := mrs.checker.Match(e.Request, &mock.Definition{Request: req}, false); !c {
r = append(r, e)
}
}
mrs.matches = r
mrs.Unlock()
}
//GetAll return current matches (positive and negative) in memory
func (mrs *InMemoryTransactionStore) GetAll() []Transaction {
mrs.Lock()
r := make([]Transaction, len(mrs.matches))
copy(r, mrs.matches)
mrs.Unlock()
return r
}
//Get return an subset of current matches (positive and negative) in memory
func (mrs *InMemoryTransactionStore) Get(limit int, offset int) []Transaction {
mrs.Lock()
defer mrs.Unlock()
max := offset + limit
if max > len(mrs.matches) {
max = len(mrs.matches)
}
if offset >= max {
return []Transaction{}
}
r := make([]Transaction, max-offset)
copy(r, mrs.matches[offset:max])
return r
}
//NewInMemoryScenarioStore is the InMemoryTransactionStore constructor
func NewInMemoryTransactionStore(checker Matcher, limit int) *InMemoryTransactionStore {
l := 100
if limit > 0 {
l = limit
}
reqs := make([]Transaction, 0, l)
return &InMemoryTransactionStore{matches: reqs, checker: checker, limit: limit}
}