...

Source file src/github.com/go-openapi/strfmt/default_test.go

Documentation: github.com/go-openapi/strfmt

     1  // Copyright 2015 go-swagger maintainers
     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 strfmt
    16  
    17  import (
    18  	"database/sql"
    19  	"database/sql/driver"
    20  	"encoding"
    21  	"encoding/base64"
    22  	"encoding/json"
    23  	"fmt"
    24  	"io"
    25  	"reflect"
    26  	"regexp"
    27  	"strings"
    28  	"testing"
    29  
    30  	"github.com/google/uuid"
    31  	"github.com/stretchr/testify/assert"
    32  	"github.com/stretchr/testify/require"
    33  	"go.mongodb.org/mongo-driver/bson"
    34  )
    35  
    36  func TestFormatURI(t *testing.T) {
    37  	uri := URI("http://somewhere.com")
    38  	str := "http://somewhereelse.com"
    39  	testStringFormat(t, &uri, "uri", str, []string{}, []string{"somewhere.com"})
    40  }
    41  
    42  func TestFormatEmail(t *testing.T) {
    43  	email := Email("somebody@somewhere.com")
    44  	str := string("somebodyelse@somewhere.com")
    45  	validEmails := []string{
    46  		"blah@gmail.com",
    47  		"test@d.verylongtoplevel",
    48  		"email+tag@gmail.com",
    49  		`" "@example.com`,
    50  		`"Abc\@def"@example.com`,
    51  		`"Fred Bloggs"@example.com`,
    52  		`"Joe\\Blow"@example.com`,
    53  		`"Abc@def"@example.com`,
    54  		"customer/department=shipping@example.com",
    55  		"$A12345@example.com",
    56  		"!def!xyz%abc@example.com",
    57  		"_somename@example.com",
    58  		"!#$%&'*+-/=?^_`{}|~@example.com",
    59  		"Miles.O'Brian@example.com",
    60  		"postmaster@☁→❄→☃→☀→☺→☂→☹→✝.ws",
    61  		"root@localhost",
    62  		"john@com",
    63  		"api@piston.ninja",
    64  	}
    65  
    66  	testStringFormat(t, &email, "email", str, validEmails, []string{"somebody@somewhere@com"})
    67  }
    68  
    69  func TestFormatHostname(t *testing.T) {
    70  	hostname := Hostname("somewhere.com")
    71  	str := string("somewhere.com")
    72  	veryLongStr := strings.Repeat("a", 256)
    73  	longStr := strings.Repeat("a", 64)
    74  	longAddrSegment := strings.Join([]string{"x", "y", longStr}, ".")
    75  	invalidHostnames := []string{
    76  		"somewhere.com!",
    77  		"user@email.domain",
    78  		"1.1.1.1",
    79  		veryLongStr,
    80  		longAddrSegment,
    81  		// dashes
    82  		"www.example-.org",
    83  		"www.--example.org",
    84  		"-www.example.org",
    85  		"www-.example.org",
    86  		"www.d-.org",
    87  		"www.-d.org",
    88  		"www-",
    89  		"-www",
    90  		// other characters (not in symbols)
    91  		"www.ex ample.org",
    92  		"_www.example.org",
    93  		"www.ex;ample.org",
    94  		"www.example_underscored.org",
    95  		// short top-level domains
    96  		"www.詹姆斯.x",
    97  		"a.b.c.d",
    98  		"-xyz",
    99  		"xyz-",
   100  		"x.",
   101  		"a.b.c.dot-",
   102  		"a.b.c.é;ö",
   103  	}
   104  	validHostnames := []string{
   105  		"somewhere.com",
   106  		"888.com",
   107  		"a.com",
   108  		"a.b.com",
   109  		"a.b.c.com",
   110  		"a.b.c.d.com",
   111  		"a.b.c.d.e.com",
   112  		"1.com",
   113  		"1.2.com",
   114  		"1.2.3.com",
   115  		"1.2.3.4.com",
   116  		"99.domain.com",
   117  		"99.99.domain.com",
   118  		"1wwworg.example.com", // valid, per RFC1123
   119  		"1000wwworg.example.com",
   120  		"xn--bcher-kva.example.com", // puny encoded
   121  		"xn-80ak6aa92e.co",
   122  		"xn-80ak6aa92e.com",
   123  		"xn--ls8h.la",
   124  		"☁→❄→☃→☀→☺→☂→☹→✝.ws",
   125  		"www.example.onion",
   126  		"www.example.ôlà",
   127  		"ôlà.ôlà",
   128  		"ôlà.ôlà.ôlà",
   129  		"ex$ample",
   130  		"localhost",
   131  		"example",
   132  		"x",
   133  		"x-y",
   134  		"a.b.c.dot",
   135  		"www.example.org",
   136  		"a.b.c.d.e.f.g.dot",
   137  		// extended symbol alphabet
   138  		"ex=ample.com",
   139  		"<foo>",
   140  		"www.example-hyphenated.org",
   141  		// localized hostnames
   142  		"www.詹姆斯.org",
   143  		"www.élégigôö.org",
   144  		// long top-level domains
   145  		"www.詹姆斯.london",
   146  	}
   147  
   148  	testStringFormat(t, &hostname, "hostname", str, []string{}, invalidHostnames)
   149  	testStringFormat(t, &hostname, "hostname", str, validHostnames, []string{})
   150  }
   151  
   152  func TestFormatIPv4(t *testing.T) {
   153  	ipv4 := IPv4("192.168.254.1")
   154  	str := string("192.168.254.2")
   155  	testStringFormat(t, &ipv4, "ipv4", str, []string{}, []string{"198.168.254.2.2"})
   156  }
   157  
   158  func TestFormatIPv6(t *testing.T) {
   159  	ipv6 := IPv6("::1")
   160  	str := string("::2")
   161  	// TODO: test ipv6 zones
   162  	testStringFormat(t, &ipv6, "ipv6", str, []string{}, []string{"127.0.0.1"})
   163  }
   164  
   165  func TestFormatCIDR(t *testing.T) {
   166  	cidr := CIDR("192.168.254.1/24")
   167  	str := string("192.168.254.2/24")
   168  	testStringFormat(t, &cidr, "cidr", str, []string{"192.0.2.1/24", "2001:db8:a0b:12f0::1/32"}, []string{"198.168.254.2", "2001:db8:a0b:12f0::1"})
   169  }
   170  
   171  func TestFormatMAC(t *testing.T) {
   172  	mac := MAC("01:02:03:04:05:06")
   173  	str := string("06:05:04:03:02:01")
   174  	testStringFormat(t, &mac, "mac", str, []string{}, []string{"01:02:03:04:05"})
   175  }
   176  
   177  func TestFormatUUID3(t *testing.T) {
   178  	first3 := uuid.NewMD5(uuid.NameSpaceURL, []byte("somewhere.com"))
   179  	other3 := uuid.NewMD5(uuid.NameSpaceURL, []byte("somewhereelse.com"))
   180  	other4 := uuid.Must(uuid.NewRandom())
   181  	other5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhereelse.com"))
   182  	uuid3 := UUID3(first3.String())
   183  	str := other3.String()
   184  	testStringFormat(t, &uuid3, "uuid3", str,
   185  		[]string{
   186  			other3.String(),
   187  			strings.ReplaceAll(other3.String(), "-", ""),
   188  		},
   189  		[]string{
   190  			"not-a-uuid",
   191  			other4.String(),
   192  			other5.String(),
   193  			strings.ReplaceAll(other4.String(), "-", ""),
   194  			strings.ReplaceAll(other5.String(), "-", ""),
   195  			strings.Replace(other3.String(), "-", "", 2),
   196  			strings.Replace(other4.String(), "-", "", 2),
   197  			strings.Replace(other5.String(), "-", "", 2),
   198  		},
   199  	)
   200  
   201  	// special case for zero UUID
   202  	var uuidZero UUID3
   203  	err := uuidZero.UnmarshalJSON([]byte(jsonNull))
   204  	require.NoError(t, err)
   205  	assert.EqualValues(t, UUID3(""), uuidZero)
   206  }
   207  
   208  func TestFormatUUID4(t *testing.T) {
   209  	first4 := uuid.Must(uuid.NewRandom())
   210  	other3 := uuid.NewMD5(uuid.NameSpaceURL, []byte("somewhere.com"))
   211  	other4 := uuid.Must(uuid.NewRandom())
   212  	other5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhereelse.com"))
   213  	uuid4 := UUID4(first4.String())
   214  	str := other4.String()
   215  	testStringFormat(t, &uuid4, "uuid4", str,
   216  		[]string{
   217  			other4.String(),
   218  			strings.ReplaceAll(other4.String(), "-", ""),
   219  		},
   220  		[]string{
   221  			"not-a-uuid",
   222  			other3.String(),
   223  			other5.String(),
   224  			strings.ReplaceAll(other3.String(), "-", ""),
   225  			strings.ReplaceAll(other5.String(), "-", ""),
   226  			strings.Replace(other3.String(), "-", "", 2),
   227  			strings.Replace(other4.String(), "-", "", 2),
   228  			strings.Replace(other5.String(), "-", "", 2),
   229  		},
   230  	)
   231  
   232  	// special case for zero UUID
   233  	var uuidZero UUID4
   234  	err := uuidZero.UnmarshalJSON([]byte(jsonNull))
   235  	require.NoError(t, err)
   236  	assert.EqualValues(t, UUID4(""), uuidZero)
   237  }
   238  
   239  func TestFormatUUID5(t *testing.T) {
   240  	first5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhere.com"))
   241  	other3 := uuid.NewMD5(uuid.NameSpaceURL, []byte("somewhere.com"))
   242  	other4 := uuid.Must(uuid.NewRandom())
   243  	other5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhereelse.com"))
   244  	uuid5 := UUID5(first5.String())
   245  	str := other5.String()
   246  	testStringFormat(t, &uuid5, "uuid5", str,
   247  		[]string{
   248  			other5.String(),
   249  			strings.ReplaceAll(other5.String(), "-", ""),
   250  		},
   251  		[]string{
   252  			"not-a-uuid",
   253  			other3.String(),
   254  			other4.String(),
   255  			strings.ReplaceAll(other3.String(), "-", ""),
   256  			strings.ReplaceAll(other4.String(), "-", ""),
   257  			strings.Replace(other3.String(), "-", "", 2),
   258  			strings.Replace(other4.String(), "-", "", 2),
   259  			strings.Replace(other5.String(), "-", "", 2),
   260  		},
   261  	)
   262  
   263  	// special case for zero UUID
   264  	var uuidZero UUID5
   265  	err := uuidZero.UnmarshalJSON([]byte(jsonNull))
   266  	require.NoError(t, err)
   267  	assert.EqualValues(t, UUID5(""), uuidZero)
   268  }
   269  
   270  func TestFormatUUID(t *testing.T) {
   271  	first5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhere.com"))
   272  	other3 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhereelse.com"))
   273  	other4 := uuid.Must(uuid.NewRandom())
   274  	other5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhereelse.com"))
   275  	other6 := uuid.Must(uuid.NewV6())
   276  	other7 := uuid.Must(uuid.NewV7())
   277  	microsoft := "0" + other4.String() + "f"
   278  
   279  	uuid := UUID(first5.String())
   280  	str := other5.String()
   281  	testStringFormat(t, &uuid, "uuid", str,
   282  		[]string{
   283  			other3.String(),
   284  			other4.String(),
   285  			other5.String(),
   286  			strings.ReplaceAll(other3.String(), "-", ""),
   287  			strings.ReplaceAll(other4.String(), "-", ""),
   288  			strings.ReplaceAll(other5.String(), "-", ""),
   289  			other6.String(),
   290  			other7.String(),
   291  			microsoft,
   292  		},
   293  		[]string{
   294  			"not-a-uuid",
   295  			strings.Replace(other3.String(), "-", "", 2),
   296  			strings.Replace(other4.String(), "-", "", 2),
   297  			strings.Replace(other5.String(), "-", "", 2),
   298  		},
   299  	)
   300  
   301  	// special case for zero UUID
   302  	var uuidZero UUID
   303  	err := uuidZero.UnmarshalJSON([]byte(jsonNull))
   304  	require.NoError(t, err)
   305  	assert.EqualValues(t, UUID(""), uuidZero)
   306  }
   307  
   308  func TestFormatISBN(t *testing.T) {
   309  	isbn := ISBN("0321751043")
   310  	str := string("0321751043")
   311  	testStringFormat(t, &isbn, "isbn", str, []string{}, []string{"836217463"}) // bad checksum
   312  }
   313  
   314  func TestFormatISBN10(t *testing.T) {
   315  	isbn10 := ISBN10("0321751043")
   316  	str := string("0321751043")
   317  	testStringFormat(t, &isbn10, "isbn10", str, []string{}, []string{"836217463"}) // bad checksum
   318  }
   319  
   320  func TestFormatISBN13(t *testing.T) {
   321  	isbn13 := ISBN13("978-0321751041")
   322  	str := string("978-0321751041")
   323  	testStringFormat(t, &isbn13, "isbn13", str, []string{}, []string{"978-0321751042"}) // bad checksum
   324  }
   325  
   326  func TestFormatHexColor(t *testing.T) {
   327  	hexColor := HexColor("#FFFFFF")
   328  	str := string("#000000")
   329  	testStringFormat(t, &hexColor, "hexcolor", str, []string{}, []string{"#fffffffz"})
   330  }
   331  
   332  func TestFormatRGBColor(t *testing.T) {
   333  	rgbColor := RGBColor("rgb(255,255,255)")
   334  	str := string("rgb(0,0,0)")
   335  	testStringFormat(t, &rgbColor, "rgbcolor", str, []string{}, []string{"rgb(300,0,0)"})
   336  }
   337  
   338  func TestFormatSSN(t *testing.T) {
   339  	ssn := SSN("111-11-1111")
   340  	str := string("999 99 9999")
   341  	testStringFormat(t, &ssn, "ssn", str, []string{}, []string{"999 99 999"})
   342  }
   343  
   344  func TestFormatCreditCard(t *testing.T) {
   345  	creditCard := CreditCard("4111-1111-1111-1111")
   346  	str := string("4012-8888-8888-1881")
   347  	testStringFormat(t, &creditCard, "creditcard", str, []string{}, []string{"9999-9999-9999-999"})
   348  }
   349  
   350  func TestFormatPassword(t *testing.T) {
   351  	password := Password("super secret stuff here")
   352  	testStringFormat(t, &password, "password", "super secret!!!", []string{"even more secret"}, []string{})
   353  }
   354  
   355  func TestFormatBase64(t *testing.T) {
   356  	const b64 string = "This is a byte array with unprintable chars, but it also isn"
   357  	str := base64.URLEncoding.EncodeToString([]byte(b64))
   358  	b := []byte(b64)
   359  	expected := Base64(b)
   360  	bj := []byte("\"" + str + "\"")
   361  
   362  	var subj Base64
   363  	err := subj.UnmarshalText([]byte(str))
   364  	require.NoError(t, err)
   365  	assert.EqualValues(t, expected, subj)
   366  
   367  	b, err = subj.MarshalText()
   368  	require.NoError(t, err)
   369  	assert.Equal(t, []byte(str), b)
   370  
   371  	var subj2 Base64
   372  	err = subj2.UnmarshalJSON(bj)
   373  	require.NoError(t, err)
   374  	assert.EqualValues(t, expected, subj2)
   375  
   376  	b, err = subj2.MarshalJSON()
   377  	require.NoError(t, err)
   378  	assert.Equal(t, bj, b)
   379  
   380  	bsonData, err := bson.Marshal(subj2)
   381  	require.NoError(t, err)
   382  
   383  	var b64Copy Base64
   384  	err = bson.Unmarshal(bsonData, &b64Copy)
   385  	require.NoError(t, err)
   386  	assert.Equal(t, subj2, b64Copy)
   387  
   388  	testValid(t, "byte", str)
   389  	testInvalid(t, "byte", "ZWxpemFiZXRocG9zZXk") // missing pad char
   390  
   391  	// Valuer interface
   392  	sqlvalue, err := subj2.Value()
   393  	require.NoError(t, err)
   394  	sqlvalueAsString, ok := sqlvalue.(string)
   395  	if assert.Truef(t, ok, "[%s]Value: expected driver value to be a string", "byte") {
   396  		assert.EqualValuesf(t, str, sqlvalueAsString, "[%s]Value: expected %v and %v to be equal", "byte", sqlvalue, str)
   397  	}
   398  	// Scanner interface
   399  	var subj3 Base64
   400  	err = subj3.Scan([]byte(str))
   401  	require.NoError(t, err)
   402  	assert.EqualValues(t, str, subj3.String())
   403  
   404  	var subj4 Base64
   405  	err = subj4.Scan(str)
   406  	require.NoError(t, err)
   407  	assert.EqualValues(t, str, subj4.String())
   408  
   409  	err = subj4.Scan(123)
   410  	require.Error(t, err)
   411  }
   412  
   413  type testableFormat interface {
   414  	encoding.TextMarshaler
   415  	encoding.TextUnmarshaler
   416  	json.Marshaler
   417  	json.Unmarshaler
   418  	bson.Marshaler
   419  	bson.Unmarshaler
   420  	fmt.Stringer
   421  	sql.Scanner
   422  	driver.Valuer
   423  }
   424  
   425  func testStringFormat(t *testing.T, what testableFormat, format, with string, validSamples, invalidSamples []string) {
   426  	t.Helper()
   427  
   428  	// text encoding interface
   429  	b := []byte(with)
   430  	err := what.UnmarshalText(b)
   431  	require.NoError(t, err)
   432  
   433  	val := reflect.Indirect(reflect.ValueOf(what))
   434  	strVal := val.String()
   435  	assert.Equalf(t, with, strVal, "[%s]UnmarshalText: expected %v and %v to be value equal", format, strVal, with)
   436  
   437  	b, err = what.MarshalText()
   438  	require.NoError(t, err)
   439  	assert.Equalf(t, []byte(with), b, "[%s]MarshalText: expected %v and %v to be value equal as []byte", format, string(b), with)
   440  
   441  	// Stringer
   442  	strVal = what.String()
   443  	assert.Equalf(t, []byte(with), b, "[%s]String: expected %v and %v to be equal", strVal, with)
   444  
   445  	// JSON encoding interface
   446  	bj := []byte("\"" + with + "\"")
   447  	err = what.UnmarshalJSON(bj)
   448  	require.NoError(t, err)
   449  	val = reflect.Indirect(reflect.ValueOf(what))
   450  	strVal = val.String()
   451  	assert.EqualValuesf(t, with, strVal, "[%s]UnmarshalJSON: expected %v and %v to be value equal", format, strVal, with)
   452  
   453  	b, err = what.MarshalJSON()
   454  	require.NoError(t, err)
   455  	assert.Equalf(t, bj, b, "[%s]MarshalJSON: expected %v and %v to be value equal as []byte", format, string(b), with)
   456  
   457  	// bson encoding interface
   458  	bsonData, err := bson.Marshal(what)
   459  	require.NoError(t, err)
   460  
   461  	resetValue(t, format, what)
   462  
   463  	err = bson.Unmarshal(bsonData, what)
   464  	require.NoError(t, err)
   465  	val = reflect.Indirect(reflect.ValueOf(what))
   466  	strVal = val.String()
   467  	assert.EqualValuesf(t, with, strVal, "[%s]bson.Unmarshal: expected %v and %v to be equal (reset value) ", format, what, with)
   468  
   469  	// Scanner interface
   470  	resetValue(t, format, what)
   471  	err = what.Scan(with)
   472  	require.NoError(t, err)
   473  	val = reflect.Indirect(reflect.ValueOf(what))
   474  	strVal = val.String()
   475  	assert.EqualValuesf(t, with, strVal, "[%s]Scan: expected %v and %v to be value equal", format, strVal, with)
   476  
   477  	err = what.Scan([]byte(with))
   478  	require.NoError(t, err)
   479  	val = reflect.Indirect(reflect.ValueOf(what))
   480  	strVal = val.String()
   481  	assert.EqualValuesf(t, with, strVal, "[%s]Scan: expected %v and %v to be value equal", format, strVal, with)
   482  
   483  	err = what.Scan(123)
   484  	require.Error(t, err)
   485  
   486  	// Valuer interface
   487  	sqlvalue, err := what.Value()
   488  	require.NoError(t, err)
   489  	sqlvalueAsString, ok := sqlvalue.(string)
   490  	if assert.Truef(t, ok, "[%s]Value: expected driver value to be a string", format) {
   491  		assert.EqualValuesf(t, with, sqlvalueAsString, "[%s]Value: expected %v and %v to be equal", format, sqlvalue, with)
   492  	}
   493  
   494  	// validation with Registry
   495  	for _, valid := range append(validSamples, with) {
   496  		testValid(t, format, valid)
   497  	}
   498  
   499  	for _, invalid := range invalidSamples {
   500  		testInvalid(t, format, invalid)
   501  	}
   502  }
   503  
   504  func resetValue(t *testing.T, format string, what encoding.TextUnmarshaler) {
   505  	t.Helper()
   506  
   507  	err := what.UnmarshalText([]byte("reset value"))
   508  	require.NoError(t, err)
   509  	val := reflect.Indirect(reflect.ValueOf(what))
   510  	strVal := val.String()
   511  	assert.Equalf(t, "reset value", strVal, "[%s]UnmarshalText: expected %v and %v to be equal (reset value) ", format, strVal, "reset value")
   512  }
   513  
   514  func testValid(t *testing.T, name, value string) {
   515  	t.Helper()
   516  
   517  	ok := Default.Validates(name, value)
   518  	if !ok {
   519  		t.Errorf("expected %q of type %s to be valid", value, name)
   520  	}
   521  }
   522  
   523  func testInvalid(t *testing.T, name, value string) {
   524  	t.Helper()
   525  
   526  	ok := Default.Validates(name, value)
   527  	if ok {
   528  		t.Errorf("expected %q of type %s to be invalid", value, name)
   529  	}
   530  }
   531  
   532  func TestDeepCopyBase64(t *testing.T) {
   533  	b64 := Base64("ZWxpemFiZXRocG9zZXk=")
   534  	in := &b64
   535  
   536  	out := new(Base64)
   537  	in.DeepCopyInto(out)
   538  	assert.Equal(t, in, out)
   539  
   540  	out2 := in.DeepCopy()
   541  	assert.Equal(t, in, out2)
   542  
   543  	var inNil *Base64
   544  	out3 := inNil.DeepCopy()
   545  	assert.Nil(t, out3)
   546  }
   547  
   548  func TestDeepCopyURI(t *testing.T) {
   549  	uri := URI("http://somewhere.com")
   550  	in := &uri
   551  
   552  	out := new(URI)
   553  	in.DeepCopyInto(out)
   554  	assert.Equal(t, in, out)
   555  
   556  	out2 := in.DeepCopy()
   557  	assert.Equal(t, in, out2)
   558  
   559  	var inNil *URI
   560  	out3 := inNil.DeepCopy()
   561  	assert.Nil(t, out3)
   562  }
   563  
   564  func TestDeepCopyEmail(t *testing.T) {
   565  	email := Email("somebody@somewhere.com")
   566  	in := &email
   567  
   568  	out := new(Email)
   569  	in.DeepCopyInto(out)
   570  	assert.Equal(t, in, out)
   571  
   572  	out2 := in.DeepCopy()
   573  	assert.Equal(t, in, out2)
   574  
   575  	var inNil *Email
   576  	out3 := inNil.DeepCopy()
   577  	assert.Nil(t, out3)
   578  }
   579  
   580  func TestDeepCopyHostname(t *testing.T) {
   581  	hostname := Hostname("somewhere.com")
   582  	in := &hostname
   583  
   584  	out := new(Hostname)
   585  	in.DeepCopyInto(out)
   586  	assert.Equal(t, in, out)
   587  
   588  	out2 := in.DeepCopy()
   589  	assert.Equal(t, in, out2)
   590  
   591  	var inNil *Hostname
   592  	out3 := inNil.DeepCopy()
   593  	assert.Nil(t, out3)
   594  }
   595  
   596  func TestDeepCopyIPv4(t *testing.T) {
   597  	ipv4 := IPv4("192.168.254.1")
   598  	in := &ipv4
   599  
   600  	out := new(IPv4)
   601  	in.DeepCopyInto(out)
   602  	assert.Equal(t, in, out)
   603  
   604  	out2 := in.DeepCopy()
   605  	assert.Equal(t, in, out2)
   606  
   607  	var inNil *IPv4
   608  	out3 := inNil.DeepCopy()
   609  	assert.Nil(t, out3)
   610  }
   611  
   612  func TestDeepCopyIPv6(t *testing.T) {
   613  	ipv6 := IPv6("::1")
   614  	in := &ipv6
   615  
   616  	out := new(IPv6)
   617  	in.DeepCopyInto(out)
   618  	assert.Equal(t, in, out)
   619  
   620  	out2 := in.DeepCopy()
   621  	assert.Equal(t, in, out2)
   622  
   623  	var inNil *IPv6
   624  	out3 := inNil.DeepCopy()
   625  	assert.Nil(t, out3)
   626  }
   627  
   628  func TestDeepCopyCIDR(t *testing.T) {
   629  	cidr := CIDR("192.0.2.1/24")
   630  	in := &cidr
   631  
   632  	out := new(CIDR)
   633  	in.DeepCopyInto(out)
   634  	assert.Equal(t, in, out)
   635  
   636  	out2 := in.DeepCopy()
   637  	assert.Equal(t, in, out2)
   638  
   639  	var inNil *CIDR
   640  	out3 := inNil.DeepCopy()
   641  	assert.Nil(t, out3)
   642  }
   643  
   644  func TestDeepCopyMAC(t *testing.T) {
   645  	mac := MAC("01:02:03:04:05:06")
   646  	in := &mac
   647  
   648  	out := new(MAC)
   649  	in.DeepCopyInto(out)
   650  	assert.Equal(t, in, out)
   651  
   652  	out2 := in.DeepCopy()
   653  	assert.Equal(t, in, out2)
   654  
   655  	var inNil *MAC
   656  	out3 := inNil.DeepCopy()
   657  	assert.Nil(t, out3)
   658  }
   659  
   660  func TestDeepCopyUUID(t *testing.T) {
   661  	first5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhere.com"))
   662  	uuid := UUID(first5.String())
   663  	in := &uuid
   664  
   665  	out := new(UUID)
   666  	in.DeepCopyInto(out)
   667  	assert.Equal(t, in, out)
   668  
   669  	out2 := in.DeepCopy()
   670  	assert.Equal(t, in, out2)
   671  
   672  	var inNil *UUID
   673  	out3 := inNil.DeepCopy()
   674  	assert.Nil(t, out3)
   675  }
   676  
   677  func TestDeepCopyUUID3(t *testing.T) {
   678  	first3 := uuid.NewMD5(uuid.NameSpaceURL, []byte("somewhere.com"))
   679  	uuid3 := UUID3(first3.String())
   680  	in := &uuid3
   681  
   682  	out := new(UUID3)
   683  	in.DeepCopyInto(out)
   684  	assert.Equal(t, in, out)
   685  
   686  	out2 := in.DeepCopy()
   687  	assert.Equal(t, in, out2)
   688  
   689  	var inNil *UUID3
   690  	out3 := inNil.DeepCopy()
   691  	assert.Nil(t, out3)
   692  }
   693  
   694  func TestDeepCopyUUID4(t *testing.T) {
   695  	first4 := uuid.Must(uuid.NewRandom())
   696  	uuid4 := UUID4(first4.String())
   697  	in := &uuid4
   698  
   699  	out := new(UUID4)
   700  	in.DeepCopyInto(out)
   701  	assert.Equal(t, in, out)
   702  
   703  	out2 := in.DeepCopy()
   704  	assert.Equal(t, in, out2)
   705  
   706  	var inNil *UUID4
   707  	out3 := inNil.DeepCopy()
   708  	assert.Nil(t, out3)
   709  }
   710  
   711  func TestDeepCopyUUID5(t *testing.T) {
   712  	first5 := uuid.NewSHA1(uuid.NameSpaceURL, []byte("somewhere.com"))
   713  	uuid5 := UUID5(first5.String())
   714  	in := &uuid5
   715  
   716  	out := new(UUID5)
   717  	in.DeepCopyInto(out)
   718  	assert.Equal(t, in, out)
   719  
   720  	out2 := in.DeepCopy()
   721  	assert.Equal(t, in, out2)
   722  
   723  	var inNil *UUID5
   724  	out3 := inNil.DeepCopy()
   725  	assert.Nil(t, out3)
   726  }
   727  
   728  func TestDeepCopyISBN(t *testing.T) {
   729  	isbn := ISBN("0321751043")
   730  	in := &isbn
   731  
   732  	out := new(ISBN)
   733  	in.DeepCopyInto(out)
   734  	assert.Equal(t, in, out)
   735  
   736  	out2 := in.DeepCopy()
   737  	assert.Equal(t, in, out2)
   738  
   739  	var inNil *ISBN
   740  	out3 := inNil.DeepCopy()
   741  	assert.Nil(t, out3)
   742  }
   743  
   744  func TestDeepCopyISBN10(t *testing.T) {
   745  	isbn10 := ISBN10("0321751043")
   746  	in := &isbn10
   747  
   748  	out := new(ISBN10)
   749  	in.DeepCopyInto(out)
   750  	assert.Equal(t, in, out)
   751  
   752  	out2 := in.DeepCopy()
   753  	assert.Equal(t, in, out2)
   754  
   755  	var inNil *ISBN10
   756  	out3 := inNil.DeepCopy()
   757  	assert.Nil(t, out3)
   758  }
   759  
   760  func TestDeepCopyISBN13(t *testing.T) {
   761  	isbn13 := ISBN13("978-0321751041")
   762  	in := &isbn13
   763  
   764  	out := new(ISBN13)
   765  	in.DeepCopyInto(out)
   766  	assert.Equal(t, in, out)
   767  
   768  	out2 := in.DeepCopy()
   769  	assert.Equal(t, in, out2)
   770  
   771  	var inNil *ISBN13
   772  	out3 := inNil.DeepCopy()
   773  	assert.Nil(t, out3)
   774  }
   775  
   776  func TestDeepCopyCreditCard(t *testing.T) {
   777  	creditCard := CreditCard("4111-1111-1111-1111")
   778  	in := &creditCard
   779  
   780  	out := new(CreditCard)
   781  	in.DeepCopyInto(out)
   782  	assert.Equal(t, in, out)
   783  
   784  	out2 := in.DeepCopy()
   785  	assert.Equal(t, in, out2)
   786  
   787  	var inNil *CreditCard
   788  	out3 := inNil.DeepCopy()
   789  	assert.Nil(t, out3)
   790  }
   791  
   792  func TestDeepCopySSN(t *testing.T) {
   793  	ssn := SSN("111-11-1111")
   794  	in := &ssn
   795  
   796  	out := new(SSN)
   797  	in.DeepCopyInto(out)
   798  	assert.Equal(t, in, out)
   799  
   800  	out2 := in.DeepCopy()
   801  	assert.Equal(t, in, out2)
   802  
   803  	var inNil *SSN
   804  	out3 := inNil.DeepCopy()
   805  	assert.Nil(t, out3)
   806  }
   807  
   808  func TestDeepCopyHexColor(t *testing.T) {
   809  	hexColor := HexColor("#FFFFFF")
   810  	in := &hexColor
   811  
   812  	out := new(HexColor)
   813  	in.DeepCopyInto(out)
   814  	assert.Equal(t, in, out)
   815  
   816  	out2 := in.DeepCopy()
   817  	assert.Equal(t, in, out2)
   818  
   819  	var inNil *HexColor
   820  	out3 := inNil.DeepCopy()
   821  	assert.Nil(t, out3)
   822  }
   823  
   824  func TestDeepCopyRGBColor(t *testing.T) {
   825  	rgbColor := RGBColor("rgb(255,255,255)")
   826  	in := &rgbColor
   827  
   828  	out := new(RGBColor)
   829  	in.DeepCopyInto(out)
   830  	assert.Equal(t, in, out)
   831  
   832  	out2 := in.DeepCopy()
   833  	assert.Equal(t, in, out2)
   834  
   835  	var inNil *RGBColor
   836  	out3 := inNil.DeepCopy()
   837  	assert.Nil(t, out3)
   838  }
   839  
   840  func TestDeepCopyPassword(t *testing.T) {
   841  	password := Password("super secret stuff here")
   842  	in := &password
   843  
   844  	out := new(Password)
   845  	in.DeepCopyInto(out)
   846  	assert.Equal(t, in, out)
   847  
   848  	out2 := in.DeepCopy()
   849  	assert.Equal(t, in, out2)
   850  
   851  	var inNil *Password
   852  	out3 := inNil.DeepCopy()
   853  	assert.Nil(t, out3)
   854  }
   855  
   856  func BenchmarkIsUUID(b *testing.B) {
   857  	const sampleSize = 100
   858  	rxUUID := regexp.MustCompile(UUIDPattern)
   859  	rxUUID3 := regexp.MustCompile(UUID3Pattern)
   860  	rxUUID4 := regexp.MustCompile(UUID4Pattern)
   861  	rxUUID5 := regexp.MustCompile(UUID5Pattern)
   862  
   863  	uuids := make([]string, 0, sampleSize)
   864  	uuid3s := make([]string, 0, sampleSize)
   865  	uuid4s := make([]string, 0, sampleSize)
   866  	uuid5s := make([]string, 0, sampleSize)
   867  
   868  	for i := 0; i < sampleSize; i++ {
   869  		seed := []byte(uuid.Must(uuid.NewRandom()).String())
   870  		uuids = append(uuids, uuid.Must(uuid.NewRandom()).String())
   871  		uuid3s = append(uuid3s, uuid.NewMD5(uuid.NameSpaceURL, seed).String())
   872  		uuid4s = append(uuid4s, uuid.Must(uuid.NewRandom()).String())
   873  		uuid5s = append(uuid5s, uuid.NewSHA1(uuid.NameSpaceURL, seed).String())
   874  	}
   875  
   876  	b.Run("IsUUID - google.uuid", benchmarkIs(uuids, IsUUID))
   877  	b.Run("IsUUID - regexp", benchmarkIs(uuids, func(id string) bool { return rxUUID.MatchString(id) }))
   878  
   879  	b.Run("IsUUIDv3 - google.uuid", benchmarkIs(uuid3s, IsUUID3))
   880  	b.Run("IsUUIDv3 - regexp", benchmarkIs(uuid3s, func(id string) bool { return rxUUID3.MatchString(id) }))
   881  
   882  	b.Run("IsUUIDv4 - google.uuid", benchmarkIs(uuid4s, IsUUID4))
   883  	b.Run("IsUUIDv4 - regexp", benchmarkIs(uuid4s, func(id string) bool { return rxUUID4.MatchString(id) }))
   884  
   885  	b.Run("IsUUIDv5 - google.uuid", benchmarkIs(uuid5s, IsUUID5))
   886  	b.Run("IsUUIDv5 - regexp", benchmarkIs(uuid5s, func(id string) bool { return rxUUID5.MatchString(id) }))
   887  }
   888  
   889  func benchmarkIs(input []string, fn func(string) bool) func(*testing.B) {
   890  	return func(b *testing.B) {
   891  		var isTrue bool
   892  		b.ReportAllocs()
   893  		b.ResetTimer()
   894  		for i := 0; i < b.N; i++ {
   895  			isTrue = fn(input[i%len(input)])
   896  		}
   897  		fmt.Fprintln(io.Discard, isTrue)
   898  	}
   899  }
   900  

View as plain text