smallindex_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. )
  10. func TestSmallIndex(t *testing.T) {
  11. db := newLowlevelMemory(t)
  12. idx := newSmallIndex(db, []byte{12, 34})
  13. // ID zero should be unallocated
  14. if val, ok := idx.Val(0); ok || val != nil {
  15. t.Fatal("Unexpected return for nonexistent ID 0")
  16. }
  17. // A new key should get ID zero
  18. if id, err := idx.ID([]byte("hello")); err != nil {
  19. t.Fatal(err)
  20. } else if id != 0 {
  21. t.Fatal("Expected 0, not", id)
  22. }
  23. // Looking up ID zero should work
  24. if val, ok := idx.Val(0); !ok || string(val) != "hello" {
  25. t.Fatalf(`Expected true, "hello", not %v, %q`, ok, val)
  26. }
  27. // Delete the key
  28. idx.Delete([]byte("hello"))
  29. // Next ID should be one
  30. if id, err := idx.ID([]byte("key2")); err != nil {
  31. t.Fatal(err)
  32. } else if id != 1 {
  33. t.Fatal("Expected 1, not", id)
  34. }
  35. // Now lets create a new index instance based on what's actually serialized to the database.
  36. idx = newSmallIndex(db, []byte{12, 34})
  37. // Status should be about the same as before.
  38. if val, ok := idx.Val(0); ok || val != nil {
  39. t.Fatal("Unexpected return for deleted ID 0")
  40. }
  41. if id, err := idx.ID([]byte("key2")); err != nil {
  42. t.Fatal(err)
  43. } else if id != 1 {
  44. t.Fatal("Expected 1, not", id)
  45. }
  46. // Setting "hello" again should get us ID 2, not 0 as it was originally.
  47. if id, err := idx.ID([]byte("hello")); err != nil {
  48. t.Fatal(err)
  49. } else if id != 2 {
  50. t.Fatal("Expected 2, not", id)
  51. }
  52. }