smallindex_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (C) 2018 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package db
  7. import (
  8. "testing"
  9. "github.com/syncthing/syncthing/lib/db/backend"
  10. )
  11. func TestSmallIndex(t *testing.T) {
  12. db := NewLowlevel(backend.OpenMemory())
  13. idx := newSmallIndex(db, []byte{12, 34})
  14. // ID zero should be unallocated
  15. if val, ok := idx.Val(0); ok || val != nil {
  16. t.Fatal("Unexpected return for nonexistent ID 0")
  17. }
  18. // A new key should get ID zero
  19. if id, err := idx.ID([]byte("hello")); err != nil {
  20. t.Fatal(err)
  21. } else if id != 0 {
  22. t.Fatal("Expected 0, not", id)
  23. }
  24. // Looking up ID zero should work
  25. if val, ok := idx.Val(0); !ok || string(val) != "hello" {
  26. t.Fatalf(`Expected true, "hello", not %v, %q`, ok, val)
  27. }
  28. // Delete the key
  29. idx.Delete([]byte("hello"))
  30. // Next ID should be one
  31. if id, err := idx.ID([]byte("key2")); err != nil {
  32. t.Fatal(err)
  33. } else if id != 1 {
  34. t.Fatal("Expected 1, not", id)
  35. }
  36. // Now lets create a new index instance based on what's actually serialized to the database.
  37. idx = newSmallIndex(db, []byte{12, 34})
  38. // Status should be about the same as before.
  39. if val, ok := idx.Val(0); ok || val != nil {
  40. t.Fatal("Unexpected return for deleted ID 0")
  41. }
  42. if id, err := idx.ID([]byte("key2")); err != nil {
  43. t.Fatal(err)
  44. } else if id != 1 {
  45. t.Fatal("Expected 1, not", id)
  46. }
  47. // Setting "hello" again should get us ID 2, not 0 as it was originally.
  48. if id, err := idx.ID([]byte("hello")); err != nil {
  49. t.Fatal(err)
  50. } else if id != 2 {
  51. t.Fatal("Expected 2, not", id)
  52. }
  53. }