src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/cli/histutil/test_db.go (about) 1 package histutil 2 3 import ( 4 "strings" 5 6 "src.elv.sh/pkg/store/storedefs" 7 ) 8 9 // FaultyInMemoryDB is an in-memory DB implementation that can be injected 10 // one-off errors. It is useful in tests. 11 type FaultyInMemoryDB interface { 12 DB 13 // SetOneOffError causes the next operation on the database to return the 14 // given error. 15 SetOneOffError(err error) 16 } 17 18 // NewFaultyInMemoryDB creates a new FaultyInMemoryDB with the given commands. 19 func NewFaultyInMemoryDB(cmds ...string) FaultyInMemoryDB { 20 return &testDB{cmds: cmds} 21 } 22 23 // Implementation of FaultyInMemoryDB. 24 type testDB struct { 25 cmds []string 26 oneOffError error 27 } 28 29 func (s *testDB) SetOneOffError(err error) { 30 s.oneOffError = err 31 } 32 33 func (s *testDB) error() error { 34 err := s.oneOffError 35 s.oneOffError = nil 36 return err 37 } 38 39 func (s *testDB) NextCmdSeq() (int, error) { 40 return len(s.cmds), s.error() 41 } 42 43 func (s *testDB) AddCmd(cmd string) (int, error) { 44 if s.oneOffError != nil { 45 return -1, s.error() 46 } 47 s.cmds = append(s.cmds, cmd) 48 return len(s.cmds) - 1, nil 49 } 50 51 func (s *testDB) CmdsWithSeq(from, upto int) ([]storedefs.Cmd, error) { 52 if err := s.error(); err != nil { 53 return nil, err 54 } 55 if from < 0 { 56 from = 0 57 } 58 if upto < 0 || upto > len(s.cmds) { 59 upto = len(s.cmds) 60 } 61 var cmds []storedefs.Cmd 62 for i := from; i < upto; i++ { 63 cmds = append(cmds, storedefs.Cmd{Text: s.cmds[i], Seq: i}) 64 } 65 return cmds, nil 66 } 67 68 func (s *testDB) PrevCmd(upto int, prefix string) (storedefs.Cmd, error) { 69 if s.oneOffError != nil { 70 return storedefs.Cmd{}, s.error() 71 } 72 for i := upto - 1; i >= 0; i-- { 73 if strings.HasPrefix(s.cmds[i], prefix) { 74 return storedefs.Cmd{Text: s.cmds[i], Seq: i}, nil 75 } 76 } 77 return storedefs.Cmd{}, storedefs.ErrNoMatchingCmd 78 } 79 80 func (s *testDB) NextCmd(from int, prefix string) (storedefs.Cmd, error) { 81 if s.oneOffError != nil { 82 return storedefs.Cmd{}, s.error() 83 } 84 for i := from; i < len(s.cmds); i++ { 85 if strings.HasPrefix(s.cmds[i], prefix) { 86 return storedefs.Cmd{Text: s.cmds[i], Seq: i}, nil 87 } 88 } 89 return storedefs.Cmd{}, storedefs.ErrNoMatchingCmd 90 }