Sonar Fixes and remove obsolete classes

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1876019 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2020-04-01 23:25:33 +00:00
parent efd9c7c277
commit 24c4f94962
5 changed files with 550 additions and 1031 deletions

View File

@ -1,171 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.stress.FileHandler;
import org.apache.poi.stress.HSLFFileHandler;
import org.apache.poi.stress.HSSFFileHandler;
import org.apache.poi.stress.HWPFFileHandler;
import org.apache.poi.stress.XSLFFileHandler;
import org.apache.poi.stress.XSSFFileHandler;
import org.apache.poi.stress.XWPFFileHandler;
import org.junit.Assume;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipException;
import static org.junit.Assert.assertNotNull;
public class BaseIntegrationTest {
private final File rootDir;
private String file;
private FileHandler handler;
public BaseIntegrationTest(File rootDir, String file, FileHandler handler) {
this.rootDir = rootDir;
this.file = file;
this.handler = handler;
}
public void test() throws Exception {
assertNotNull("Unknown file extension for file: " + file + ": " + TestAllFiles.getExtension(file), handler);
testOneFile(new File(rootDir, file));
}
protected void testOneFile(File inputFile) throws Exception {
try {
handleFile(inputFile);
} catch (OfficeXmlFileException e) {
// switch XWPF and HWPF and so forth depending on the error message
handleWrongOLE2XMLExtension(inputFile, e);
} catch (OldFileFormatException e) {
if (e.getClass().equals(OldFileFormatException.class)) {
// Not even text extraction is supported for these: handler.handleExtracting(inputFile);
Assume.assumeFalse("File " + file + " excluded because it is unsupported old Excel format", true);
}
// otherwise try at least to perform extracting tests on these old files
} catch (EncryptedDocumentException e) {
// Do not try to read encrypted files
Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true);
} catch (ZipException e) {
// some files are corrupted
if (e.getMessage().equals("unexpected EOF") || e.getMessage().equals("Truncated ZIP file")) {
Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true);
}
throw e;
} catch (IOException e) {
// ignore some other ways of corrupted files
String message = e.getMessage();
if(message != null && message.contains("Truncated ZIP file")) {
Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true);
}
// sometimes binary format has XML-format-extension...
if(message != null && message.contains("rong file format or file extension for OO XML file")) {
handleWrongOLE2XMLExtension(inputFile, e);
return;
}
throw e;
} catch (IllegalArgumentException e) {
// ignore errors for documents with incorrect extension
String message = e.getMessage();
if(message != null && (message.equals("The document is really a RTF file") ||
message.equals("The document is really a PDF file") ||
message.equals("The document is really a HTML file"))) {
Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file", true);
}
if(message != null && message.equals("The document is really a OOXML file")) {
handleWrongOLE2XMLExtension(inputFile, e);
return;
}
throw e;
}
try {
handler.handleExtracting(inputFile);
} catch (EncryptedDocumentException e) {
// Do not try to read encrypted files
Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true);
}
}
void handleWrongOLE2XMLExtension(File inputFile, Exception e) throws Exception {
// we sometimes have wrong extensions, so for some exceptions we try to handle it
// with the correct FileHandler instead
String message = e.getMessage();
// ignore some file-types that we do not want to handle here
Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file",
message != null && (message.equals("The document is really a RTF file") ||
message.equals("The document is really a PDF file") ||
message.equals("The document is really a HTML file")));
if(message != null && (message.equals("The document is really a XLS file"))) {
handler = TestAllFiles.HANDLERS.get(".xls");
handleFile(inputFile);
} else if(message != null && (message.equals("The document is really a PPT file"))) {
handler = TestAllFiles.HANDLERS.get(".ppt");
handleFile(inputFile);
} else if(message != null && (message.equals("The document is really a DOC file"))) {
handler = TestAllFiles.HANDLERS.get(".doc");
handleFile(inputFile);
} else if(message != null && (message.equals("The document is really a VSD file"))) {
handler = TestAllFiles.HANDLERS.get(".vsd");
handleFile(inputFile);
// use XWPF instead of HWPF and XSSF instead of HSSF as the file seems to have the wrong extension
} else if (handler instanceof HWPFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".docx");
handleFile(inputFile);
} else if (handler instanceof HSSFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".xlsx");
handleFile(inputFile);
} else if (handler instanceof HSLFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".pptx");
handleFile(inputFile);
// and the other way around, use HWPF instead of XWPF and so forth
} else if(handler instanceof XWPFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".doc");
handleFile(inputFile);
} else if(handler instanceof XSSFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".xls");
handleFile(inputFile);
} else if(handler instanceof XSLFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".ppt");
handleFile(inputFile);
} else {
// nothing matched => throw the exception to the outside
throw e;
}
}
private void handleFile(File inputFile) throws Exception {
try (InputStream newStream = new BufferedInputStream(new FileInputStream(inputFile), 64*1024)) {
handler.handleFile(newStream, inputFile.getAbsolutePath());
}
}
}

View File

@ -213,7 +213,7 @@ public final class XMLHelper {
return XMLEventFactory.newInstance();
}
@SuppressWarnings("squid:S4435")
@SuppressWarnings({"squid:S4435","java:S2755"})
public static TransformerFactory getTransformerFactory() {
TransformerFactory factory = TransformerFactory.newInstance();
trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true);
@ -232,6 +232,7 @@ public final class XMLHelper {
return serializer;
}
@SuppressWarnings("java:S2755")
public static SchemaFactory getSchemaFactory() {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true);

View File

@ -16,74 +16,95 @@
==================================================================== */
package org.apache.poi.ss.format;
import static java.awt.Color.ORANGE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.awt.Color;
import java.io.IOException;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.swing.JLabel;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/** Test the individual CellFormatPart types. */
public class TestCellFormatPart extends CellFormatTestBase {
/**
* Class for spreadsheet-based tests, such as are used for cell formatting.
* This reads tests from the spreadsheet, as well as reading
* flags that can be used to paramterize these tests.
* <p>
* Each test has four parts: The expected result (column A), the format string
* (column B), the value to format (column C), and a comma-separated list of
* categores that this test falls in. Normally all tests are run, but if the
* flag "Categories" is not empty, only tests that have at least one category
* listed in "Categories" are run.
*/
public class TestCellFormatPart {
private static final Pattern NUMBER_EXTRACT_FMT = Pattern.compile(
"([-+]?[0-9]+)(\\.[0-9]+)?.*(?:(e).*?([+-]?[0-9]+))",
Pattern.CASE_INSENSITIVE);
private static final Color TEST_COLOR = ORANGE.darker();
private static Locale userLocale;
@BeforeClass
public static void setLocale() {
userLocale = LocaleUtil.getUserLocale();
LocaleUtil.setUserLocale(Locale.UK);
}
@AfterClass
public static void unsetLocale() {
LocaleUtil.setUserLocale(userLocale);
}
private static final Pattern NUMBER_EXTRACT_FMT = Pattern.compile(
"([-+]?[0-9]+)(\\.[0-9]+)?.*(?:(e).*?([+-]?[0-9]+))",
Pattern.CASE_INSENSITIVE);
public TestCellFormatPart() {
super(XSSFITestDataProvider.instance);
private final ITestDataProvider _testDataProvider = XSSFITestDataProvider.instance;
private interface CellValue {
Object getValue(Cell cell);
default void equivalent(String expected, String actual, CellFormatPart format) {
assertEquals("format \"" + format + "\"", '"' + expected + '"',
'"' + actual + '"');
}
}
@Test
public void testGeneralFormat() throws IOException {
runFormatTests("GeneralFormatTests.xlsx", new CellValue() {
@Override
public Object getValue(Cell cell) {
switch (CellFormat.ultimateType(cell)) {
case BOOLEAN:
return cell.getBooleanCellValue();
case NUMERIC:
return cell.getNumericCellValue();
default:
return cell.getStringCellValue();
}
runFormatTests("GeneralFormatTests.xlsx", cell -> {
assertNotNull(cell);
switch (CellFormat.ultimateType(cell)) {
case BOOLEAN:
return cell.getBooleanCellValue();
case NUMERIC:
return cell.getNumericCellValue();
default:
return cell.getStringCellValue();
}
});
}
@Test
public void testNumberFormat() throws IOException {
runFormatTests("NumberFormatTests.xlsx", new CellValue() {
@Override
public Object getValue(Cell cell) {
return cell.getNumericCellValue();
}
});
runFormatTests("NumberFormatTests.xlsx", Cell::getNumericCellValue);
}
@Test
@ -95,7 +116,7 @@ public class TestCellFormatPart extends CellFormatTestBase {
}
@Override
void equivalent(String expected, String actual,
public void equivalent(String expected, String actual,
CellFormatPart format) {
double expectedVal = extractNumber(expected);
double actualVal = extractNumber(actual);
@ -112,12 +133,7 @@ public class TestCellFormatPart extends CellFormatTestBase {
TimeZone tz = LocaleUtil.getUserTimeZone();
LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET"));
try {
runFormatTests("DateFormatTests.xlsx", new CellValue() {
@Override
public Object getValue(Cell cell) {
return cell.getDateCellValue();
}
});
runFormatTests("DateFormatTests.xlsx", Cell::getDateCellValue);
} finally {
LocaleUtil.setUserTimeZone(tz);
}
@ -125,55 +141,34 @@ public class TestCellFormatPart extends CellFormatTestBase {
@Test
public void testElapsedFormat() throws IOException {
runFormatTests("ElapsedFormatTests.xlsx", new CellValue() {
@Override
public Object getValue(Cell cell) {
return cell.getNumericCellValue();
}
});
runFormatTests("ElapsedFormatTests.xlsx", Cell::getNumericCellValue);
}
@Test
public void testTextFormat() throws IOException {
runFormatTests("TextFormatTests.xlsx", new CellValue() {
@Override
public Object getValue(Cell cell) {
if (CellFormat.ultimateType(cell) == CellType.BOOLEAN) {
return cell.getBooleanCellValue();
}
return cell.getStringCellValue();
}
});
runFormatTests("TextFormatTests.xlsx", cell ->
(CellFormat.ultimateType(cell) == CellType.BOOLEAN) ? cell.getBooleanCellValue() : cell.getStringCellValue()
);
}
@Test
public void testConditions() throws IOException {
runFormatTests("FormatConditionTests.xlsx", new CellValue() {
@Override
Object getValue(Cell cell) {
return cell.getNumericCellValue();
}
});
runFormatTests("FormatConditionTests.xlsx", Cell::getNumericCellValue);
}
@Test
public void testNamedColors() {
assertTrue(CellFormatPart.NAMED_COLORS.size() >= HSSFColor.HSSFColorPredefined.values().length);
assertNotNull(CellFormatPart.NAMED_COLORS.get("GREEN"));
assertNotNull(CellFormatPart.NAMED_COLORS.get("Green"));
assertNotNull(CellFormatPart.NAMED_COLORS.get("RED"));
assertNotNull(CellFormatPart.NAMED_COLORS.get("Red"));
assertNotNull(CellFormatPart.NAMED_COLORS.get("BLUE"));
assertNotNull(CellFormatPart.NAMED_COLORS.get("Blue"));
assertNotNull(CellFormatPart.NAMED_COLORS.get("YELLOW"));
assertNotNull(CellFormatPart.NAMED_COLORS.get("Yellow"));
Stream.of("GREEN","Green","RED","Red","BLUE","Blue","YELLOW","Yellow")
.map(CellFormatPart.NAMED_COLORS::get)
.forEach(Assert::assertNotNull);
}
private double extractNumber(String str) {
Matcher m = NUMBER_EXTRACT_FMT.matcher(str);
if (!m.find())
throw new IllegalArgumentException(
"Cannot find number in \"" + str + "\"");
if (!m.find()) {
throw new IllegalArgumentException("Cannot find number in \"" + str + "\"");
}
StringBuilder sb = new StringBuilder();
// The groups in the pattern are the parts of the number
@ -182,6 +177,45 @@ public class TestCellFormatPart extends CellFormatTestBase {
if (part != null)
sb.append(part);
}
return Double.valueOf(sb.toString());
return Double.parseDouble(sb.toString());
}
protected void runFormatTests(String workbookName, CellValue valueGetter) throws IOException {
try (Workbook workbook = _testDataProvider.openSampleWorkbook(workbookName)) {
workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Sheet sheet = workbook.getSheet("Tests");
boolean isHeader = true;
for (Row row : sheet) {
// Skip the header row
if (isHeader || row == null) {
isHeader = false;
continue;
}
String expectedText = row.getCell(0).getStringCellValue();
String format = row.getCell(1).getStringCellValue();
Cell value = row.getCell(2);
if (expectedText.isEmpty() && format.isEmpty()) {
continue;
}
Object objVal = valueGetter.getValue(value);
JLabel label = new JLabel();
label.setForeground(TEST_COLOR);
label.setText("xyzzy");
Color origColor = label.getForeground();
CellFormatPart cellFormatPart = new CellFormatPart(format);
// If this doesn't apply, no color change is expected
Color expectedColor = cellFormatPart.apply(label, objVal).applies ? TEST_COLOR : origColor;
String actualText = label.getText();
Color actualColor = label.getForeground();
valueGetter.equivalent(expectedText, actualText, cellFormatPart);
assertEquals("no color", expectedColor, actualColor);
}
}
}
}

View File

@ -1,309 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.ss.format;
import static java.awt.Color.BLACK;
import static java.awt.Color.BLUE;
import static java.awt.Color.CYAN;
import static java.awt.Color.GREEN;
import static java.awt.Color.MAGENTA;
import static java.awt.Color.ORANGE;
import static java.awt.Color.RED;
import static java.awt.Color.WHITE;
import static java.awt.Color.YELLOW;
import static org.junit.Assert.assertEquals;
import java.awt.Color;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.swing.JLabel;
import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
/**
* This class is a base class for spreadsheet-based tests, such as are used for
* cell formatting. This reads tests from the spreadsheet, as well as reading
* flags that can be used to paramterize these tests.
* <p>
* Each test has four parts: The expected result (column A), the format string
* (column B), the value to format (column C), and a comma-separated list of
* categores that this test falls in. Normally all tests are run, but if the
* flag "Categories" is not empty, only tests that have at least one category
* listed in "Categories" are run.
*/
public class CellFormatTestBase {
private static final POILogger logger = POILogFactory.getLogger(CellFormatTestBase.class);
private final ITestDataProvider _testDataProvider;
protected Workbook workbook;
private String testFile;
private Map<String, String> testFlags;
private boolean tryAllColors;
private JLabel label;
private static final String[] COLOR_NAMES =
{"Black", "Red", "Green", "Blue", "Yellow", "Cyan", "Magenta",
"White"};
private static final Color[] COLORS =
{BLACK, RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA, WHITE};
public static final Color TEST_COLOR = ORANGE.darker();
protected CellFormatTestBase(ITestDataProvider testDataProvider) {
_testDataProvider = testDataProvider;
}
abstract static class CellValue {
abstract Object getValue(Cell cell);
Color getColor(Cell cell) {
return TEST_COLOR;
}
void equivalent(String expected, String actual, CellFormatPart format) {
assertEquals("format \"" + format + "\"", '"' + expected + '"',
'"' + actual + '"');
}
}
protected void runFormatTests(String workbookName, CellValue valueGetter) throws IOException {
openWorkbook(workbookName);
readFlags(workbook);
Set<String> runCategories = new TreeSet<>(
String.CASE_INSENSITIVE_ORDER);
String runCategoryList = flagString("Categories", "");
if (runCategoryList != null) {
runCategories.addAll(Arrays.asList(runCategoryList.split(
"\\s*,\\s*")));
runCategories.remove(""); // this can be found and means nothing
}
Sheet sheet = workbook.getSheet("Tests");
Iterator<Row> rowIter = sheet.rowIterator();
// Skip the header row
rowIter.next();
while (rowIter.hasNext()) {
Row row = rowIter.next();
if (row == null) continue;
String expectedText = row.getCell(0).getStringCellValue();
String format = row.getCell(1).getStringCellValue();
Cell value = row.getCell(2);
String testCategoryList = row.getCell(3).getStringCellValue();
boolean byCategory = runByCategory(runCategories, testCategoryList);
if ((expectedText.length() > 0 || format.length() > 0) && byCategory) {
tryFormat(row.getRowNum(), expectedText, format, valueGetter, value);
}
}
workbook.close();
}
/**
* Open a given workbook.
*
* @param workbookName The workbook name. This is presumed to live in the
* "spreadsheets" directory under the directory named in
* the Java property "POI.testdata.path".
*/
protected void openWorkbook(String workbookName) {
workbook = _testDataProvider.openSampleWorkbook(workbookName);
workbook.setMissingCellPolicy(MissingCellPolicy.CREATE_NULL_AS_BLANK);
testFile = workbookName;
}
/**
* Read the flags from the workbook. Flags are on the sheet named "Flags",
* and consist of names in column A and values in column B. These are put
* into a map that can be queried later.
*
* @param wb The workbook to look in.
*/
private void readFlags(Workbook wb) {
Sheet flagSheet = wb.getSheet("Flags");
testFlags = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
if (flagSheet != null) {
int end = flagSheet.getLastRowNum();
// Skip the header row, therefore "+ 1"
for (int r = flagSheet.getFirstRowNum() + 1; r <= end; r++) {
Row row = flagSheet.getRow(r);
if (row == null)
continue;
String flagName = row.getCell(0).getStringCellValue();
String flagValue = row.getCell(1).getStringCellValue();
if (flagName.length() > 0) {
testFlags.put(flagName, flagValue);
}
}
}
tryAllColors = flagBoolean("AllColors", true);
}
/**
* Returns <tt>true</tt> if any of the categories for this run are contained
* in the test's listed categories.
*
* @param categories The categories of tests to be run. If this is
* empty, then all tests will be run.
* @param testCategories The categories that this test is in. This is a
* comma-separated list. If <em>any</em> tests in
* this list are in <tt>categories</tt>, the test will
* be run.
*
* @return <tt>true</tt> if the test should be run.
*/
private boolean runByCategory(Set<String> categories,
String testCategories) {
if (categories.isEmpty())
return true;
// If there are specified categories, find out if this has one of them
for (String category : testCategories.split("\\s*,\\s*")) {
if (categories.contains(category)) {
return true;
}
}
return false;
}
private void tryFormat(int row, String expectedText, String desc,
CellValue getter, Cell cell) {
Object value = getter.getValue(cell);
Color testColor = getter.getColor(cell);
if (testColor == null)
testColor = TEST_COLOR;
if (label == null)
label = new JLabel();
label.setForeground(testColor);
label.setText("xyzzy");
logger.log(POILogger.INFO, String.format(LocaleUtil.getUserLocale(),
"Row %d: \"%s\" -> \"%s\": expected \"%s\"",
row + 1, String.valueOf(value), desc, expectedText));
String actualText = tryColor(desc, null, getter, value, expectedText,
testColor);
logger.log(POILogger.INFO, String.format(LocaleUtil.getUserLocale(),
", actual \"%s\")%n", actualText));
if (tryAllColors && testColor != TEST_COLOR) {
for (int i = 0; i < COLOR_NAMES.length; i++) {
tryColor(desc, COLOR_NAMES[i], getter, value, expectedText, COLORS[i]);
}
}
}
private String tryColor(String desc, String cname, CellValue getter,
Object value, String expectedText, Color expectedColor) {
if (cname != null)
desc = "[" + cname + "]" + desc;
Color origColor = label.getForeground();
CellFormatPart format = new CellFormatPart(desc);
if (!format.apply(label, value).applies) {
// If this doesn't apply, no color change is expected
expectedColor = origColor;
}
String actualText = label.getText();
Color actualColor = label.getForeground();
getter.equivalent(expectedText, actualText, format);
assertEquals(cname == null ? "no color" : "color " + cname,
expectedColor, actualColor);
return actualText;
}
/**
* Returns the value for the given flag. The flag has the value of
* <tt>true</tt> if the text value is <tt>"true"</tt>, <tt>"yes"</tt>, or
* <tt>"on"</tt> (ignoring case).
*
* @param flagName The name of the flag to fetch.
* @param expected The value for the flag that is expected when the tests
* are run for a full test. If the current value is not the
* expected one, you will get a warning in the test output.
* This is so that you do not accidentally leave a flag set
* to a value that prevents running some tests, thereby
* letting you accidentally release code that is not fully
* tested.
*
* @return The value for the flag.
*/
protected boolean flagBoolean(String flagName, boolean expected) {
String value = testFlags.get(flagName);
boolean isSet;
if (value == null)
isSet = false;
else {
isSet = value.equalsIgnoreCase("true") || value.equalsIgnoreCase(
"yes") || value.equalsIgnoreCase("on");
}
warnIfUnexpected(flagName, expected, isSet);
return isSet;
}
/**
* Returns the value for the given flag.
*
* @param flagName The name of the flag to fetch.
* @param expected The value for the flag that is expected when the tests
* are run for a full test. If the current value is not the
* expected one, you will get a warning in the test output.
* This is so that you do not accidentally leave a flag set
* to a value that prevents running some tests, thereby
* letting you accidentally release code that is not fully
* tested.
*
* @return The value for the flag.
*/
protected String flagString(String flagName, String expected) {
String value = testFlags.get(flagName);
if (value == null)
value = "";
warnIfUnexpected(flagName, expected, value);
return value;
}
private void warnIfUnexpected(String flagName, Object expected,
Object actual) {
if (!actual.equals(expected)) {
System.err.println(
"WARNING: " + testFile + ": " + "Flag " + flagName +
" = \"" + actual + "\" [not \"" + expected + "\"]");
}
}
}