github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_set_mesaurement_test.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  package funcs
     7  
     8  import (
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/GuanceCloud/cliutils/pipeline/ptinput"
    13  	"github.com/GuanceCloud/cliutils/point"
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  func TestSetMeasurement(t *testing.T) {
    18  	cases := []struct {
    19  		name, pl, in string
    20  		del          bool
    21  		out          string
    22  		expect       string
    23  		fail         bool
    24  	}{
    25  		{
    26  			name: "set_measurement 0",
    27  			in:   `162.62.81.1 - - [29/Nov/2021:07:30:50 +0000] "123 /?signature=b8d8ea&timestamp=1638171049 HTTP/1.1" 200 413 "-" "Mozilla/4.0"`,
    28  			pl: `
    29  		set_tag(client_ip)
    30  		grok(_, "%{IPORHOST:client_ip} %{NOTSPACE} %{NOTSPACE} \\[%{HTTPDATE:time}\\] \"%{DATA:data} %{GREEDYDATA} HTTP/%{NUMBER}\" %{INT:status_code} %{INT:bytes}")
    31  		cast(data, "int")
    32  		set_measurement(client_ip)
    33  
    34  		`,
    35  			del:    false,
    36  			out:    "client_ip",
    37  			expect: "162.62.81.1",
    38  			fail:   false,
    39  		},
    40  		{
    41  			name: "set_measurement 1",
    42  			in:   `162.62.81.1 - - [29/Nov/2021:07:30:50 +0000] "123 /?signature=b8d8ea&timestamp=1638171049 HTTP/1.1" 200 413 "-" "Mozilla/4.0"`,
    43  			pl: `
    44  		grok(_, "%{IPORHOST:client_ip} %{NOTSPACE} %{NOTSPACE} \\[%{HTTPDATE:time}\\] \"%{DATA:data} %{GREEDYDATA} HTTP/%{NUMBER}\" %{INT:status_code} %{INT:bytes}")
    45  		set_tag(client_ip)
    46  		cast(data, "int")
    47  		set_measurement(client_ip, true)
    48  
    49  		`,
    50  			del:    true,
    51  			out:    "client_ip",
    52  			expect: "162.62.81.1",
    53  			fail:   false,
    54  		},
    55  	}
    56  
    57  	for idx, tc := range cases {
    58  		t.Run(tc.name, func(t *testing.T) {
    59  			runner, err := NewTestingRunner(tc.pl)
    60  			if err != nil {
    61  				if tc.fail {
    62  					t.Logf("[%d]expect error: %s", idx, err)
    63  				} else {
    64  					t.Errorf("[%d] failed: %s", idx, err)
    65  				}
    66  				return
    67  			}
    68  			pt := ptinput.NewPlPoint(
    69  				point.Logging, "test", nil, map[string]any{"message": tc.in}, time.Now())
    70  			errR := runScript(runner, pt)
    71  
    72  			if errR != nil {
    73  				t.Fatal(errR.Error())
    74  			}
    75  
    76  			_, _, e := pt.Get(tc.out)
    77  			assert.Equal(t, tc.del, e != nil)
    78  			assert.Equal(t, tc.expect, pt.GetPtName())
    79  			t.Logf("[%d] PASS", idx)
    80  		})
    81  	}
    82  }