extended forbidden-apis-check to ooxml-tests

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1712693 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2015-11-05 00:15:51 +00:00
parent ecab3629d8
commit 9b4919cd51
15 changed files with 306 additions and 191 deletions

View File

@ -1776,9 +1776,9 @@ under the License.
<fileset dir="${scratchpad.output.dir}"/>
<fileset dir="${ooxml.output.dir}"/>
<fileset dir="${main.output.test.dir}"/>
<fileset dir="${ooxml.output.test.dir}"/>
<!--
<fileset dir="${scratchpad.output.test.dir}"/>
<fileset dir="${ooxml.output.test.dir}"/>
-->
</forbiddenapis>
</target>

View File

@ -185,13 +185,13 @@ public final class TestPOIXMLProperties {
Date dateCreated = LocaleUtil.getLocaleCalendar(2010, 6, 15, 10, 0, 0).getTime();
cp.setCreated(new Nullable<Date>(dateCreated));
assertEquals(dateCreated.toString(), cp.getCreated().toString());
assertEquals(dateCreated, cp.getCreated());
XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc);
doc.close();
cp = doc.getProperties().getCoreProperties();
Date dt3 = cp.getCreated();
assertEquals(dateCreated.toString(), dt3.toString());
assertEquals(dateCreated, dt3);
doc2.close();
}

View File

@ -35,6 +35,7 @@ import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
@ -44,6 +45,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIXMLException;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
@ -65,6 +67,7 @@ import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public final class TestPackage {
private static final POILogger logger = POILogFactory.getLogger(TestPackage.class);
@ -73,11 +76,12 @@ public final class TestPackage {
* Test that just opening and closing the file doesn't alter the document.
*/
@Test
public void openSave() throws Exception {
public void openSave() throws IOException, InvalidFormatException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
try {
p.save(targetFile.getAbsoluteFile());
@ -94,15 +98,21 @@ public final class TestPackage {
/**
* Test that when we create a new Package, we give it
* the correct default content types
* @throws IllegalAccessException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws SecurityException
*/
@Test
public void createGetsContentTypes() throws Exception {
public void createGetsContentTypes()
throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
// Zap the target file, in case of an earlier run
if(targetFile.exists()) targetFile.delete();
OPCPackage pkg = OPCPackage.create(targetFile);
@SuppressWarnings("resource")
OPCPackage pkg = OPCPackage.create(targetFile);
// Check it has content types for rels and xml
ContentTypeManager ctm = getContentTypeManager(pkg);
@ -123,13 +133,15 @@ public final class TestPackage {
PackagingURIHelper.createPartName("/foo.txt")
)
);
pkg.revert();
}
/**
* Test package creation.
*/
@Test
public void createPackageAddPart() throws Exception {
public void createPackageAddPart() throws IOException, InvalidFormatException {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
File expectedFile = OpenXML4JTestDataSamples.getSampleFile("TestCreatePackageOUTPUT.docx");
@ -174,9 +186,10 @@ public final class TestPackage {
* Tests that we can create a new package, add a core
* document and another part, save and re-load and
* have everything setup as expected
* @throws SAXException
*/
@Test
public void createPackageWithCoreDocument() throws Exception {
public void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.create(baos);
@ -188,7 +201,7 @@ public final class TestPackage {
PackagePart corePart = pkg.createPart(corePartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
// Put in some dummy content
OutputStream coreOut = corePart.getOutputStream();
coreOut.write("<dummy-xml />".getBytes());
coreOut.write("<dummy-xml />".getBytes("UTF-8"));
coreOut.close();
// And another bit
@ -200,7 +213,7 @@ public final class TestPackage {
// Dummy content again
coreOut = corePart.getOutputStream();
coreOut.write("<dummy-xml2 />".getBytes());
coreOut.write("<dummy-xml2 />".getBytes("UTF-8"));
coreOut.close();
//add a relationship with internal target: "#Sheet1!A1"
@ -250,7 +263,7 @@ public final class TestPackage {
}
}
private void assertMSCompatibility(OPCPackage pkg) throws Exception {
private void assertMSCompatibility(OPCPackage pkg) throws IOException, InvalidFormatException, SAXException {
PackagePartName relName = PackagingURIHelper.createPartName(PackageRelationship.getContainerPartRelationship());
PackagePart relPart = pkg.getPart(relName);
@ -271,7 +284,7 @@ public final class TestPackage {
* Test package opening.
*/
@Test
public void openPackage() throws Exception {
public void openPackage() throws IOException, InvalidFormatException {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx");
File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx");
@ -331,11 +344,12 @@ public final class TestPackage {
* to a file
*/
@Test
public void saveToOutputStream() throws Exception {
public void saveToOutputStream() throws IOException, InvalidFormatException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
try {
FileOutputStream fout = new FileOutputStream(targetFile);
try {
@ -360,12 +374,13 @@ public final class TestPackage {
* reading from a file
*/
@Test
public void openFromInputStream() throws Exception {
public void openFromInputStream() throws IOException, InvalidFormatException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
FileInputStream finp = new FileInputStream(originalFile);
OPCPackage p = OPCPackage.open(finp);
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(finp);
assertNotNull(p);
assertNotNull(p.getRelationships());
@ -374,19 +389,24 @@ public final class TestPackage {
// Check it has the usual bits
assertTrue(p.hasRelationships());
assertTrue(p.containPart(PackagingURIHelper.createPartName("/_rels/.rels")));
p.revert();
finp.close();
}
/**
* TODO: fix and enable
* @throws URISyntaxException
*/
@Test
@Ignore
public void removePartRecursive() throws Exception {
public void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx");
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
p.removePartRecursive(PackagingURIHelper.createPartName(new URI(
"/word/document.xml")));
p.save(tempFile.getAbsoluteFile());
@ -395,6 +415,8 @@ public final class TestPackage {
assertTrue(targetFile.exists());
ZipFileAssert.assertEquals(targetFile, tempFile);
assertTrue(targetFile.delete());
p.revert();
}
@Test
@ -437,7 +459,8 @@ public final class TestPackage {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
// Remove the core part
p.deletePart(PackagingURIHelper.createPartName("/word/document.xml"));
@ -476,7 +499,8 @@ public final class TestPackage {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
// Remove the core part
p.deletePartRecursive(PackagingURIHelper.createPartName("/word/document.xml"));
@ -499,7 +523,7 @@ public final class TestPackage {
* write changes to it.
*/
@Test
public void openFileThenOverwrite() throws Exception {
public void openFileThenOverwrite() throws IOException, InvalidFormatException {
File tempFile = TempFile.createTempFile("poiTesting","tmp");
File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
FileHelper.copyFile(origFile, tempFile);
@ -537,7 +561,7 @@ public final class TestPackage {
* to another file, then delete both
*/
@Test
public void openFileThenSaveDelete() throws Exception {
public void openFileThenSaveDelete() throws IOException, InvalidFormatException {
File tempFile = TempFile.createTempFile("poiTesting","tmp");
File tempFile2 = TempFile.createTempFile("poiTesting","tmp");
File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
@ -555,16 +579,18 @@ public final class TestPackage {
assertTrue(tempFile2.delete());
}
private static ContentTypeManager getContentTypeManager(OPCPackage pkg) throws Exception {
private static ContentTypeManager getContentTypeManager(OPCPackage pkg)
throws IOException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field f = OPCPackage.class.getDeclaredField("contentTypeManager");
f.setAccessible(true);
return (ContentTypeManager)f.get(pkg);
}
@Test
public void getPartsByName() throws Exception {
public void getPartsByName() throws IOException, InvalidFormatException {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
@SuppressWarnings("resource")
OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
try {
List<PackagePart> rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml"));
@ -587,7 +613,7 @@ public final class TestPackage {
}
@Test
public void getPartSize() throws Exception {
public void getPartSize() throws IOException, InvalidFormatException {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ);
try {
@ -620,8 +646,10 @@ public final class TestPackage {
}
@Test
public void replaceContentType() throws Exception {
public void replaceContentType()
throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx");
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(is);
ContentTypeManager mgr = getContentTypeManager(p);
@ -637,10 +665,13 @@ public final class TestPackage {
assertFalse(mgr.isContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"));
assertTrue(mgr.isContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml"));
p.revert();
is.close();
}
@Test(expected=IOException.class)
public void zipBombCreateAndHandle() throws Exception {
public void zipBombCreateAndHandle()
throws IOException, EncryptedDocumentException, InvalidFormatException {
// #50090 / #56865
ZipFile zipFile = ZipHelper.openZipFile(OpenXML4JTestDataSamples.getSampleFile("sample.xlsx"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
@ -668,12 +699,13 @@ public final class TestPackage {
append.write(spam);
size += spam.length;
}
append.write("</Types>".getBytes());
append.write("</Types>".getBytes("UTF-8"));
size += 8;
e.setSize(size);
} else {
IOUtils.copy(is, append);
}
is.close();
}
append.closeEntry();
}
@ -690,7 +722,8 @@ public final class TestPackage {
}
@Test
public void zipBombCheckSizes() throws Exception {
public void zipBombCheckSizes()
throws IOException, EncryptedDocumentException, InvalidFormatException {
File file = OpenXML4JTestDataSamples.getSampleFile("sample.xlsx");
try {
@ -709,14 +742,12 @@ public final class TestPackage {
// use values close to, but within the limits
ZipSecureFile.setMinInflateRatio(min_ratio-0.002);
ZipSecureFile.setMaxEntrySize(max_size+1);
Workbook wb = WorkbookFactory.create(file, null, true);
wb.close();
WorkbookFactory.create(file, null, true).close();
// check ratio out of bounds
ZipSecureFile.setMinInflateRatio(min_ratio+0.002);
try {
wb = WorkbookFactory.create(file, null, true);
wb.close();
WorkbookFactory.create(file, null, true).close();
// this is a bit strange, as there will be different exceptions thrown
// depending if this executed via "ant test" or within eclipse
// maybe a difference in JDK ...
@ -730,8 +761,7 @@ public final class TestPackage {
ZipSecureFile.setMinInflateRatio(min_ratio-0.002);
ZipSecureFile.setMaxEntrySize(max_size-1);
try {
wb = WorkbookFactory.create(file, null, true);
wb.close();
WorkbookFactory.create(file, null, true).close();
} catch (InvalidFormatException e) {
checkForZipBombException(e);
} catch (POIXMLException e) {

View File

@ -338,7 +338,7 @@ public class TestSignatureInfo {
@Override
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
revocationData.addCRL(crl);
return "time-stamp-token".getBytes();
return "time-stamp-token".getBytes(LocaleUtil.CHARSET_1252);
}
@Override
public void setSignatureConfig(SignatureConfig config) {

View File

@ -17,26 +17,37 @@
package org.apache.poi.xssf.extractor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import junit.framework.TestCase;
import javax.xml.xpath.XPathExpressionException;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFMap;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.xml.sax.SAXException;
/**
*
* @author Roberto Manicardi
*
*/
public class TestXSSFImportFromXML extends TestCase {
public class TestXSSFImportFromXML {
public void testImportFromXML() throws Exception{
@Test
public void testImportFromXML() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx");
try {
@ -82,10 +93,8 @@ public class TestXSSFImportFromXML extends TestCase {
}
}
public void testMultiTable() throws Exception{
@Test
public void testMultiTable() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx");
try {
String cellC6 = "c6";
@ -128,7 +137,8 @@ public class TestXSSFImportFromXML extends TestCase {
}
public void testSingleAttributeCellWithNamespace() throws Exception{
@Test
public void testSingleAttributeCellWithNamespace() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx");
try {
int id = 1;
@ -148,16 +158,17 @@ public class TestXSSFImportFromXML extends TestCase {
//Check for Schema element
XSSFSheet sheet=wb.getSheetAt(0);
assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue());
assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0);
assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue());
assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue());
assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue());
assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0);
} finally {
wb.close();
}
}
public void testOptionalFields_Bugzilla_55864() throws Exception {
@Test
public void testOptionalFields_Bugzilla_55864() throws IOException, XPathExpressionException, SAXException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx");
try {
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
@ -197,7 +208,8 @@ public class TestXSSFImportFromXML extends TestCase {
}
}
public void testOptionalFields_Bugzilla_57890() throws Exception {
@Test
public void testOptionalFields_Bugzilla_57890() throws IOException, ParseException, XPathExpressionException, SAXException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57890.xlsx");
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<TestInfoRoot>"
@ -216,16 +228,18 @@ public class TestXSSFImportFromXML extends TestCase {
XSSFRow rowData = sheet.getRow(1);
assertEquals("Date", rowHeadings.getCell(0).getStringCellValue());
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1991-3-14");
Date date = new SimpleDateFormat("yyyy-MM-dd", DateFormatSymbols.getInstance(Locale.ROOT)).parse("1991-3-14");
assertEquals(date, rowData.getCell(0).getDateCellValue());
assertEquals("Amount Int", rowHeadings.getCell(1).getStringCellValue());
assertEquals(new Double(Integer.MIN_VALUE), rowData.getCell(1).getNumericCellValue());
assertEquals(new Double(Integer.MIN_VALUE), rowData.getCell(1).getNumericCellValue(), 0);
assertEquals("Amount Double", rowHeadings.getCell(2).getStringCellValue());
assertEquals(1.0000123, rowData.getCell(2).getNumericCellValue());
assertEquals(1.0000123, rowData.getCell(2).getNumericCellValue(), 0);
assertEquals("Amount UnsignedInt", rowHeadings.getCell(3).getStringCellValue());
assertEquals(new Double(12345), rowData.getCell(3).getNumericCellValue());
assertEquals(new Double(12345), rowData.getCell(3).getNumericCellValue(), 0);
wb.close();
}
}

View File

@ -23,10 +23,7 @@ import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.POIXMLException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples;
@ -36,6 +33,8 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import junit.framework.TestCase;
/**
* Test {@link SharedStringsTable}, the cache of strings in a workbook
*
@ -114,12 +113,13 @@ public final class TestSharedStringsTable extends TestCase {
assertEquals("Second string", new XSSFRichTextString(sst.getEntryAt(2)).toString());
}
public void testReadWrite() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
SharedStringsTable sst1 = wb.getSharedStringSource();
public void testReadWrite() throws IOException {
XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
SharedStringsTable sst1 = wb1.getSharedStringSource();
//serialize, read back and compare with the original
SharedStringsTable sst2 = XSSFTestDataSamples.writeOutAndReadBack(wb).getSharedStringSource();
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
SharedStringsTable sst2 = wb2.getSharedStringSource();
assertEquals(sst1.getCount(), sst2.getCount());
assertEquals(sst1.getUniqueCount(), sst2.getUniqueCount());
@ -133,7 +133,11 @@ public final class TestSharedStringsTable extends TestCase {
assertEquals(st1.toString(), st2.toString());
}
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb));
XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
assertNotNull(wb3);
wb3.close();
wb2.close();
wb1.close();
}
/**
@ -144,34 +148,34 @@ public final class TestSharedStringsTable extends TestCase {
* @author Philippe Laflamme
*/
public void testBug48936() throws IOException {
Workbook w = new XSSFWorkbook();
Sheet s = w.createSheet();
Workbook w1 = new XSSFWorkbook();
Sheet s = w1.createSheet();
int i = 0;
List<String> lst = readStrings("48936-strings.txt");
for (String str : lst) {
s.createRow(i++).createCell(0).setCellValue(str);
}
try {
w = XSSFTestDataSamples.writeOutAndReadBack(w);
} catch (POIXMLException e){
fail("Detected Bug #48936");
}
s = w.getSheetAt(0);
Workbook w2 = XSSFTestDataSamples.writeOutAndReadBack(w1);
w1.close();
s = w2.getSheetAt(0);
i = 0;
for (String str : lst) {
String val = s.getRow(i++).getCell(0).getStringCellValue();
assertEquals(str, val);
}
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(w));
Workbook w3 = XSSFTestDataSamples.writeOutAndReadBack(w2);
w2.close();
assertNotNull(w3);
w3.close();
}
private List<String> readStrings(String filename) throws IOException {
List<String> strs = new ArrayList<String>();
POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();
BufferedReader br = new BufferedReader(
new InputStreamReader(samples.openResourceAsStream(filename)));
new InputStreamReader(samples.openResourceAsStream(filename), "UTF-8"));
String s;
while ((s = br.readLine()) != null) {
if (s.trim().length() > 0) {

View File

@ -367,7 +367,7 @@ public final class TestUnfixedBugs {
}
// verify that the resulting XML has the rows in correct order as required by Excel
String xml = new String(stream.toByteArray());
String xml = new String(stream.toByteArray(), "UTF-8");
int posR12 = xml.indexOf("<row r=\"12\"");
int posR13 = xml.indexOf("<row r=\"13\"");

View File

@ -18,6 +18,9 @@
package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.io.IOException;
@ -31,8 +34,10 @@ import org.apache.poi.ss.usermodel.FontUnderline;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.SheetUtil;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBooleanProperty;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont;
@ -52,15 +57,18 @@ public final class TestXSSFFont extends BaseTestFont{
super(XSSFITestDataProvider.instance);
}
public void testDefaultFont() {
@Test
public void testDefaultFont() throws IOException {
baseTestDefaultFont("Calibri", (short) 220, IndexedColors.BLACK.getIndex());
}
@Test
public void testConstructor() {
XSSFFont xssfFont=new XSSFFont();
assertNotNull(xssfFont.getCTFont());
}
@Test
public void testBoldweight() {
CTFont ctFont=CTFont.Factory.newInstance();
CTBooleanProperty bool=ctFont.addNewB();
@ -75,7 +83,8 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(true, ctFont.getBArray(0).getVal());
}
public void testCharSet() {
@Test
public void testCharSet() throws IOException {
CTFont ctFont=CTFont.Factory.newInstance();
CTIntProperty prop=ctFont.addNewCharset();
prop.setVal(FontCharset.ANSI.getValue());
@ -89,37 +98,40 @@ public final class TestXSSFFont extends BaseTestFont{
// Try with a few less usual ones:
// Set with the Charset itself
xssfFont.setCharSet(FontCharset.RUSSIAN);
assertEquals(FontCharset.RUSSIAN.getValue(), xssfFont.getCharSet());
// And set with the Charset index
xssfFont.setCharSet(FontCharset.ARABIC.getValue());
assertEquals(FontCharset.ARABIC.getValue(), xssfFont.getCharSet());
xssfFont.setCharSet((byte)(FontCharset.ARABIC.getValue()));
assertEquals(FontCharset.ARABIC.getValue(), xssfFont.getCharSet());
xssfFont.setCharSet(FontCharset.RUSSIAN);
assertEquals(FontCharset.RUSSIAN.getValue(), xssfFont.getCharSet());
// And set with the Charset index
xssfFont.setCharSet(FontCharset.ARABIC.getValue());
assertEquals(FontCharset.ARABIC.getValue(), xssfFont.getCharSet());
xssfFont.setCharSet((byte)(FontCharset.ARABIC.getValue()));
assertEquals(FontCharset.ARABIC.getValue(), xssfFont.getCharSet());
// This one isn't allowed
assertEquals(null, FontCharset.valueOf(9999));
try {
xssfFont.setCharSet(9999);
fail("Shouldn't be able to set an invalid charset");
} catch(POIXMLException e) {}
// This one isn't allowed
assertEquals(null, FontCharset.valueOf(9999));
try {
xssfFont.setCharSet(9999);
fail("Shouldn't be able to set an invalid charset");
} catch(POIXMLException e) {}
// Now try with a few sample files
// Normal charset
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
assertEquals(0,
workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet()
);
XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
assertEquals(0,
wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet()
);
wb1.close();
// GB2312 charact set
workbook = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx");
assertEquals(134,
workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet()
);
XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx");
assertEquals(134,
wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet()
);
wb2.close();
}
@Test
public void testFontName() {
CTFont ctFont=CTFont.Factory.newInstance();
CTFontName fname=ctFont.addNewName();
@ -133,6 +145,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals("Courier",ctFont.getNameArray(0).getVal());
}
@Test
public void testItalic() {
CTFont ctFont=CTFont.Factory.newInstance();
CTBooleanProperty bool=ctFont.addNewI();
@ -148,6 +161,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(true,ctFont.getIArray(0).getVal());
}
@Test
public void testStrikeout() {
CTFont ctFont=CTFont.Factory.newInstance();
CTBooleanProperty bool=ctFont.addNewStrike();
@ -163,6 +177,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(true,ctFont.getStrikeArray(0).getVal());
}
@Test
public void testFontHeight() {
CTFont ctFont=CTFont.Factory.newInstance();
CTFontSize size=ctFont.addNewSz();
@ -176,6 +191,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0);
}
@Test
public void testFontHeightInPoint() {
CTFont ctFont=CTFont.Factory.newInstance();
CTFontSize size=ctFont.addNewSz();
@ -189,6 +205,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0);
}
@Test
public void testUnderline() {
CTFont ctFont=CTFont.Factory.newInstance();
CTUnderlineProperty underlinePropr=ctFont.addNewU();
@ -207,6 +224,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal());
}
@Test
public void testColor() {
CTFont ctFont=CTFont.Factory.newInstance();
CTColor color=ctFont.addNewColor();
@ -220,11 +238,12 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(IndexedColors.RED.getIndex(), ctFont.getColorArray(0).getIndexed());
}
@Test
public void testRgbColor() {
CTFont ctFont=CTFont.Factory.newInstance();
CTColor color=ctFont.addNewColor();
color.setRgb(Integer.toHexString(0xFFFFFF).getBytes());
color.setRgb(Integer.toHexString(0xFFFFFF).getBytes(LocaleUtil.CHARSET_1252));
ctFont.setColorArray(0,color);
XSSFFont xssfFont=new XSSFFont(ctFont);
@ -235,7 +254,7 @@ public final class TestXSSFFont extends BaseTestFont{
xssfFont.setColor((short)23);
byte[] bytes = Integer.toHexString(0xF1F1F1).getBytes();
byte[] bytes = Integer.toHexString(0xF1F1F1).getBytes(LocaleUtil.CHARSET_1252);
color.setRgb(bytes);
XSSFColor newColor=new XSSFColor(color);
xssfFont.setColor(newColor);
@ -245,6 +264,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(0, xssfFont.getColor());
}
@Test
public void testThemeColor() {
CTFont ctFont=CTFont.Factory.newInstance();
CTColor color=ctFont.addNewColor();
@ -258,6 +278,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(IndexedColors.RED.getIndex(),ctFont.getColorArray(0).getTheme());
}
@Test
public void testFamily() {
CTFont ctFont=CTFont.Factory.newInstance();
CTIntProperty family=ctFont.addNewFamily();
@ -268,6 +289,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(FontFamily.MODERN.getValue(),xssfFont.getFamily());
}
@Test
public void testScheme() {
CTFont ctFont=CTFont.Factory.newInstance();
CTFontScheme scheme=ctFont.addNewScheme();
@ -281,6 +303,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(STFontScheme.NONE,ctFont.getSchemeArray(0).getVal());
}
@Test
public void testTypeOffset() {
CTFont ctFont=CTFont.Factory.newInstance();
CTVerticalAlignFontProperty valign=ctFont.addNewVertAlign();
@ -295,7 +318,8 @@ public final class TestXSSFFont extends BaseTestFont{
}
// store test from TestSheetUtil here as it uses XSSF
public void testCanComputeWidthXSSF() throws IOException {
@Test
public void testCanComputeWidthXSSF() throws IOException {
Workbook wb = new XSSFWorkbook();
// cannot check on result because on some machines we get back false here!
@ -305,7 +329,8 @@ public final class TestXSSFFont extends BaseTestFont{
}
// store test from TestSheetUtil here as it uses XSSF
public void testCanComputeWidthInvalidFont() throws IOException {
@Test
public void testCanComputeWidthInvalidFont() throws IOException {
Font font = new XSSFFont(CTFont.Factory.newInstance());
font.setFontName("some non existing font name");

View File

@ -24,6 +24,7 @@ import java.util.List;
import org.apache.poi.ss.usermodel.BaseTestPicture;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
@ -58,7 +59,7 @@ public final class TestXSSFPicture extends BaseTestPicture {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
byte[] jpegData = "test jpeg data".getBytes();
byte[] jpegData = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252);
List<XSSFPictureData> pictures = wb.getAllPictures();
assertEquals(0, pictures.size());
@ -97,13 +98,13 @@ public final class TestXSSFPicture extends BaseTestPicture {
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30);
byte[] jpegData = "picture1".getBytes();
byte[] jpegData = "picture1".getBytes(LocaleUtil.CHARSET_1252);
int jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG);
XSSFPicture shape1 = drawing.createPicture(anchor, jpegIdx);
assertEquals(1, shape1.getCTPicture().getNvPicPr().getCNvPr().getId());
jpegData = "picture2".getBytes();
jpegData = "picture2".getBytes(LocaleUtil.CHARSET_1252);
jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG);
XSSFPicture shape2 = drawing.createPicture(anchor, jpegIdx);
assertEquals(2, shape2.getCTPicture().getNvPicPr().getCNvPr().getId());
@ -118,8 +119,8 @@ public final class TestXSSFPicture extends BaseTestPicture {
public void multiRelationShips() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
byte[] pic1Data = "test jpeg data".getBytes();
byte[] pic2Data = "test png data".getBytes();
byte[] pic1Data = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252);
byte[] pic2Data = "test png data".getBytes(LocaleUtil.CHARSET_1252);
List<XSSFPictureData> pictures = wb.getAllPictures();
assertEquals(0, pictures.size());

View File

@ -18,18 +18,23 @@
package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.io.IOException;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
/**
* @author Yegor Kozlov
*/
public final class TestXSSFPictureData extends TestCase {
public void testRead(){
public final class TestXSSFPictureData {
@Test
public void testRead() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
List<XSSFPictureData> pictures = wb.getAllPictures();
//wb.getAllPictures() should return the same instance across multiple calls
@ -54,16 +59,18 @@ public final class TestXSSFPictureData extends TestCase {
XSSFPictureData pict = pictures.get(idx);
assertEquals("jpeg", pict.suggestFileExtension());
assertArrayEquals(pictureData, pict.getData());
wb.close();
}
public void testNew(){
@Test
public void testNew() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
byte[] jpegData = "test jpeg data".getBytes();
byte[] wmfData = "test wmf data".getBytes();
byte[] pngData = "test png data".getBytes();
byte[] jpegData = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252);
byte[] wmfData = "test wmf data".getBytes(LocaleUtil.CHARSET_1252);
byte[] pngData = "test png data".getBytes(LocaleUtil.CHARSET_1252);
List<XSSFPictureData> pictures = wb.getAllPictures();
assertEquals(0, pictures.size());
@ -104,13 +111,15 @@ public final class TestXSSFPictureData extends TestCase {
assertEquals("png", pictures2.get(pngIdx).suggestFileExtension());
assertArrayEquals(pngData, pictures2.get(pngIdx).getData());
wbBack.close();
wb.close();
}
/**
* Bug 53568: XSSFPicture.getPictureData() can return null.
*/
public void test53568(){
@Test
public void test53568() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53568.xlsx");
List<XSSFPictureData> pictures = wb.getAllPictures();
assertNotNull(pictures);
@ -132,6 +141,6 @@ public final class TestXSSFPictureData extends TestCase {
}
}
}
wb.close();
}
}

View File

@ -31,7 +31,6 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ -53,6 +52,7 @@ import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.CalculationChain;
@ -1479,7 +1479,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
// Date
cell = CellUtil.getCell(destRow, col++);
assertEquals("[Date] E7 cell type", Cell.CELL_TYPE_NUMERIC, cell.getCellType());
final Date date = new GregorianCalendar(2000, Calendar.JANUARY, 1).getTime();
final Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime();
assertEquals("[Date] E7 cell value", date, cell.getDateCellValue());
// Boolean
@ -1641,12 +1641,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Date] E10 cell type", Cell.CELL_TYPE_NUMERIC, cell.getCellType());
Date date = new GregorianCalendar(2000, Calendar.JANUARY, 1).getTime();
Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime();
assertEquals("[Date] E10 cell value", date, cell.getDateCellValue());
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Date] E11 cell type", Cell.CELL_TYPE_NUMERIC, cell.getCellType());
date = new GregorianCalendar(2000, Calendar.JANUARY, 2).getTime();
date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 2).getTime();
assertEquals("[Date] E11 cell value", date, cell.getDateCellValue());
// Boolean

View File

@ -742,7 +742,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
sheetBack.commit();
String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()));
String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), "UTF-8");
assertEquals(1, countMatches(str, "<worksheet"));
} finally {

View File

@ -17,9 +17,12 @@
package org.apache.poi.hssf.usermodel;
import java.io.IOException;
import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestFont;
import org.apache.poi.ss.usermodel.Font;
import org.junit.Test;
/**
* Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}.
@ -32,7 +35,8 @@ public final class TestHSSFFont extends BaseTestFont {
super(HSSFITestDataProvider.instance);
}
public void testDefaultFont() {
@Test
public void testDefaultFont() throws IOException {
baseTestDefaultFont(HSSFFont.FONT_ARIAL, (short)200, Font.COLOR_NORMAL);
}
}

View File

@ -17,10 +17,10 @@
package org.apache.poi.hssf.usermodel;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import java.io.IOException;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.RecordFormatException;
@ -31,6 +31,8 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Test;
import junit.framework.AssertionFailedError;
/**
* @author aviks
*
@ -40,8 +42,9 @@ import org.junit.Test;
* Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are
* fixed, so that they are then run automatically.
*/
public final class TestUnfixedBugs extends TestCase {
public final class TestUnfixedBugs {
@Test
public void test43493() {
// Has crazy corrupt sub-records on
// a EmbeddedObjectRefSubRecord
@ -59,6 +62,7 @@ public final class TestUnfixedBugs extends TestCase {
* Note - some parts of this bug have been fixed, and have been
* transfered over to {@link TestBugs#bug49612_part()}
*/
@Test
public void test49612() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49612.xls");
HSSFSheet sh = wb.getSheetAt(0);
@ -79,54 +83,65 @@ public final class TestUnfixedBugs extends TestCase {
assertEquals("SUM('49612.xls'!BOB+'49612.xls'!JIM)", e1.getCellFormula());
// Problem 3 - fixed and transfered
wb.close();
}
@Test
public void testFormulaRecordAggregate_1() throws Exception {
// fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)"
Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958_1.xls");
for(int i = 0;i < wb.getNumberOfSheets();i++) {
Sheet sheet = wb.getSheetAt(i);
assertNotNull(wb.getSheet(sheet.getSheetName()));
sheet.groupColumn((short) 4, (short) 5);
sheet.setColumnGroupCollapsed(4, true);
sheet.setColumnGroupCollapsed(4, false);
try {
for(int i = 0;i < wb.getNumberOfSheets();i++) {
Sheet sheet = wb.getSheetAt(i);
assertNotNull(wb.getSheet(sheet.getSheetName()));
sheet.groupColumn((short) 4, (short) 5);
sheet.setColumnGroupCollapsed(4, true);
sheet.setColumnGroupCollapsed(4, false);
for(Row row : sheet) {
for(Cell cell : row) {
try {
cell.toString();
} catch (Exception e) {
throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e);
}
}
}
}
}
public void testFormulaRecordAggregate() throws Exception {
// fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)"
Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958.xls");
for(int i = 0;i < wb.getNumberOfSheets();i++) {
Sheet sheet = wb.getSheetAt(i);
assertNotNull(wb.getSheet(sheet.getSheetName()));
sheet.groupColumn((short) 4, (short) 5);
sheet.setColumnGroupCollapsed(4, true);
sheet.setColumnGroupCollapsed(4, false);
for(Row row : sheet) {
for(Cell cell : row) {
try {
cell.toString();
} catch (Exception e) {
throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e);
for(Row row : sheet) {
for(Cell cell : row) {
try {
cell.toString();
} catch (Exception e) {
throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e);
}
}
}
}
} finally {
wb.close();
}
}
@Test
public void testBug57074() {
public void testFormulaRecordAggregate() throws Exception {
// fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)"
Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958.xls");
try {
for(int i = 0;i < wb.getNumberOfSheets();i++) {
Sheet sheet = wb.getSheetAt(i);
assertNotNull(wb.getSheet(sheet.getSheetName()));
sheet.groupColumn((short) 4, (short) 5);
sheet.setColumnGroupCollapsed(4, true);
sheet.setColumnGroupCollapsed(4, false);
for(Row row : sheet) {
for(Cell cell : row) {
try {
cell.toString();
} catch (Exception e) {
throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e);
}
}
}
}
} finally {
wb.close();
}
}
@Test
public void testBug57074() throws IOException {
Workbook wb = HSSFTestDataSamples.openSampleWorkbook("57074.xls");
Sheet sheet = wb.getSheet("Sheet1");
Row row = sheet.getRow(0);
@ -141,5 +156,6 @@ public final class TestUnfixedBugs extends TestCase {
String fontColorStr = fontColor.getTriplet()[0]+", "+fontColor.getTriplet()[1]+", "+fontColor.getTriplet()[2];
//System.out.println(fontColorStr);
assertEquals("0, 128, 128", fontColorStr);
wb.close();
}
}

View File

@ -17,14 +17,17 @@
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import static org.junit.Assert.*;
import java.io.IOException;
import org.apache.poi.ss.ITestDataProvider;
import org.junit.Test;
/**
* @author Yegor Kozlov
*/
public abstract class BaseTestFont extends TestCase {
public abstract class BaseTestFont {
private final ITestDataProvider _testDataProvider;
@ -32,7 +35,7 @@ public abstract class BaseTestFont extends TestCase {
_testDataProvider = testDataProvider;
}
protected final void baseTestDefaultFont(String defaultName, short defaultSize, short defaultColor){
protected final void baseTestDefaultFont(String defaultName, short defaultSize, short defaultColor) throws IOException {
//get default font and check against default value
Workbook workbook = _testDataProvider.createWorkbook();
Font fontFind=workbook.findFont(Font.BOLDWEIGHT_NORMAL, defaultColor, defaultSize, defaultName, false, false, Font.SS_NONE, Font.U_NONE);
@ -49,9 +52,11 @@ public abstract class BaseTestFont extends TestCase {
assertEquals(15, font.getFontHeightInPoints());
fontFind=workbook.findFont(Font.BOLDWEIGHT_BOLD, defaultColor, (short)(15*20), defaultName, false, false, Font.SS_NONE, Font.U_DOUBLE);
assertNotNull(fontFind);
workbook.close();
}
public final void testGetNumberOfFonts(){
@Test
public final void testGetNumberOfFonts() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
int num0 = wb.getNumberOfFonts();
@ -74,63 +79,68 @@ public abstract class BaseTestFont extends TestCase {
assertEquals(Font.BOLDWEIGHT_BOLD,wb.getFontAt(idx1).getBoldweight());
assertEquals(Font.U_DOUBLE,wb.getFontAt(idx2).getUnderline());
assertEquals(23,wb.getFontAt(idx3).getFontHeightInPoints());
wb.close();
}
/**
* Tests that we can define fonts to a new
* file, save, load, and still see them
*/
public final void testCreateSave() {
Workbook wb = _testDataProvider.createWorkbook();
Sheet s1 = wb.createSheet();
@Test
public final void testCreateSave() throws IOException {
Workbook wb1 = _testDataProvider.createWorkbook();
Sheet s1 = wb1.createSheet();
Row r1 = s1.createRow(0);
Cell r1c1 = r1.createCell(0);
r1c1.setCellValue(2.2);
int num0 = wb.getNumberOfFonts();
int num0 = wb1.getNumberOfFonts();
Font font=wb.createFont();
Font font=wb1.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setStrikeout(true);
font.setColor(IndexedColors.YELLOW.getIndex());
font.setFontName("Courier");
short font1Idx = font.getIndex();
wb.createCellStyle().setFont(font);
assertEquals(num0 + 1, wb.getNumberOfFonts());
wb1.createCellStyle().setFont(font);
assertEquals(num0 + 1, wb1.getNumberOfFonts());
CellStyle cellStyleTitle=wb.createCellStyle();
CellStyle cellStyleTitle=wb1.createCellStyle();
cellStyleTitle.setFont(font);
r1c1.setCellStyle(cellStyleTitle);
// Save and re-load
wb = _testDataProvider.writeOutAndReadBack(wb);
s1 = wb.getSheetAt(0);
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
s1 = wb2.getSheetAt(0);
assertEquals(num0 + 1, wb.getNumberOfFonts());
assertEquals(num0 + 1, wb2.getNumberOfFonts());
short idx = s1.getRow(0).getCell(0).getCellStyle().getFontIndex();
Font fnt = wb.getFontAt(idx);
Font fnt = wb2.getFontAt(idx);
assertNotNull(fnt);
assertEquals(IndexedColors.YELLOW.getIndex(), fnt.getColor());
assertEquals("Courier", fnt.getFontName());
// Now add an orphaned one
Font font2 = wb.createFont();
Font font2 = wb2.createFont();
font2.setItalic(true);
font2.setFontHeightInPoints((short)15);
short font2Idx = font2.getIndex();
wb.createCellStyle().setFont(font2);
assertEquals(num0 + 2, wb.getNumberOfFonts());
wb2.createCellStyle().setFont(font2);
assertEquals(num0 + 2, wb2.getNumberOfFonts());
// Save and re-load
wb = _testDataProvider.writeOutAndReadBack(wb);
s1 = wb.getSheetAt(0);
Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2);
wb2.close();
s1 = wb3.getSheetAt(0);
assertEquals(num0 + 2, wb.getNumberOfFonts());
assertNotNull(wb.getFontAt(font1Idx));
assertNotNull(wb.getFontAt(font2Idx));
assertEquals(num0 + 2, wb3.getNumberOfFonts());
assertNotNull(wb3.getFontAt(font1Idx));
assertNotNull(wb3.getFontAt(font2Idx));
assertEquals(15, wb.getFontAt(font2Idx).getFontHeightInPoints());
assertEquals(true, wb.getFontAt(font2Idx).getItalic());
assertEquals(15, wb3.getFontAt(font2Idx).getFontHeightInPoints());
assertEquals(true, wb3.getFontAt(font2Idx).getItalic());
wb3.close();
}
/**
@ -138,7 +148,8 @@ public abstract class BaseTestFont extends TestCase {
*
* @see org.apache.poi.hssf.usermodel.TestBugs#test45338()
*/
public final void test45338() {
@Test
public final void test45338() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
int num0 = wb.getNumberOfFonts();
@ -200,5 +211,6 @@ public abstract class BaseTestFont extends TestCase {
"Thingy", false, true, (short)2, (byte)2
)
);
wb.close();
}
}