Skip to content

Commit

Permalink
feat: Added mocked functions
Browse files Browse the repository at this point in the history
  • Loading branch information
ellistarn committed Mar 22, 2024
1 parent 4aa2d80 commit a376b46
Show file tree
Hide file tree
Showing 3 changed files with 231 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ go 1.20

require (
github.com/Pallinder/go-randomdata v1.2.0
github.com/go-logr/logr v1.2.4
github.com/go-logr/zapr v1.2.4
github.com/imdario/mergo v0.3.6
github.com/onsi/ginkgo/v2 v2.11.0
Expand All @@ -30,6 +29,7 @@ require (
github.com/evanphx/json-patch v5.6.0+incompatible // indirect
github.com/evanphx/json-patch/v5 v5.6.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
Expand Down
158 changes: 158 additions & 0 deletions mock/atomic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package mock

import (
"bytes"
"encoding/json"
"log"
"sync"
)

// atomicPtr is intended for use in mocks to easily expose variables for use in testing. It makes setting and retrieving
// the values race free by wrapping the pointer itself in a mutex. There is no Get() method, but instead a Clone() method
// deep copies the object being stored by serializing/de-serializing it from JSON. This pattern shouldn't be followed
// anywhere else but is an easy way to eliminate races in our tests.
type atomicPtr[T any] struct {
mu sync.Mutex
value *T
}

func (a *atomicPtr[T]) Set(v *T) {
a.mu.Lock()
defer a.mu.Unlock()
a.value = v
}

func (a *atomicPtr[T]) IsNil() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.value == nil
}

func (a *atomicPtr[T]) Clone() *T {
a.mu.Lock()
defer a.mu.Unlock()
return clone(a.value)
}

func clone[T any](v *T) *T {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(v); err != nil {
log.Fatalf("encoding %T, %s", v, err)
}
dec := json.NewDecoder(&buf)
var cp T
if err := dec.Decode(&cp); err != nil {
log.Fatalf("encoding %T, %s", v, err)
}
return &cp
}

func (a *atomicPtr[T]) Reset() {
a.mu.Lock()
defer a.mu.Unlock()
a.value = nil
}

type atomicError struct {
mu sync.Mutex
err error

calls int
maxCalls int
}

func (e *atomicError) Reset() {
e.mu.Lock()
defer e.mu.Unlock()
e.err = nil
e.calls = 0
e.maxCalls = 0
}

func (e *atomicError) IsNil() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.err == nil
}

// Get is equivalent to the error being called, so we increase
// number of calls in this function
func (e *atomicError) Get() error {
e.mu.Lock()
defer e.mu.Unlock()
if e.calls >= e.maxCalls {
return nil
}
e.calls++
return e.err
}

func (e *atomicError) Set(err error, opts ...atomicErrorOption) {
e.mu.Lock()
defer e.mu.Unlock()
e.err = err
for _, opt := range opts {
opt(e)
}
if e.maxCalls == 0 {
e.maxCalls = 1
}
}

type atomicErrorOption func(atomicError *atomicError)

// atomicPtrSlice exposes a slice of a pointer type in a race-free manner. The interface is just enough to replace the
// set.Set usage in our previous tests.
type atomicPtrSlice[T any] struct {
mu sync.RWMutex
values []*T
}

func (a *atomicPtrSlice[T]) Reset() {
a.mu.Lock()
defer a.mu.Unlock()
a.values = nil
}

func (a *atomicPtrSlice[T]) Add(input *T) {
a.mu.Lock()
defer a.mu.Unlock()
a.values = append(a.values, clone(input))
}

func (a *atomicPtrSlice[T]) Len() int {
a.mu.RLock()
defer a.mu.RUnlock()
return len(a.values)
}

func (a *atomicPtrSlice[T]) Pop() *T {
a.mu.Lock()
defer a.mu.Unlock()
last := a.values[len(a.values)-1]
a.values = a.values[0 : len(a.values)-1]
return last
}

func (a *atomicPtrSlice[T]) ForEach(fn func(*T)) {
a.mu.RLock()
defer a.mu.RUnlock()
for _, t := range a.values {
fn(clone(t))
}
}
72 changes: 72 additions & 0 deletions mock/function.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package mock

import (
"sync/atomic"
)

type Function[I any, O any] struct {
Output atomicPtr[O] // Output to return on call to this function
CalledWithInput atomicPtrSlice[I] // Slice used to keep track of passed input to this function
Error atomicError // Error to return a certain number of times defined by custom error options

successfulCalls atomic.Int32 // Internal construct to keep track of the number of times this function has successfully been called
failedCalls atomic.Int32 // Internal construct to keep track of the number of times this function has failed (with error)
}

// Reset must be called between tests otherwise tests will pollute
// each other.
func (m *Function[I, O]) Reset() {
m.Output.Reset()
m.CalledWithInput.Reset()
m.Error.Reset()

m.successfulCalls.Store(0)
m.failedCalls.Store(0)
}

func (m *Function[I, O]) Invoke(input *I, defaultTransformer func(*I) (*O, error)) (*O, error) {
err := m.Error.Get()
if err != nil {
m.failedCalls.Add(1)
return nil, err
}
m.CalledWithInput.Add(input)

if !m.Output.IsNil() {
m.successfulCalls.Add(1)
return m.Output.Clone(), nil
}
out, err := defaultTransformer(input)
if err != nil {
m.failedCalls.Add(1)
} else {
m.successfulCalls.Add(1)
}
return out, err
}

func (m *Function[I, O]) Calls() int {
return m.SuccessfulCalls() + m.FailedCalls()
}

func (m *Function[I, O]) SuccessfulCalls() int {
return int(m.successfulCalls.Load())
}

func (m *Function[I, O]) FailedCalls() int {
return int(m.failedCalls.Load())
}

0 comments on commit a376b46

Please sign in to comment.