go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/builtins/regexp_test.go (about)

     1  // Copyright 2018 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package builtins
    16  
    17  import (
    18  	"testing"
    19  
    20  	"go.starlark.net/starlark"
    21  
    22  	. "github.com/smartystreets/goconvey/convey"
    23  	. "go.chromium.org/luci/common/testing/assertions"
    24  )
    25  
    26  const regexpTest = `
    27  def assert(a, b):
    28    if a != b:
    29      fail("%s != %s" % (a, b))
    30  
    31  def test():
    32    groups = submatches(r'a (\d+) (\d+)', 'a 123 456 tail')
    33    assert(groups, ("a 123 456", "123", "456"))
    34  
    35    groups = submatches(r'a (\d+) (\d+)', 'a huh 456')
    36    assert(groups, ())
    37  
    38    groups = submatches('.*', 'a 123 456 tail')
    39    assert(groups, ("a 123 456 tail",))
    40  
    41    groups = submatches('', 'zzz')
    42    assert(groups, ('',))  # empty match (not the same as no match at all)
    43  
    44  test()
    45  `
    46  
    47  func TestRegexp(t *testing.T) {
    48  	t.Parallel()
    49  
    50  	submatches := RegexpMatcher("submatches")
    51  
    52  	runScript := func(code string) error {
    53  		_, err := starlark.ExecFile(&starlark.Thread{}, "main", code, starlark.StringDict{
    54  			"submatches": submatches,
    55  			"fail":       Fail, // for 'assert'
    56  		})
    57  		return err
    58  	}
    59  
    60  	Convey("Success", t, func() {
    61  		So(runScript(regexpTest), ShouldBeNil)
    62  	})
    63  
    64  	Convey("Fails", t, func() {
    65  		So(runScript(`submatches('(((', '')`), ShouldErrLike, "error parsing regexp")
    66  	})
    67  }