bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/bosun/search/search_test.go (about) 1 package search 2 3 import ( 4 "os" 5 "reflect" 6 "testing" 7 "time" 8 9 "bosun.org/host" 10 "bosun.org/util" 11 12 "bosun.org/cmd/bosun/database/test" 13 "bosun.org/opentsdb" 14 ) 15 16 var testSearch *Search 17 18 func TestMain(m *testing.M) { 19 hm, err := host.NewManager(false) 20 if err != nil { 21 panic(err) 22 } 23 util.SetHostManager(hm) 24 25 testData, closeF := dbtest.StartTestRedis(9990) 26 testSearch = NewSearch(testData, false) 27 status := m.Run() 28 closeF() 29 os.Exit(status) 30 } 31 32 func checkEqual(t *testing.T, err error, desc string, expected, actual []string) { 33 if err != nil { 34 t.Fatal(err) 35 } 36 if len(expected) != len(actual) { 37 t.Fatalf("%s lengths differ. Expected %d, but found %d", desc, len(expected), len(actual)) 38 } 39 if !reflect.DeepEqual(actual, expected) { 40 t.Fatalf("Expect %s: %s. Found %s", desc, expected, actual) 41 } 42 } 43 44 func TestIndex(t *testing.T) { 45 mdp := opentsdb.MultiDataPoint{ 46 &opentsdb.DataPoint{Metric: "os.cpu", Value: 12.0, Timestamp: 13, Tags: opentsdb.TagSet{"host": "abc", "proc": "7"}}, 47 &opentsdb.DataPoint{Metric: "os.mem", Value: 4000, Timestamp: 13, Tags: opentsdb.TagSet{"host": "abc1", "foo": "q"}}, 48 &opentsdb.DataPoint{Metric: "os.mem", Value: 4050, Timestamp: 13, Tags: opentsdb.TagSet{"host": "def", "foo": "q"}}, 49 &opentsdb.DataPoint{Metric: "os.mem", Value: 4050, Timestamp: 13, Tags: opentsdb.TagSet{"host": "def", "foo": "r"}}, 50 &opentsdb.DataPoint{Metric: "os.cpu2", Value: 12.0, Timestamp: 13, Tags: opentsdb.TagSet{"host": "abc"}}, 51 } 52 testSearch.Index(mdp) 53 time.Sleep(1 * time.Second) 54 um, err := testSearch.UniqueMetrics(0) 55 checkEqual(t, err, "metrics", []string{"os.cpu", "os.cpu2", "os.mem"}, um) 56 57 tagks, err := testSearch.TagKeysByMetric("os.cpu") 58 checkEqual(t, err, "tagk", []string{"host", "proc"}, tagks) 59 60 tagvs, err := testSearch.TagValuesByTagKey("host", 0) 61 checkEqual(t, err, "tagvsByTagKeyOnly", []string{"abc", "abc1", "def"}, tagvs) 62 63 tagvs, err = testSearch.TagValuesByMetricTagKey("os.mem", "host", 0) 64 checkEqual(t, err, "tagvsByTagKeyAndMetric", []string{"abc1", "def"}, tagvs) 65 66 metrics, err := testSearch.MetricsByTagPair("host", "abc", 0) 67 checkEqual(t, err, "metricsByPair", []string{"os.cpu", "os.cpu2"}, metrics) 68 69 filtered, err := testSearch.FilteredTagSets("os.mem", opentsdb.TagSet{"foo": "q"}, 0) 70 if err != nil { 71 t.Fatal(err) 72 } 73 if len(filtered) != 2 { 74 t.Fatalf("Expected 2 filtered results. Found %d.", len(filtered)) 75 } 76 }