go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/core/resources/regex_unit_test.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package resources
     5  
     6  import (
     7  	"regexp"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  var lre = mqlRegex{}
    15  
    16  func testRegex(t *testing.T, f func() (string, error), matches, fails []string) {
    17  	r, err := f()
    18  	require.NoError(t, err)
    19  
    20  	re, err := regexp.Compile("^" + r + "$")
    21  	require.NoError(t, err)
    22  
    23  	for i := range matches {
    24  		s := matches[i]
    25  		t.Run("matches "+s, func(t *testing.T) {
    26  			assert.True(t, re.MatchString(s))
    27  		})
    28  	}
    29  
    30  	for i := range fails {
    31  		s := fails[i]
    32  		t.Run("fails "+s, func(t *testing.T) {
    33  			assert.False(t, re.MatchString(s))
    34  		})
    35  	}
    36  }
    37  
    38  func TestResource_RegexEmail(t *testing.T) {
    39  	// The following tests are copied from:
    40  	//   https://en.wikipedia.org/wiki/Email_address
    41  	//   Example section
    42  	matches := []string{
    43  		"simple@example.com",
    44  		"very.common@example.com",
    45  		"disposable.style.email.with+symbol@example.com",
    46  		"other.email-with-hyphen@example.com",
    47  		"fully-qualified-domain@example.com",
    48  		"user.name+tag+sorting@example.com",
    49  		"x@example.com",
    50  		"example-indeed@strange-example.com",
    51  		"test/test@test.com",
    52  		"admin@mailserver1", // local domain name with no TLD, although ICANN highly discourages dotless email addresses
    53  		"example@s.example",
    54  		"\" \"@example.org",
    55  		"\"john..doe\"@example.org",
    56  		"mailhost!username@example.org",
    57  		"user%example.com@example.org",
    58  		"user-@example.org",
    59  		"jsmith@[192.168.2.1]",
    60  		"jsmith@[IPv6:2001:db8::1]",
    61  	}
    62  
    63  	fails := []string{
    64  		"Abc.example.com",
    65  		"A@b@c@example.com",
    66  		"a\"b(c)d,e:f;g<h>i[j\\k]l@example.com",
    67  		"just\"not\"right@example.com",
    68  		"this is\"not\\allowed@example.com",
    69  		"this\\ still\\\"not\\\\allowed@example.com",
    70  		"1234567890123456789012345678901234567890123456789012345678901234+x@example.com",
    71  		"i_like_underscore@but_its_not_allowed_in_this_part.example.com",
    72  		"QA[icon]CHOCOLATE[icon]@test.com",
    73  	}
    74  
    75  	testRegex(t, lre.email, matches, fails)
    76  }