Commit 5176504

Richard Luby <richluby@gmail.com>
2017-01-26 14:11:58
can retrieve categories from database
unique, unsorted categories retrieved from databse using simple regex query
1 parent dab4af4
Changed files (2)
db.go
@@ -24,6 +24,19 @@ var DB_config = DB_CONFIG{
 // to the database
 var DBsession *mgo.Session
 
+// getCategoriesFromDB
+func getCategoriesFromDB() ([]string, error) {
+	if DBsession == nil {
+		if _, err := InitDBSession(); err != nil {
+			return nil, err
+		}
+	}
+	var dbCats []string
+	collection := DBsession.DB(DB_config.DB_name).C(DB_config.CollectionName)
+	err := collection.Find(bson.M{"path": bson.M{"$regex": ""}}).Distinct("path", &dbCats)
+	return dbCats, err
+}
+
 // initDBSession initializes the connection to the database containing
 // the list of records.
 // returns the *mgo.Session connected to the database
@@ -39,6 +52,10 @@ func InitDBSession() (*mgo.Session, error) {
 		DropDups: true,
 		Unique:   true}
 	DBsession.DB(DB_config.DB_name).C(DB_config.CollectionName).EnsureIndex(index)
+	categories, err = getCategoriesFromDB()
+	if err != nil {
+		return nil, err
+	}
 	return DBsession, nil
 }
 
db_test.go
@@ -51,3 +51,33 @@ func TestAddAndRetriveForDB(t *testing.T) {
 		t.Errorf("Wrong length of test results: %d: %+v", len(results), results)
 	}
 }
+
+// TestRetrieveCategories verifies that categories can be
+// retrieved from the database
+func TestRetrieveCategories(t *testing.T) {
+	initDBForTest(t)
+	categories = nil
+	categories, err := getCategoriesFromDB()
+	if err != nil {
+		t.Errorf("Error getting categories: %+v", err)
+	}
+	if len(categories) <= 0 {
+		t.Error("No categories found.")
+		t.Fail()
+	}
+	testCase := "linux:filesystem:acl"
+	testCaseFound := false
+	for i, cat := range categories {
+		if cat == testCase {
+			testCaseFound = true
+		}
+		for j, secondCat := range categories { //check for duplicates
+			if j != i && cat == secondCat {
+				t.Errorf("Duplicate categories: %+v\t%d and %d", cat, i, j)
+			}
+		}
+	}
+	if !testCaseFound {
+		t.Errorf("No test case was found: %+v", categories)
+	}
+}