github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_cidr_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  	tu "github.com/GuanceCloud/cliutils/testutil"
    15  )
    16  
    17  func TestCIDR(t *testing.T) {
    18  	cases := []struct {
    19  		name     string
    20  		outKey   string
    21  		pl, in   string
    22  		expected interface{}
    23  		fail     bool
    24  	}{
    25  		{
    26  			name: "ipv4_contains",
    27  			pl: `ip = "192.0.2.233"
    28  			if cidr(ip, "192.0.2.1/24") {
    29  				add_key(ip_prefix, "192.0.2.1/24")
    30  			}`,
    31  			in:       ``,
    32  			outKey:   "ip_prefix",
    33  			expected: "192.0.2.1/24",
    34  			fail:     false,
    35  		},
    36  		{
    37  			name: "ipv4_not_contains",
    38  			pl: `ip = "192.0.2.233"
    39  			if cidr(ip, "192.0.1.1/24") {
    40  				add_key(ip_prefix, "192.0.1.1/24")
    41  			}`,
    42  			in:     ``,
    43  			outKey: "ip_prefix",
    44  			fail:   false,
    45  		},
    46  	}
    47  
    48  	for idx, tc := range cases {
    49  		t.Run(tc.name, func(t *testing.T) {
    50  			runner, err := NewTestingRunner(tc.pl)
    51  			if err != nil {
    52  				if tc.fail {
    53  					t.Logf("[%d]expect error: %s", idx, err)
    54  				} else {
    55  					t.Errorf("[%d] failed: %s", idx, err)
    56  				}
    57  				return
    58  			}
    59  
    60  			pt := ptinput.NewPlPoint(
    61  				point.Logging, "test", nil, map[string]any{"message": tc.in}, time.Now())
    62  			errR := runScript(runner, pt)
    63  
    64  			if errR != nil {
    65  				t.Fatal(errR.Error())
    66  			}
    67  
    68  			if tc.fail {
    69  				t.Logf("[%d]expect error: %s", idx, errR.Error())
    70  			}
    71  			v, _, _ := pt.Get(tc.outKey)
    72  			tu.Equals(t, tc.expected, v)
    73  			t.Logf("[%d] PASS", idx)
    74  		})
    75  	}
    76  }