github.com/creachadair/ffs@v0.17.3/storage/dbkey/dbkey_test.go (about) 1 // Copyright 2019 Michael J. Fromberger. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package dbkey_test 16 17 import ( 18 "testing" 19 20 "github.com/creachadair/ffs/storage/dbkey" 21 ) 22 23 type keyOp = func(dbkey.Prefix) dbkey.Prefix 24 25 func subs(names ...string) keyOp { 26 return func(p dbkey.Prefix) dbkey.Prefix { 27 for _, name := range names { 28 p = p.Sub(name) 29 } 30 return p 31 } 32 } 33 34 func subKV(names ...string) keyOp { 35 return func(p dbkey.Prefix) dbkey.Prefix { 36 for _, name := range names[:len(names)-1] { 37 p = p.Sub(name) 38 } 39 return p.Keyspace(names[len(names)-1]) 40 } 41 } 42 43 func TestPrefix(t *testing.T) { 44 tests := []struct { 45 base dbkey.Prefix 46 op keyOp 47 wantHex string 48 }{ 49 {"", subs(), ""}, 50 {"ABC", subs(), "414243"}, 51 {"", subs("sub1"), "6e3617aaf658"}, 52 {"", subKV("sub1"), "fea73fac92bd"}, // KV does not collide with sub 53 54 // Verify that we get to the same place regardless where we start. 55 {"", subs("sub1", "sub2"), "d404af12ddfb"}, 56 {"\xd4\x04\xaf\x12\xdd\xfb", subKV("ks"), "47b256a71b00"}, 57 {"", subKV("sub1", "sub2", "ks"), "47b256a71b00"}, 58 {"\x6e\x36\x17\xaa\xf6\x58", subKV("sub2", "ks"), "47b256a71b00"}, 59 } 60 for _, tc := range tests { 61 got := tc.op(tc.base) 62 if got.String() != tc.wantHex { 63 t.Errorf("Prefix %q derivation: got %q, want %q", tc.base, got, tc.wantHex) 64 } 65 } 66 } 67 68 func TestAddRemove(t *testing.T) { 69 tests := []struct { 70 prefix dbkey.Prefix 71 input string 72 added string 73 }{ 74 {"", "", ""}, 75 {"", "apple", "apple"}, 76 {"pear", "apple", "pearapple"}, 77 {"plum", "", "plum"}, 78 {"cherry:", "plum", "cherry:plum"}, 79 } 80 for _, tc := range tests { 81 added := tc.prefix.Add(tc.input) 82 if added != tc.added { 83 t.Errorf("%q.Add(%q): got %q, want %q", tc.prefix, tc.input, added, tc.added) 84 } 85 86 // Verify that Remove round-trips the key. 87 rem := tc.prefix.Remove(added) 88 if rem != tc.input { 89 t.Errorf("%q.Remove(%q): got %q, want %q", tc.prefix, added, rem, tc.input) 90 } 91 } 92 }