bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/bosun/web/relay_test.go (about)

     1  package web
     2  
     3  import (
     4  	"bytes"
     5  	"compress/gzip"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"net/url"
     9  	"os"
    10  	"sort"
    11  	"testing"
    12  	"time"
    13  
    14  	"bosun.org/host"
    15  	"bosun.org/util"
    16  
    17  	"bosun.org/cmd/bosun/conf"
    18  	"bosun.org/cmd/bosun/conf/rule"
    19  	"bosun.org/cmd/bosun/database"
    20  	"bosun.org/cmd/bosun/database/test"
    21  )
    22  
    23  var testData database.DataAccess
    24  
    25  func TestMain(m *testing.M) {
    26  	var closeF func()
    27  	testData, closeF = dbtest.StartTestRedis(9991)
    28  	status := m.Run()
    29  	closeF()
    30  	os.Exit(status)
    31  }
    32  
    33  func TestRelay(t *testing.T) {
    34  	hm, err := host.NewManager(false)
    35  	if err != nil {
    36  		t.Error(err)
    37  	}
    38  	util.SetHostManager(hm)
    39  
    40  	schedule.Init("relay_test", &conf.SystemConf{}, new(rule.Conf), testData, nil, false, false)
    41  	rs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    42  		w.WriteHeader(204)
    43  	}))
    44  	defer rs.Close()
    45  	rurl, err := url.Parse(rs.URL)
    46  	if err != nil {
    47  		t.Fatal(err)
    48  	}
    49  	ts := httptest.NewServer(Relay(rurl.Host))
    50  	defer ts.Close()
    51  
    52  	body := []byte(`[{
    53  		"timestamp": 1,
    54  		"metric": "no-gzip-works",
    55  		"value": 123.45,
    56  		"tags": {
    57  			"host": "host.no.gzip",
    58  			"other": "something"
    59  		}
    60  	}]`)
    61  	if _, err := http.Post(ts.URL, "application/json", bytes.NewBuffer(body)); err != nil {
    62  		t.Fatal(err)
    63  	}
    64  
    65  	bodygzip := []byte(`[{
    66  		"timestamp": 1,
    67  		"metric": "gzip-works",
    68  		"value": 345,
    69  		"tags": {
    70  			"host": "host.gzip",
    71  			"gzipped": "yup"
    72  		}
    73  	}]`)
    74  	buf := new(bytes.Buffer)
    75  	gw := gzip.NewWriter(buf)
    76  	gw.Write(bodygzip)
    77  	gw.Flush()
    78  	if _, err := http.Post(ts.URL, "application/json", bytes.NewReader(buf.Bytes())); err != nil {
    79  		t.Fatal(err)
    80  	}
    81  	time.Sleep(time.Second)
    82  
    83  	m, _ := schedule.Search.UniqueMetrics(0)
    84  	sort.Strings(m)
    85  	if len(m) != 2 || m[0] != "gzip-works" || m[1] != "no-gzip-works" {
    86  		t.Errorf("bad um: %v", m)
    87  	}
    88  	m, _ = schedule.Search.TagValuesByMetricTagKey("gzip-works", "gzipped", 0)
    89  	if len(m) != 1 || m[0] != "yup" {
    90  		t.Errorf("bad tvbmtk: %v", m)
    91  	}
    92  	m, _ = schedule.Search.TagKeysByMetric("no-gzip-works")
    93  	sort.Strings(m)
    94  	if len(m) != 2 || m[0] != "host" || m[1] != "other" {
    95  		t.Errorf("bad tkbm: %v", m)
    96  	}
    97  }