github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/common/math/integer_test.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package math 13 14 import ( 15 "testing" 16 ) 17 18 type operation byte 19 20 const ( 21 sub operation = iota 22 add 23 mul 24 ) 25 26 func TestOverflow(t *testing.T) { 27 for i, test := range []struct { 28 x uint64 29 y uint64 30 overflow bool 31 op operation 32 }{ 33 // add operations 34 {MaxUint64, 1, true, add}, 35 {MaxUint64 - 1, 1, false, add}, 36 37 // sub operations 38 {0, 1, true, sub}, 39 {0, 0, false, sub}, 40 41 // mul operations 42 {0, 0, false, mul}, 43 {10, 10, false, mul}, 44 {MaxUint64, 2, true, mul}, 45 {MaxUint64, 1, false, mul}, 46 } { 47 var overflows bool 48 switch test.op { 49 case sub: 50 _, overflows = SafeSub(test.x, test.y) 51 case add: 52 _, overflows = SafeAdd(test.x, test.y) 53 case mul: 54 _, overflows = SafeMul(test.x, test.y) 55 } 56 57 if test.overflow != overflows { 58 t.Errorf("%d failed. Expected test to be %v, got %v", i, test.overflow, overflows) 59 } 60 } 61 } 62 63 func TestHexOrDecimal64(t *testing.T) { 64 tests := []struct { 65 input string 66 num uint64 67 ok bool 68 }{ 69 {"", 0, true}, 70 {"0", 0, true}, 71 {"0x0", 0, true}, 72 {"12345678", 12345678, true}, 73 {"0x12345678", 0x12345678, true}, 74 {"0X12345678", 0x12345678, true}, 75 // Tests for leading zero behaviour: 76 {"0123456789", 123456789, true}, // note: not octal 77 {"0x00", 0, true}, 78 {"0x012345678abc", 0x12345678abc, true}, 79 // Invalid syntax: 80 {"abcdef", 0, false}, 81 {"0xgg", 0, false}, 82 // Doesn't fit into 64 bits: 83 {"18446744073709551617", 0, false}, 84 } 85 for _, test := range tests { 86 var num HexOrDecimal64 87 err := num.UnmarshalText([]byte(test.input)) 88 if (err == nil) != test.ok { 89 t.Errorf("ParseUint64(%q) -> (err == nil) = %t, want %t", test.input, err == nil, test.ok) 90 continue 91 } 92 if err == nil && uint64(num) != test.num { 93 t.Errorf("ParseUint64(%q) -> %d, want %d", test.input, num, test.num) 94 } 95 } 96 } 97 98 func TestMustParseUint64(t *testing.T) { 99 if v := MustParseUint64("12345"); v != 12345 { 100 t.Errorf(`MustParseUint64("12345") = %d, want 12345`, v) 101 } 102 } 103 104 func TestMustParseUint64Panic(t *testing.T) { 105 defer func() { 106 if recover() == nil { 107 t.Error("MustParseBig should've panicked") 108 } 109 }() 110 MustParseUint64("ggg") 111 }