/** * 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 . */ 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 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 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 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)); } }