github.com/wI2L/jettison@v0.7.5-0.20230106001914-c70014c6417a/number_test.go (about)

     1  package jettison
     2  
     3  import (
     4  	"regexp"
     5  	"testing"
     6  )
     7  
     8  func TestIsValidNumber(t *testing.T) {
     9  	// Taken from https://golang.org/src/encoding/json/number_test.go
    10  	// Regexp from: https://stackoverflow.com/a/13340826
    11  	var re = regexp.MustCompile(
    12  		`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`,
    13  	)
    14  	valid := []string{
    15  		"0",
    16  		"-0",
    17  		"1",
    18  		"-1",
    19  		"0.1",
    20  		"-0.1",
    21  		"1234",
    22  		"-1234",
    23  		"12.34",
    24  		"-12.34",
    25  		"12E0",
    26  		"12E1",
    27  		"12e34",
    28  		"12E-0",
    29  		"12e+1",
    30  		"12e-34",
    31  		"-12E0",
    32  		"-12E1",
    33  		"-12e34",
    34  		"-12E-0",
    35  		"-12e+1",
    36  		"-12e-34",
    37  		"1.2E0",
    38  		"1.2E1",
    39  		"1.2e34",
    40  		"1.2E-0",
    41  		"1.2e+1",
    42  		"1.2e-34",
    43  		"-1.2E0",
    44  		"-1.2E1",
    45  		"-1.2e34",
    46  		"-1.2E-0",
    47  		"-1.2e+1",
    48  		"-1.2e-34",
    49  		"0E0",
    50  		"0E1",
    51  		"0e34",
    52  		"0E-0",
    53  		"0e+1",
    54  		"0e-34",
    55  		"-0E0",
    56  		"-0E1",
    57  		"-0e34",
    58  		"-0E-0",
    59  		"-0e+1",
    60  		"-0e-34",
    61  	}
    62  	for _, tt := range valid {
    63  		if !isValidNumber(tt) {
    64  			t.Errorf("%s should be valid", tt)
    65  		}
    66  		if !re.MatchString(tt) {
    67  			t.Errorf("%s should be valid but regexp does not match", tt)
    68  		}
    69  	}
    70  	invalid := []string{
    71  		"",
    72  		"-",
    73  		"invalid",
    74  		"1.0.1",
    75  		"1..1",
    76  		"-1-2",
    77  		"012a42",
    78  		"01.2",
    79  		"012",
    80  		"12E12.12",
    81  		"1e2e3",
    82  		"1e+-2",
    83  		"1e--23",
    84  		"1e",
    85  		"e1",
    86  		"1e+",
    87  		"1ea",
    88  		"1a",
    89  		"1.a",
    90  		"1.",
    91  		"01",
    92  		"1.e1",
    93  	}
    94  	for _, tt := range invalid {
    95  		if isValidNumber(tt) {
    96  			t.Errorf("%s should be invalid", tt)
    97  		}
    98  		if re.MatchString(tt) {
    99  			t.Errorf("%s should be invalid but matches regexp", tt)
   100  		}
   101  	}
   102  }