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="${scratchpad.output.dir}"/>
<fileset dir="${ooxml.output.dir}"/> <fileset dir="${ooxml.output.dir}"/>
<fileset dir="${main.output.test.dir}"/> <fileset dir="${main.output.test.dir}"/>
<fileset dir="${ooxml.output.test.dir}"/>
<!-- <!--
<fileset dir="${scratchpad.output.test.dir}"/> <fileset dir="${scratchpad.output.test.dir}"/>
<fileset dir="${ooxml.output.test.dir}"/>
--> -->
</forbiddenapis> </forbiddenapis>
</target> </target>

View File

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

View File

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

View File

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

View File

@ -17,26 +17,37 @@
package org.apache.poi.xssf.extractor; 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.text.SimpleDateFormat;
import java.util.Date; 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.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFMap; import org.apache.poi.xssf.usermodel.XSSFMap;
import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.xml.sax.SAXException;
/** /**
* *
* @author Roberto Manicardi * @author Roberto Manicardi
* *
*/ */
public class TestXSSFImportFromXML extends TestCase { public class TestXSSFImportFromXML {
@Test
public void testImportFromXML() throws Exception{ public void testImportFromXML() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx");
try { try {
@ -82,10 +93,8 @@ public class TestXSSFImportFromXML extends TestCase {
} }
} }
@Test
public void testMultiTable() throws IOException, XPathExpressionException, SAXException{
public void testMultiTable() throws Exception{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx");
try { try {
String cellC6 = "c6"; 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"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx");
try { try {
int id = 1; int id = 1;
@ -148,16 +158,17 @@ public class TestXSSFImportFromXML extends TestCase {
//Check for Schema element //Check for Schema element
XSSFSheet sheet=wb.getSheetAt(0); 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(displayName, sheet.getRow(11).getCell(5).getStringCellValue());
assertEquals(ref, sheet.getRow(14).getCell(7).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 { } finally {
wb.close(); 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"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx");
try { try {
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + 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"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57890.xlsx");
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<TestInfoRoot>" 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); XSSFRow rowData = sheet.getRow(1);
assertEquals("Date", rowHeadings.getCell(0).getStringCellValue()); 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(date, rowData.getCell(0).getDateCellValue());
assertEquals("Amount Int", rowHeadings.getCell(1).getStringCellValue()); 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("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("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.ArrayList;
import java.util.List; import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.POIXMLException;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples; 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.CTRPrElt;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import junit.framework.TestCase;
/** /**
* Test {@link SharedStringsTable}, the cache of strings in a workbook * 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()); assertEquals("Second string", new XSSFRichTextString(sst.getEntryAt(2)).toString());
} }
public void testReadWrite() { public void testReadWrite() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
SharedStringsTable sst1 = wb.getSharedStringSource(); SharedStringsTable sst1 = wb1.getSharedStringSource();
//serialize, read back and compare with the original //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.getCount(), sst2.getCount());
assertEquals(sst1.getUniqueCount(), sst2.getUniqueCount()); assertEquals(sst1.getUniqueCount(), sst2.getUniqueCount());
@ -133,7 +133,11 @@ public final class TestSharedStringsTable extends TestCase {
assertEquals(st1.toString(), st2.toString()); 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 * @author Philippe Laflamme
*/ */
public void testBug48936() throws IOException { public void testBug48936() throws IOException {
Workbook w = new XSSFWorkbook(); Workbook w1 = new XSSFWorkbook();
Sheet s = w.createSheet(); Sheet s = w1.createSheet();
int i = 0; int i = 0;
List<String> lst = readStrings("48936-strings.txt"); List<String> lst = readStrings("48936-strings.txt");
for (String str : lst) { for (String str : lst) {
s.createRow(i++).createCell(0).setCellValue(str); s.createRow(i++).createCell(0).setCellValue(str);
} }
try { Workbook w2 = XSSFTestDataSamples.writeOutAndReadBack(w1);
w = XSSFTestDataSamples.writeOutAndReadBack(w); w1.close();
} catch (POIXMLException e){ s = w2.getSheetAt(0);
fail("Detected Bug #48936");
}
s = w.getSheetAt(0);
i = 0; i = 0;
for (String str : lst) { for (String str : lst) {
String val = s.getRow(i++).getCell(0).getStringCellValue(); String val = s.getRow(i++).getCell(0).getStringCellValue();
assertEquals(str, val); 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 { private List<String> readStrings(String filename) throws IOException {
List<String> strs = new ArrayList<String>(); List<String> strs = new ArrayList<String>();
POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();
BufferedReader br = new BufferedReader( BufferedReader br = new BufferedReader(
new InputStreamReader(samples.openResourceAsStream(filename))); new InputStreamReader(samples.openResourceAsStream(filename), "UTF-8"));
String s; String s;
while ((s = br.readLine()) != null) { while ((s = br.readLine()) != null) {
if (s.trim().length() > 0) { 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 // 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 posR12 = xml.indexOf("<row r=\"12\"");
int posR13 = xml.indexOf("<row r=\"13\""); int posR13 = xml.indexOf("<row r=\"13\"");

View File

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

View File

@ -18,18 +18,23 @@
package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.assertArrayEquals; 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 java.util.List;
import junit.framework.TestCase; import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
/** /**
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class TestXSSFPictureData extends TestCase { public final class TestXSSFPictureData {
public void testRead(){ @Test
public void testRead() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
List<XSSFPictureData> pictures = wb.getAllPictures(); List<XSSFPictureData> pictures = wb.getAllPictures();
//wb.getAllPictures() should return the same instance across multiple calls //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); XSSFPictureData pict = pictures.get(idx);
assertEquals("jpeg", pict.suggestFileExtension()); assertEquals("jpeg", pict.suggestFileExtension());
assertArrayEquals(pictureData, pict.getData()); assertArrayEquals(pictureData, pict.getData());
wb.close();
} }
public void testNew(){ @Test
public void testNew() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFDrawing drawing = sheet.createDrawingPatriarch();
byte[] jpegData = "test jpeg data".getBytes(); byte[] jpegData = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252);
byte[] wmfData = "test wmf data".getBytes(); byte[] wmfData = "test wmf data".getBytes(LocaleUtil.CHARSET_1252);
byte[] pngData = "test png data".getBytes(); byte[] pngData = "test png data".getBytes(LocaleUtil.CHARSET_1252);
List<XSSFPictureData> pictures = wb.getAllPictures(); List<XSSFPictureData> pictures = wb.getAllPictures();
assertEquals(0, pictures.size()); assertEquals(0, pictures.size());
@ -104,13 +111,15 @@ public final class TestXSSFPictureData extends TestCase {
assertEquals("png", pictures2.get(pngIdx).suggestFileExtension()); assertEquals("png", pictures2.get(pngIdx).suggestFileExtension());
assertArrayEquals(pngData, pictures2.get(pngIdx).getData()); assertArrayEquals(pngData, pictures2.get(pngIdx).getData());
wbBack.close();
wb.close();
} }
/** /**
* Bug 53568: XSSFPicture.getPictureData() can return null. * Bug 53568: XSSFPicture.getPictureData() can return null.
*/ */
public void test53568(){ @Test
public void test53568() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53568.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53568.xlsx");
List<XSSFPictureData> pictures = wb.getAllPictures(); List<XSSFPictureData> pictures = wb.getAllPictures();
assertNotNull(pictures); 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.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; 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.CellRangeAddress;
import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.util.CellUtil; import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.CalculationChain; import org.apache.poi.xssf.model.CalculationChain;
@ -1479,7 +1479,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
// Date // Date
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("[Date] E7 cell type", Cell.CELL_TYPE_NUMERIC, cell.getCellType()); 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()); assertEquals("[Date] E7 cell value", date, cell.getDateCellValue());
// Boolean // Boolean
@ -1641,12 +1641,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Date] E10 cell type", Cell.CELL_TYPE_NUMERIC, cell.getCellType()); 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()); assertEquals("[Date] E10 cell value", date, cell.getDateCellValue());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Date] E11 cell type", Cell.CELL_TYPE_NUMERIC, cell.getCellType()); 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()); assertEquals("[Date] E11 cell value", date, cell.getDateCellValue());
// Boolean // Boolean

View File

@ -742,7 +742,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
sheetBack.commit(); 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")); assertEquals(1, countMatches(str, "<worksheet"));
} finally { } finally {

View File

@ -17,9 +17,12 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.IOException;
import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestFont; import org.apache.poi.ss.usermodel.BaseTestFont;
import org.apache.poi.ss.usermodel.Font; 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}. * 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); super(HSSFITestDataProvider.instance);
} }
public void testDefaultFont() { @Test
public void testDefaultFont() throws IOException {
baseTestDefaultFont(HSSFFont.FONT_ARIAL, (short)200, Font.COLOR_NORMAL); baseTestDefaultFont(HSSFFont.FONT_ARIAL, (short)200, Font.COLOR_NORMAL);
} }
} }

View File

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

View File

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