Last active
February 15, 2024 08:07
-
-
Save mickmister/f2ac1c99c63291692b18fdae715338af to your computer and use it in GitHub Desktop.
Mock KVStore for Mattermost plugin unit testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/mattermost/mattermost/server/public/plugin/plugintest" | |
"github.com/stretchr/testify/mock" | |
) | |
type testKVStore map[string][]byte | |
func makeTestKVStore(api *plugintest.API, initialValues testKVStore) testKVStore { | |
testStore := initialValues | |
if testStore == nil { | |
testStore = testKVStore{} | |
} | |
kvCall := api.On("KVGet", mock.Anything).Maybe().Return(nil, nil) | |
kvCall.Run(func(args mock.Arguments) { | |
key := args.Get(0).(string) | |
val, ok := testStore[key] | |
if ok { | |
kvCall.Return(val, nil) | |
} else { | |
kvCall.Return(nil, nil) | |
} | |
}) | |
api.On("KVSet", mock.Anything, mock.Anything).Maybe().Return(nil).Run(func(args mock.Arguments) { | |
key := args.Get(0).(string) | |
value := args.Get(1).([]byte) | |
testStore[key] = value | |
}) | |
return testStore | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
func (p *Plugin) KVScratch() { | |
p.API.KVSet("mykey", []byte("my value")) | |
initialValue, _ := p.API.KVGet("initial") | |
p.API.KVSet("fetched", initialValue) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
"github.com/mattermost/mattermost/server/public/plugin/plugintest" | |
"github.com/stretchr/testify/require" | |
) | |
func TestKVScratch(t *testing.T) { | |
p := &Plugin{} | |
api := &plugintest.API{} | |
p.SetAPI(api) | |
testStore := makeTestKVStore(api, testKVStore{ | |
"initial": []byte("initial value"), | |
}) | |
p.KVScratch() | |
require.Equal(t, "my value", string(testStore["mykey"])) | |
require.Equal(t, "initial value", string(testStore["fetched"])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment