File size: 2,085 Bytes
651d019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package explorer_test

import (
	"os"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"

	"github.com/mudler/LocalAI/core/explorer"
)

var _ = Describe("Database", func() {
	var (
		dbPath string
		db     *explorer.Database
		err    error
	)

	BeforeEach(func() {
		// Create a temporary file path for the database
		dbPath = "test_db.json"
		db, err = explorer.NewDatabase(dbPath)
		Expect(err).To(BeNil())
	})

	AfterEach(func() {
		// Clean up the temporary database file
		os.Remove(dbPath)
	})

	Context("when managing tokens", func() {
		It("should add and retrieve a token", func() {
			token := "token123"
			t := explorer.TokenData{Name: "TokenName", Description: "A test token"}

			err = db.Set(token, t)
			Expect(err).To(BeNil())

			retrievedToken, exists := db.Get(token)
			Expect(exists).To(BeTrue())
			Expect(retrievedToken).To(Equal(t))
		})

		It("should delete a token", func() {
			token := "token123"
			t := explorer.TokenData{Name: "TokenName", Description: "A test token"}

			err = db.Set(token, t)
			Expect(err).To(BeNil())

			err = db.Delete(token)
			Expect(err).To(BeNil())

			_, exists := db.Get(token)
			Expect(exists).To(BeFalse())
		})

		It("should persist data to disk", func() {
			token := "token123"
			t := explorer.TokenData{Name: "TokenName", Description: "A test token"}

			err = db.Set(token, t)
			Expect(err).To(BeNil())

			// Recreate the database object to simulate reloading from disk
			db, err = explorer.NewDatabase(dbPath)
			Expect(err).To(BeNil())

			retrievedToken, exists := db.Get(token)
			Expect(exists).To(BeTrue())
			Expect(retrievedToken).To(Equal(t))

			// Check the token list
			tokenList := db.TokenList()
			Expect(tokenList).To(ContainElement(token))
		})
	})

	Context("when loading an empty or non-existent file", func() {
		It("should start with an empty database", func() {
			dbPath = "empty_db.json"
			db, err = explorer.NewDatabase(dbPath)
			Expect(err).To(BeNil())

			_, exists := db.Get("nonexistent")
			Expect(exists).To(BeFalse())

			// Clean up
			os.Remove(dbPath)
		})
	})
})