github.com/mem/u-root@v2.0.1-0.20181004165302-9b18b4636a33+incompatible/pkg/forth/forth_test.go (about) 1 // Copyright 2018 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 forth 6 7 import ( 8 "os" 9 "testing" 10 ) 11 12 type forthTest struct { 13 val string 14 res string 15 err string 16 } 17 18 var forthTests = []forthTest{ 19 {"hostname", "", ""}, 20 {"2", "2", ""}, 21 {"", "2", "Empty stack"}, 22 {"2 2 +", "4", ""}, 23 {"4 2 -", "2", ""}, 24 {"4 2 *", "8", ""}, 25 {"4 2 /", "2", ""}, 26 {"5 2 %", "1", ""}, 27 {"sb43 hostbase", "43", ""}, 28 {"sb43 hostbase dup 20 / swap 20 % dup ifelse", "3", ""}, 29 {"sb40 hostbase dup 20 / swap 20 % dup ifelse", "2", ""}, 30 {"2 4 swap /", "2", ""}, 31 {"0 1 1 ifelse", "1", ""}, 32 {"0 1 0 ifelse", "0", ""}, 33 {"str cat strcat", "strcat", ""}, 34 {"1 dup +", "2", ""}, 35 {"4095 4096 roundup", "4096", ""}, 36 {"4097 8192 roundup", "8192", ""}, 37 {"2 x +", "", "parsing \"x\": invalid syntax"}, 38 {"1 dd +", "2", ""}, 39 {"1 d3d", "3", ""}, 40 } 41 42 func TestForth(t *testing.T) { 43 44 forthTests[0].res, _ = os.Hostname() 45 f := New() 46 if f.Length() != 0 { 47 t.Errorf("Test: stack is %d and should be 0", f.Length()) 48 } 49 if f.Empty() != true { 50 t.Errorf("Test: stack is %v and should be false", f.Empty()) 51 } 52 f.Push("test") 53 if f.Length() != 1 { 54 t.Errorf("Test: stack is %d and should be 1", f.Length()) 55 } 56 if f.Empty() == true { 57 t.Errorf("Test: stack is %v and should be false", f.Empty()) 58 } 59 f.Reset() 60 if f.Length() != 0 { 61 t.Errorf("Test: After Reset(): stack is %d and should be 0", f.Length()) 62 } 63 if f.Empty() != true { 64 t.Errorf("Test: After Reset(): stack is %v and should be true", f.Empty()) 65 } 66 NewWord(f, "dd", "dup") 67 NewWord(f, "d3d", "dup dup + +") 68 for _, tt := range forthTests { 69 var err error 70 res, err := Eval(f, tt.val) 71 if res == tt.res || (err != nil && err.Error() == tt.err) { 72 if err != nil { 73 /* stack is not going to be right; reset it. */ 74 f.Reset() 75 } 76 t.Logf("Test: '%v' '%v' '%v': Pass\n", tt.val, res, err) 77 } else { 78 t.Errorf("Test: '%v' '%v' '%v': Fail\n", tt.val, res, err) 79 t.Logf("ops %v\n", Ops()) 80 } 81 if f.Length() != 0 { 82 t.Errorf("Test: %v: stack is %d and should be empty", tt, f.Length()) 83 } 84 if f.Empty() != true { 85 t.Errorf("Test: %v: stack is %v and should be empty", tt, f.Empty()) 86 } 87 } 88 89 }