github.com/metasources/buildx@v0.0.0-20230418141019-7aa1459cedea/internal/regex_helpers_test.go (about)

     1  package internal
     2  
     3  import (
     4  	"regexp"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestMatchCaptureGroups(t *testing.T) {
    11  	tests := []struct {
    12  		name     string
    13  		input    string
    14  		pattern  string
    15  		expected map[string]string
    16  	}{
    17  		{
    18  			name:    "go-case",
    19  			input:   "match this thing",
    20  			pattern: `(?P<name>match).*(?P<version>thing)`,
    21  			expected: map[string]string{
    22  				"name":    "match",
    23  				"version": "thing",
    24  			},
    25  		},
    26  		{
    27  			name:    "only matches the first instance",
    28  			input:   "match this thing batch another think",
    29  			pattern: `(?P<name>[mb]atch).*?(?P<version>thin[gk])`,
    30  			expected: map[string]string{
    31  				"name":    "match",
    32  				"version": "thing",
    33  			},
    34  		},
    35  		{
    36  			name:    "nested capture groups",
    37  			input:   "cool something to match against",
    38  			pattern: `((?P<name>match) (?P<version>against))`,
    39  			expected: map[string]string{
    40  				"name":    "match",
    41  				"version": "against",
    42  			},
    43  		},
    44  		{
    45  			name:    "nested optional capture groups",
    46  			input:   "cool something to match against",
    47  			pattern: `((?P<name>match) (?P<version>against))?`,
    48  			expected: map[string]string{
    49  				"name":    "match",
    50  				"version": "against",
    51  			},
    52  		},
    53  		{
    54  			name:    "nested optional capture groups with larger match",
    55  			input:   "cool something to match against match never",
    56  			pattern: `.*?((?P<name>match) (?P<version>(against|never)))?`,
    57  			expected: map[string]string{
    58  				"name":    "match",
    59  				"version": "against",
    60  			},
    61  		},
    62  	}
    63  
    64  	for _, test := range tests {
    65  		t.Run(test.name, func(t *testing.T) {
    66  			actual := MatchNamedCaptureGroups(regexp.MustCompile(test.pattern), test.input)
    67  			assert.Equal(t, test.expected, actual)
    68  		})
    69  	}
    70  }