github.hscsec.cn/u-root/u-root@v7.0.0+incompatible/pkg/pogosh/arithmetic_test.go (about) 1 // Copyright 2020 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package pogosh 6 7 import ( 8 "math/big" 9 "reflect" 10 "testing" 11 ) 12 13 // Fake variables for the test. 14 func getVar(name string) *big.Int { 15 fakeVars := map[string]*big.Int{ 16 "x": big.NewInt(1), 17 "y": big.NewInt(123), 18 "z": big.NewInt(-1), 19 "xyz": big.NewInt(42), 20 } 21 val, ok := fakeVars[name] 22 if !ok { 23 return big.NewInt(0) 24 } 25 return val 26 } 27 28 // The positive tests are expected to pass parsing. 29 var arithmeticPositiveTests = []struct { 30 name string 31 in string 32 out *big.Int 33 }{ 34 // Constants 35 {"Zero", 36 "0", 37 big.NewInt(0), 38 }, 39 {"Decimal", 40 "123", 41 big.NewInt(123), 42 }, 43 {"Octal", 44 "0123", 45 big.NewInt(0123), 46 }, 47 {"Hex", 48 "0x123", 49 big.NewInt(0x123), 50 }, 51 52 // Order of operation 53 {"BEDMAS1", 54 "1+2*3", 55 big.NewInt(7), 56 }, 57 {"BEDMAS2", 58 "(1+2)*3", 59 big.NewInt(9), 60 }, 61 {"BEDMAS3", 62 "1*2+3", 63 big.NewInt(5), 64 }, 65 {"BEDMAS4", 66 "-1*-2+-+-3", 67 big.NewInt(5), 68 }, 69 70 // Associativity 71 {"Associativity1", 72 "1-2-3", 73 big.NewInt(-4), 74 }, 75 {"Associativity2", 76 "1-2*3-4", 77 big.NewInt(-9), 78 }, 79 80 // Spacing 81 {"Spacing", 82 " 1 + 3 * 4 / 3 - 8 ", 83 big.NewInt(-3), 84 }, 85 86 // Conditional Operator 87 {"Conditional", 88 " 0 ? 4 : 1 ? 5 : 6 ", 89 big.NewInt(5), 90 }, 91 92 // Variables 93 {"Variables1", 94 "x", 95 big.NewInt(1), 96 }, 97 {"Variables2", 98 "x + y", 99 big.NewInt(124), 100 }, 101 {"Variables3", 102 "xyz * 2", 103 big.NewInt(84), 104 }, 105 } 106 107 func TestArithmeticPositive(t *testing.T) { 108 for _, tt := range arithmeticPositiveTests { 109 t.Run(tt.name, func(t *testing.T) { 110 a := Arithmetic{ 111 getVar: getVar, 112 input: tt.in, 113 } 114 got := a.evalExpression() 115 116 if !reflect.DeepEqual(got, tt.out) { 117 t.Errorf("got %v, want %v", got, tt.out) 118 } 119 }) 120 } 121 }