1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
/**
* Copyright (C) 2019 Adrien Hopkins
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package sevenUnits.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
// TODO add tests for expression-to-RPN and RPN-to-result
/**
* A test for the {@code ExpressionParser} class. This is NOT part of this
* program's public API.
*
* @author Adrien Hopkins
* @since 2019-03-22
* @since v0.2.0
*/
class ExpressionParserTest {
private static final ExpressionParser<Integer> numberParser = new ExpressionParser.Builder<>(
Integer::parseInt).addBinaryOperator("+", (o1, o2) -> o1 + o2, 0)
.addBinaryOperator("-", (o1, o2) -> o1 - o2, 0)
.addBinaryOperator("*", (o1, o2) -> o1 * o2, 1)
.addBinaryOperator("/", (o1, o2) -> o1 / o2, 1)
.addBinaryOperator("^", (o1, o2) -> (int) Math.pow(o1, o2), 2)
.build();
/**
* The expressions used in the expression parsing tests
*/
private static final List<String> TEST_EXPRESSIONS = List.of(
// test parsing of expressions
"1 + 2 ^ 5 * 3", "(1 + 2) ^ 5 * 3",
"12 * 5 + (3 ^ (2 * 3) - 72) / (3 + 3 * 2)",
// ensure it normally goes from left to right
"1 + 2 + 3 + 4", "12 - 4 - 3", "12 - (4 - 3)", "1 / 2 + 3");
/**
* The expected results for evaluating these expressions
*/
private static final int[] RESULTS = { 97, 729, 133, 10, 5, 11, 3 };
/**
* @return A stream of objects, where each one is an expression and the
* expected result
* @since 2021-09-27
*/
private static final Stream<Arguments> testParseExpressionData() {
return IntStream.range(0, TEST_EXPRESSIONS.size())
.mapToObj(i -> Arguments.of(TEST_EXPRESSIONS.get(i), RESULTS[i]));
}
/**
* Test method for
* {@link sevenUnits.utils.ExpressionParser#parseExpression(java.lang.String)}.
*/
@ParameterizedTest
@MethodSource("testParseExpressionData")
public void testParseExpression(String expression, int value) {
assertEquals(value, numberParser.parseExpression(expression));
}
}
|