github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/nomad/state/schema_test.go (about) 1 package state 2 3 import ( 4 "testing" 5 6 memdb "github.com/hashicorp/go-memdb" 7 "github.com/stretchr/testify/require" 8 ) 9 10 func TestStateStoreSchema(t *testing.T) { 11 schema := stateStoreSchema() 12 _, err := memdb.NewMemDB(schema) 13 if err != nil { 14 t.Fatalf("err: %v", err) 15 } 16 } 17 18 func TestState_singleRecord(t *testing.T) { 19 require := require.New(t) 20 21 const ( 22 singletonTable = "cluster_meta" 23 singletonIDIdx = "id" 24 ) 25 26 db, err := memdb.NewMemDB(&memdb.DBSchema{ 27 Tables: map[string]*memdb.TableSchema{ 28 singletonTable: clusterMetaTableSchema(), 29 }, 30 }) 31 require.NoError(err) 32 33 // numRecords in table counts all the items in the table, which is expected 34 // to always be 1 since that's the point of the singletonRecord Indexer. 35 numRecordsInTable := func() int { 36 txn := db.Txn(false) 37 defer txn.Abort() 38 39 iter, err := txn.Get(singletonTable, singletonIDIdx) 40 require.NoError(err) 41 42 num := 0 43 for item := iter.Next(); item != nil; item = iter.Next() { 44 num++ 45 } 46 return num 47 } 48 49 // setSingleton "updates" the singleton record in the singletonTable, 50 // which requires that the singletonRecord Indexer is working as 51 // expected. 52 setSingleton := func(s string) { 53 txn := db.Txn(true) 54 err := txn.Insert(singletonTable, s) 55 require.NoError(err) 56 txn.Commit() 57 } 58 59 // first retrieves the one expected entry in the singletonTable - use the 60 // numRecordsInTable helper function to make the cardinality assertion, 61 // this is just for fetching the value. 62 first := func() string { 63 txn := db.Txn(false) 64 defer txn.Abort() 65 record, err := txn.First(singletonTable, singletonIDIdx) 66 require.NoError(err) 67 s, ok := record.(string) 68 require.True(ok) 69 return s 70 } 71 72 // Ensure that multiple Insert & Commit calls result in only 73 // a single "singleton" record existing in the table. 74 75 setSingleton("one") 76 require.Equal(1, numRecordsInTable()) 77 require.Equal("one", first()) 78 79 setSingleton("two") 80 require.Equal(1, numRecordsInTable()) 81 require.Equal("two", first()) 82 83 setSingleton("three") 84 require.Equal(1, numRecordsInTable()) 85 require.Equal("three", first()) 86 }