67 lines
2.4 KiB
Go
67 lines
2.4 KiB
Go
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
|
|
// All rights reserved.
|
|
|
|
// t_fractions_test.go
|
|
package expr
|
|
|
|
import (
|
|
"errors"
|
|
"testing"
|
|
)
|
|
|
|
func TestFractionsParser(t *testing.T) {
|
|
section := "Fraction"
|
|
inputs := []inputType{
|
|
/* 1 */ {`1|2`, newFraction(1, 2), nil},
|
|
/* 2 */ {`1|2 + 1`, newFraction(3, 2), nil},
|
|
/* 3 */ {`1|2 - 1`, newFraction(-1, 2), nil},
|
|
/* 4 */ {`1|2 * 1`, newFraction(1, 2), nil},
|
|
/* 5 */ {`1|2 * 2|3`, newFraction(2, 6), nil},
|
|
/* 6 */ {`1|2 / 2|3`, newFraction(3, 4), nil},
|
|
/* 7 */ {`1|"5"`, nil, errors.New(`denominator must be integer, got string (5)`)},
|
|
/* 8 */ {`"1"|5`, nil, errors.New(`numerator must be integer, got string (1)`)},
|
|
/* 9 */ {`1|+5`, nil, errors.New(`[1:3] infix operator "|" requires two non-nil operands, got 1`)},
|
|
/* 10 */ {`1|(-2)`, newFraction(-1, 2), nil},
|
|
/* 11 */ {`builtin "math.arith"; add(1|2, 2|3)`, newFraction(7, 6), nil},
|
|
/* 12 */ {`builtin "math.arith"; add(1|2, 1.0, 2)`, float64(3.5), nil},
|
|
/* 13 */ {`builtin "math.arith"; mul(1|2, 2|3)`, newFraction(2, 6), nil},
|
|
/* 14 */ {`builtin "math.arith"; mul(1|2, 1.0, 2)`, float64(1.0), nil},
|
|
/* 15 */ {`1|0`, nil, errors.New(`division by zero`)},
|
|
/* 16 */ {`fract(-0.5)`, newFraction(-1, 2), nil},
|
|
/* 17 */ {`fract("")`, (*FractionType)(nil), errors.New(`bad syntax`)},
|
|
/* 18 */ {`fract("-1")`, newFraction(-1, 1), nil},
|
|
/* 19 */ {`fract("+1")`, newFraction(1, 1), nil},
|
|
/* 20 */ {`fract("1a")`, (*FractionType)(nil), errors.New(`strconv.ParseInt: parsing "1a": invalid syntax`)},
|
|
/* 21 */ {`fract(1,0)`, nil, errors.New(`fract(): division by zero`)},
|
|
}
|
|
runTestSuite(t, section, inputs)
|
|
}
|
|
|
|
func TestFractionToStringSimple(t *testing.T) {
|
|
source := newFraction(1, 2)
|
|
want := "1|2"
|
|
got := source.ToString(0)
|
|
if got != want {
|
|
t.Errorf(`(1,2) -> result = %v [%T], want = %v [%T]`, got, got, want, want)
|
|
}
|
|
}
|
|
|
|
func TestFractionToStringMultiline(t *testing.T) {
|
|
source := newFraction(1, 2)
|
|
want := "1\n-\n2"
|
|
got := source.ToString(MultiLine)
|
|
if got != want {
|
|
t.Errorf(`(1,2) -> result = %v [%T], want = %v [%T]`, got, got, want, want)
|
|
}
|
|
}
|
|
|
|
// TODO Check this test: the output string ends with a space
|
|
func _TestToStringMultilineTty(t *testing.T) {
|
|
source := newFraction(-1, 2)
|
|
want := "\x1b[4m-1\x1b[0m\n2"
|
|
got := source.ToString(MultiLine | TTY)
|
|
if got != want {
|
|
t.Errorf(`(1,2) -> result = %#v [%T], want = %#v [%T]`, got, got, want, want)
|
|
}
|
|
}
|