connectivity_test.go 1.5 KB
Newer Older
O
ob-robot 已提交
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
package net

import (
	"context"
	"net/http"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"gopkg.in/yaml.v3"
)

func Helloworld(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("helloworld"))
}

func TestConnectable(t *testing.T) {
	configStr := `
        timeout: 10s
        targets:
          t1: '127.0.0.1:9877'
    `
	var connectivityConfigMap map[string]interface{}
	_ = yaml.Unmarshal([]byte(configStr), &connectivityConfigMap)

	connectivityInput := &ConnectivityInput{}
	connectivityInput.Init(context.Background(), connectivityConfigMap)

	http.HandleFunc("/", Helloworld)
	go http.ListenAndServe(":9877", nil)
	time.Sleep(time.Second * 1)

	metrics, _ := connectivityInput.CollectMsgs()
	require.Equal(t, 1, len(metrics))
	value, exists := metrics[0].GetField("value")
	v, ok := value.(float64)
	require.True(t, exists)
	require.True(t, ok)
	require.Equal(t, 1.0, v)

}

func TestNotConnectable(t *testing.T) {
	configStr := `
        timeout: 10s
        targets:
          t1: '127.0.0.1:28833'
    `
	var connectivityConfigMap map[string]interface{}
	_ = yaml.Unmarshal([]byte(configStr), &connectivityConfigMap)

	connectivityInput := &ConnectivityInput{}
	connectivityInput.Init(context.Background(), connectivityConfigMap)

	metrics, _ := connectivityInput.CollectMsgs()
	require.Equal(t, 1, len(metrics))
	value, exists := metrics[0].GetField("value")
	v, ok := value.(float64)
	require.True(t, exists)
	require.True(t, ok)
	require.Equal(t, 0.0, v)
}