bitbucket.org/ai69/amoy@v0.2.3/regex_test.go (about)

     1  package amoy
     2  
     3  import (
     4  	"reflect"
     5  	"regexp"
     6  	"testing"
     7  )
     8  
     9  func TestExtractNamedValues(t *testing.T) {
    10  	type args struct {
    11  		r   *regexp.Regexp
    12  		str string
    13  	}
    14  	tests := []struct {
    15  		name string
    16  		args args
    17  		want NamedValues
    18  	}{
    19  		{"nil regex", args{nil, "Hello"}, map[string]string{}},
    20  		{"empty regex", args{regexp.MustCompile(""), "Hello"}, map[string]string{}},
    21  		{"not match", args{regexp.MustCompile(`(?P<url>https?://[/.\-\w]+)/(?P<key>[\w]{10,})/?`), "Hello"}, map[string]string{}},
    22  		{"match empty", args{regexp.MustCompile(`(?P<val>[^/]*)/(?P<key>[\w]*)/?`), `//`}, map[string]string{"val": EmptyStr, "key": EmptyStr}},
    23  		{"match", args{regexp.MustCompile(`(?P<val>[^/]*)/(?P<key>[\w]*)/?`), `123/hello/`}, map[string]string{"val": "123", "key": "hello"}},
    24  		{"match unnamed", args{regexp.MustCompile(`([^/]*)/([\w]*)/?`), `123/hello/`}, map[string]string{}},
    25  	}
    26  	for _, tt := range tests {
    27  		t.Run(tt.name, func(t *testing.T) {
    28  			if got := ExtractNamedValues(tt.args.r, tt.args.str); !reflect.DeepEqual(got, tt.want) {
    29  				t.Errorf("ExtractNamedValues() = %v, want %v", got, tt.want)
    30  			}
    31  		})
    32  	}
    33  }
    34  
    35  func TestRegexMatch(t *testing.T) {
    36  	tests := []struct {
    37  		name    string
    38  		pat     string
    39  		s       string
    40  		want    bool
    41  		wantErr bool
    42  	}{
    43  		{"invalid pattern", "[[", "hello", false, true},
    44  		{"match pattern", "(?i)^hello", "Hello World", true, false},
    45  		{"unmatch pattern", "(?i)^hello", "Halo World", false, false},
    46  	}
    47  	for _, tt := range tests {
    48  		t.Run(tt.name, func(t *testing.T) {
    49  			got, err := RegexMatch(tt.pat, tt.s)
    50  			if (err != nil) != tt.wantErr {
    51  				t.Errorf("RegexMatch() error = %v, wantErr %v", err, tt.wantErr)
    52  				return
    53  			}
    54  			if got != tt.want {
    55  				t.Errorf("RegexMatch() got = %v, want %v", got, tt.want)
    56  			}
    57  		})
    58  	}
    59  }
    60  
    61  func BenchmarkRegexMatch(b *testing.B) {
    62  	var (
    63  		p1 = "(?i)^hello"
    64  		s1 = "Hello World"
    65  		p2 = "(?i)^hello[^|&%]+W(.*?)"
    66  		s2 = "Hello_World"
    67  		p3 = "zln##@%v$%^%#h234"
    68  		s3 = "Hello World!"
    69  	)
    70  	b.ResetTimer()
    71  	for i := 0; i < b.N; i++ {
    72  		_, _ = RegexMatch(p1, s1)
    73  		_, _ = RegexMatch(p2, s2)
    74  		_, _ = RegexMatch(p3, s3)
    75  	}
    76  }