store_test.go 954 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package ipn
  4. import (
  5. "bytes"
  6. "sync"
  7. "testing"
  8. "tailscale.com/util/mak"
  9. )
  10. type memStore struct {
  11. mu sync.Mutex
  12. writes int
  13. m map[StateKey][]byte
  14. }
  15. func (s *memStore) ReadState(k StateKey) ([]byte, error) {
  16. s.mu.Lock()
  17. defer s.mu.Unlock()
  18. return bytes.Clone(s.m[k]), nil
  19. }
  20. func (s *memStore) WriteState(k StateKey, v []byte) error {
  21. s.mu.Lock()
  22. defer s.mu.Unlock()
  23. mak.Set(&s.m, k, bytes.Clone(v))
  24. s.writes++
  25. return nil
  26. }
  27. func TestWriteState(t *testing.T) {
  28. var ss StateStore = new(memStore)
  29. WriteState(ss, "foo", []byte("bar"))
  30. WriteState(ss, "foo", []byte("bar"))
  31. got, err := ss.ReadState("foo")
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. if want := []byte("bar"); !bytes.Equal(got, want) {
  36. t.Errorf("got %q; want %q", got, want)
  37. }
  38. if got, want := ss.(*memStore).writes, 1; got != want {
  39. t.Errorf("got %d writes; want %d", got, want)
  40. }
  41. }