refactored all hssf junits to get test sample data in the in one place

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@645348 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Josh Micich 2008-04-07 03:02:03 +00:00
parent 1051e2853c
commit 27761348b9
49 changed files with 3051 additions and 4113 deletions

View File

@ -37,6 +37,7 @@
<!-- Don't forget to update status.xml too! --> <!-- Don't forget to update status.xml too! -->
<release version="3.0.3-beta1" date="2008-04-??"> <release version="3.0.3-beta1" date="2008-04-??">
<action dev="POI-DEVELOPERS" type="fix">refactored all junits' usage of HSSF.testdata.path to one place</action>
<action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action> <action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action>
<action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action> <action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action>
<action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action> <action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action>

View File

@ -34,6 +34,7 @@
<!-- Don't forget to update changes.xml too! --> <!-- Don't forget to update changes.xml too! -->
<changes> <changes>
<release version="3.0.3-beta1" date="2008-04-??"> <release version="3.0.3-beta1" date="2008-04-??">
<action dev="POI-DEVELOPERS" type="fix">refactored all junits' usage of HSSF.testdata.path to one place</action>
<action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action> <action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action>
<action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action> <action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action>
<action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action> <action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action>

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,7 +14,6 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.util; package org.apache.poi.util;
@ -25,6 +23,7 @@ import java.util.ArrayList;
/** /**
* Utilities to read hex from files. * Utilities to read hex from files.
* TODO - move to test packages
* *
* @author Marc Johnson * @author Marc Johnson
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
@ -62,10 +61,8 @@ public class HexRead
* *
* @see #readData(String) * @see #readData(String)
*/ */
public static byte[] readData( String filename, String section ) throws IOException public static byte[] readData(InputStream stream, String section ) throws IOException {
{
File file = new File( filename );
FileInputStream stream = new FileInputStream( file );
try try
{ {
StringBuffer sectionText = new StringBuffer(); StringBuffer sectionText = new StringBuffer();
@ -100,6 +97,12 @@ public class HexRead
} }
throw new IOException( "Section '" + section + "' not found" ); throw new IOException( "Section '" + section + "' not found" );
} }
public static byte[] readData( String filename, String section ) throws IOException
{
File file = new File( filename );
FileInputStream stream = new FileInputStream( file );
return readData(stream, section);
}
static public byte[] readData( InputStream stream, int eofChar ) static public byte[] readData( InputStream stream, int eofChar )
throws IOException throws IOException

View File

@ -15,17 +15,17 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi; package org.apache.poi;
import junit.framework.TestCase; import java.io.ByteArrayInputStream;
import java.io.*; import java.io.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import junit.framework.TestCase;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Tests that POIDocument correctly loads and saves the common * Tests that POIDocument correctly loads and saves the common
@ -36,85 +36,73 @@ import org.apache.poi.poifs.filesystem.*;
* *
* @author Nick Burch (nick at torchbox dot com) * @author Nick Burch (nick at torchbox dot com)
*/ */
public class TestPOIDocumentMain extends TestCase { public final class TestPOIDocumentMain extends TestCase {
// The POI Documents to work on // The POI Documents to work on
private POIDocument doc; private POIDocument doc;
private POIDocument doc2; private POIDocument doc2;
// POIFS primed on the test (two different hssf) data
private POIFSFileSystem pfs;
private POIFSFileSystem pfs2;
/** /**
* Set things up, using a PowerPoint document and * Set things up, two spreadsheets for our testing
* a Word Document for our testing
*/ */
public void setUp() throws Exception { public void setUp() {
String dirnameHSSF = System.getProperty("HSSF.testdata.path");
String filenameHSSF = dirnameHSSF + "/DateFormats.xls";
String filenameHSSF2 = dirnameHSSF + "/StringFormulas.xls";
FileInputStream fisHSSF = new FileInputStream(filenameHSSF); doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
pfs = new POIFSFileSystem(fisHSSF); doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls");
doc = new HSSFWorkbook(pfs); }
FileInputStream fisHSSF2 = new FileInputStream(filenameHSSF2); public void testReadProperties() throws Exception {
pfs2 = new POIFSFileSystem(fisHSSF2); // We should have both sets
doc2 = new HSSFWorkbook(pfs2); assertNotNull(doc.getDocumentSummaryInformation());
assertNotNull(doc.getSummaryInformation());
// Check they are as expected for the test doc
assertEquals("Administrator", doc.getSummaryInformation().getAuthor());
assertEquals(0, doc.getDocumentSummaryInformation().getByteCount());
}
public void testReadProperties2() throws Exception {
// Check again on the word one
assertNotNull(doc2.getDocumentSummaryInformation());
assertNotNull(doc2.getSummaryInformation());
assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor());
assertEquals(null, doc2.getSummaryInformation().getKeywords());
assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
} }
public void testReadProperties() throws Exception {
// We should have both sets
assertNotNull(doc.getDocumentSummaryInformation());
assertNotNull(doc.getSummaryInformation());
// Check they are as expected for the test doc
assertEquals("Administrator", doc.getSummaryInformation().getAuthor());
assertEquals(0, doc.getDocumentSummaryInformation().getByteCount());
}
public void testReadProperties2() throws Exception {
// Check again on the word one
assertNotNull(doc2.getDocumentSummaryInformation());
assertNotNull(doc2.getSummaryInformation());
assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor());
assertEquals(null, doc2.getSummaryInformation().getKeywords());
assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
}
public void testWriteProperties() throws Exception { public void testWriteProperties() throws Exception {
// Just check we can write them back out into a filesystem // Just check we can write them back out into a filesystem
POIFSFileSystem outFS = new POIFSFileSystem(); POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties(); doc.readProperties();
doc.writeProperties(outFS); doc.writeProperties(outFS);
// Should now hold them // Should now hold them
assertNotNull( assertNotNull(
outFS.createDocumentInputStream("\005SummaryInformation") outFS.createDocumentInputStream("\005SummaryInformation")
); );
assertNotNull( assertNotNull(
outFS.createDocumentInputStream("\005DocumentSummaryInformation") outFS.createDocumentInputStream("\005DocumentSummaryInformation")
); );
} }
public void testWriteReadProperties() throws Exception { public void testWriteReadProperties() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Write them out // Write them out
POIFSFileSystem outFS = new POIFSFileSystem(); POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties(); doc.readProperties();
doc.writeProperties(outFS); doc.writeProperties(outFS);
outFS.writeFilesystem(baos); outFS.writeFilesystem(baos);
// Create a new version // Create a new version
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
POIFSFileSystem inFS = new POIFSFileSystem(bais); POIFSFileSystem inFS = new POIFSFileSystem(bais);
// Check they're still there // Check they're still there
doc.filesystem = inFS; doc.filesystem = inFS;
doc.readProperties(); doc.readProperties();
// Delegate test // Delegate test
testReadProperties(); testReadProperties();
} }
} }

View File

@ -0,0 +1,175 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder.
*
* @author Josh Micich
*/
public final class HSSFTestDataSamples {
private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path";
private static boolean _isInitialised;
private static File _resolvedDataDir;
/** <code>true</code> if standard system propery is not set,
* but the data is available on the test runtime classpath */
private static boolean _sampleDataIsAvaliableOnClassPath;
/**
* Opens a sample file from the standard HSSF test data directory
*
* @return an open <tt>InputStream</tt> for the specified sample file
*/
public static InputStream openSampleFileStream(String sampleFileName) {
if(!_isInitialised) {
try {
initialise();
} finally {
_isInitialised = true;
}
}
if (_sampleDataIsAvaliableOnClassPath) {
InputStream result = openClasspathResource(sampleFileName);
if(result == null) {
throw new RuntimeException("specified test sample file '" + sampleFileName
+ "' not found on the classpath");
}
// System.out.println("opening cp: " + sampleFileName);
// wrap to avoid temp warning method about auto-closing input stream
return new NonSeekableInputStream(result);
}
if (_resolvedDataDir == null) {
throw new RuntimeException("Must set system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME
+ "' properly before running tests");
}
File f = new File(_resolvedDataDir, sampleFileName);
if (!f.exists()) {
throw new RuntimeException("Sample file '" + sampleFileName
+ "' not found in data dir '" + _resolvedDataDir.getAbsolutePath() + "'");
}
// System.out.println("opening " + f.getAbsolutePath());
try {
return new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private static void initialise() {
String dataDirName = System.getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME);
if (dataDirName == null) {
// check to see if we can just get the resources from the classpath
InputStream is = openClasspathResource("SampleSS.xls");
if(is != null) {
try {
is.close(); // be nice
} catch (IOException e) {
throw new RuntimeException(e);
}
_sampleDataIsAvaliableOnClassPath = true;
return;
}
throw new RuntimeException("Must set system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME
+ "' before running tests");
}
File dataDir = new File(dataDirName);
if (!dataDir.exists()) {
throw new RuntimeException("Data dir '" + dataDirName
+ "' specified by system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist");
}
// convert to canonical file, to make any subsequent error messages clearer.
try {
_resolvedDataDir = dataDir.getCanonicalFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Opens a test sample file from the 'data' sub-package of this class's package.
* @return <code>null</code> if the sample file is not deployed on the classpath.
*/
private static InputStream openClasspathResource(String sampleFileName) {
return HSSFTestDataSamples.class.getResourceAsStream("data/" + sampleFileName);
}
private static final class NonSeekableInputStream extends InputStream {
private final InputStream _is;
public NonSeekableInputStream(InputStream is) {
_is = is;
}
public int read() throws IOException {
return _is.read();
}
public int read(byte[] b, int off, int len) throws IOException {
return _is.read(b, off, len);
}
public boolean markSupported() {
return false;
}
public void close() throws IOException {
_is.close();
}
}
public static HSSFWorkbook openSampleWorkbook(String sampleFileName) {
try {
return new HSSFWorkbook(openSampleFileStream(sampleFileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Writes a spreadsheet to a <tt>ByteArrayOutputStream</tt> and reads it back
* from a <tt>ByteArrayInputStream</tt>.<p/>
* Useful for verifying that the serialisation round trip
*/
public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
original.write(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new HSSFWorkbook(bais);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -16,109 +16,108 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.eventusermodel; package org.apache.poi.hssf.eventusermodel;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; import java.io.InputStream;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.ContinueRecord;
import org.apache.poi.hssf.record.DVALRecord; import org.apache.poi.hssf.record.DVALRecord;
import org.apache.poi.hssf.record.DVRecord; import org.apache.poi.hssf.record.DVRecord;
import org.apache.poi.hssf.record.EOFRecord; import org.apache.poi.hssf.record.EOFRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.ContinueRecord;
import org.apache.poi.hssf.record.SelectionRecord; import org.apache.poi.hssf.record.SelectionRecord;
import org.apache.poi.hssf.record.WindowTwoRecord; import org.apache.poi.hssf.record.WindowTwoRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
import junit.framework.TestCase; *
*/
public class TestHSSFEventFactory extends TestCase { public final class TestHSSFEventFactory extends TestCase {
private String dirname;
public TestHSSFEventFactory() { private static final InputStream openSample(String sampleFileName) {
dirname = System.getProperty("HSSF.testdata.path"); return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
} }
public void testWithMissingRecords() throws Exception { public void testWithMissingRecords() throws Exception {
File f = new File(dirname + "/SimpleWithSkip.xls");
HSSFRequest req = new HSSFRequest(); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener(); MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen); req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); POIFSFileSystem fs = new POIFSFileSystem(openSample("SimpleWithSkip.xls"));
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs); factory.processWorkbookEvents(req, fs);
Record[] recs = mockListen.getRecords();
// Check we got the records // Check we got the records
System.out.println("Processed, found " + mockListen.records.size() + " records"); assertTrue( recs.length > 100 );
assertTrue( mockListen.records.size() > 100 );
// Check that the last few records are as we expect // Check that the last few records are as we expect
// (Makes sure we don't accidently skip the end ones) // (Makes sure we don't accidently skip the end ones)
int numRec = mockListen.records.size(); int numRec = recs.length;
assertEquals(WindowTwoRecord.class, mockListen.records.get(numRec-3).getClass()); assertEquals(WindowTwoRecord.class, recs[numRec-3].getClass());
assertEquals(SelectionRecord.class, mockListen.records.get(numRec-2).getClass()); assertEquals(SelectionRecord.class, recs[numRec-2].getClass());
assertEquals(EOFRecord.class, mockListen.records.get(numRec-1).getClass()); assertEquals(EOFRecord.class, recs[numRec-1].getClass());
} }
public void testWithCrazyContinueRecords() throws Exception { public void testWithCrazyContinueRecords() throws Exception {
// Some files have crazy ordering of their continue records // Some files have crazy ordering of their continue records
// Check that we don't break on them (bug #42844) // Check that we don't break on them (bug #42844)
File f = new File(dirname + "/ContinueRecordProblem.xls");
HSSFRequest req = new HSSFRequest(); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener(); MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen); req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); POIFSFileSystem fs = new POIFSFileSystem(openSample("ContinueRecordProblem.xls"));
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs); factory.processWorkbookEvents(req, fs);
Record[] recs = mockListen.getRecords();
// Check we got the records // Check we got the records
System.out.println("Processed, found " + mockListen.records.size() + " records"); assertTrue( recs.length > 100 );
assertTrue( mockListen.records.size() > 100 );
// And none of them are continue ones // And none of them are continue ones
Record[] r = (Record[])mockListen.records.toArray( for(int i=0; i<recs.length; i++) {
new Record[mockListen.records.size()] ); assertFalse( recs[i] instanceof ContinueRecord );
for(int i=0; i<r.length; i++) {
assertFalse( r[i] instanceof ContinueRecord );
} }
// Check that the last few records are as we expect // Check that the last few records are as we expect
// (Makes sure we don't accidently skip the end ones) // (Makes sure we don't accidently skip the end ones)
int numRec = mockListen.records.size(); int numRec = recs.length;
assertEquals(DVALRecord.class, mockListen.records.get(numRec-3).getClass()); assertEquals(DVALRecord.class, recs[numRec-3].getClass());
assertEquals(DVRecord.class, mockListen.records.get(numRec-2).getClass()); assertEquals(DVRecord.class, recs[numRec-2].getClass());
assertEquals(EOFRecord.class, mockListen.records.get(numRec-1).getClass()); assertEquals(EOFRecord.class, recs[numRec-1].getClass());
} }
/** /**
* Unknown records can be continued. * Unknown records can be continued.
* Check that HSSFEventFactory doesn't break on them. * Check that HSSFEventFactory doesn't break on them.
* (the test file was provided in a reopen of bug #42844) * (the test file was provided in a reopen of bug #42844)
*/ */
public void testUnknownContinueRecords() throws Exception { public void testUnknownContinueRecords() throws Exception {
File f = new File(dirname + "/42844.xls");
HSSFRequest req = new HSSFRequest(); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener(); MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen); req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); POIFSFileSystem fs = new POIFSFileSystem(openSample("42844.xls"));
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs); factory.processWorkbookEvents(req, fs);
assertTrue("no errors while processing the file", true); assertTrue("no errors while processing the file", true);
} }
private static class MockHSSFListener implements HSSFListener { private static class MockHSSFListener implements HSSFListener {
private MockHSSFListener() {} private final List records = new ArrayList();
private ArrayList records = new ArrayList();
public MockHSSFListener() {}
public Record[] getRecords() {
Record[] result = new Record[records.size()];
records.toArray(result);
return result;
}
public void processRecord(Record record) { public void processRecord(Record record) {
records.add(record); records.add(record);

View File

@ -19,11 +19,13 @@ package org.apache.poi.hssf.eventusermodel;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord;
@ -39,8 +41,6 @@ public final class TestMissingRecordAwareHSSFListener extends TestCase {
private Record[] r; private Record[] r;
public void setUp() { public void setUp() {
String dirname = System.getProperty("HSSF.testdata.path");
File f = new File(dirname + "/MissingBits.xls");
HSSFRequest req = new HSSFRequest(); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener(); MockHSSFListener mockListen = new MockHSSFListener();
@ -49,7 +49,8 @@ public final class TestMissingRecordAwareHSSFListener extends TestCase {
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
try { try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); InputStream is = HSSFTestDataSamples.openSampleFileStream("MissingBits.xls");
POIFSFileSystem fs = new POIFSFileSystem(is);
factory.processWorkbookEvents(req, fs); factory.processWorkbookEvents(req, fs);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -14,21 +14,36 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.extractor; package org.apache.poi.hssf.extractor;
import java.io.File; import java.io.IOException;
import java.io.FileInputStream; import java.io.InputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestExcelExtractor extends TestCase { import org.apache.poi.hssf.HSSFTestDataSamples;
public void testSimple() throws Exception { import org.apache.poi.poifs.filesystem.POIFSFileSystem;
String path = System.getProperty("HSSF.testdata.path"); /**
FileInputStream fin = new FileInputStream(path + File.separator + "Simple.xls"); *
*/
public final class TestExcelExtractor extends TestCase {
private static final ExcelExtractor createExtractor(String sampleFileName) {
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
try {
return new ExcelExtractor(new POIFSFileSystem(is));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void testSimple() {
ExcelExtractor extractor = createExtractor("Simple.xls");
assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText()); assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText());
@ -37,11 +52,9 @@ public class TestExcelExtractor extends TestCase {
assertEquals("replaceMe\n", extractor.getText()); assertEquals("replaceMe\n", extractor.getText());
} }
public void testNumericFormula() throws Exception { public void testNumericFormula() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "sumifformula.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("sumifformula.xls");
assertEquals( assertEquals(
"Sheet1\n" + "Sheet1\n" +
@ -68,11 +81,9 @@ public class TestExcelExtractor extends TestCase {
); );
} }
public void testwithContinueRecords() throws Exception { public void testwithContinueRecords() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "StringContinueRecords.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("StringContinueRecords.xls");
extractor.getText(); extractor.getText();
@ -82,11 +93,9 @@ public class TestExcelExtractor extends TestCase {
assertTrue(extractor.getText().length() > 40960); assertTrue(extractor.getText().length() > 40960);
} }
public void testStringConcat() throws Exception { public void testStringConcat() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "SimpleWithFormula.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls");
// Comes out as NaN if treated as a number // Comes out as NaN if treated as a number
// And as XYZ if treated as a string // And as XYZ if treated as a string
@ -97,11 +106,9 @@ public class TestExcelExtractor extends TestCase {
assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText()); assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText());
} }
public void testStringFormula() throws Exception { public void testStringFormula() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "StringFormulas.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("StringFormulas.xls");
// Comes out as NaN if treated as a number // Comes out as NaN if treated as a number
// And as XYZ if treated as a string // And as XYZ if treated as a string

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,36 +14,28 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.File; import java.io.InputStream;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestBOFRecord extends TestCase import org.apache.poi.hssf.HSSFTestDataSamples;
{ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
private String _test_file_path; /**
private static final String _test_file_path_property = "HSSF.testdata.path"; *
*/
public TestBOFRecord() public final class TestBOFRecord extends TestCase {
{
super();
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "bug_42794.xls";
}
public void testBOFRecord() throws Exception { public void testBOFRecord() throws Exception {
POIFSFileSystem fs = new POIFSFileSystem( InputStream is = HSSFTestDataSamples.openSampleFileStream("bug_42794.xls");
new FileInputStream(_test_file_path)
); // This used to throw an error before
try {
// This used to throw an error before new HSSFWorkbook(is);
HSSFWorkbook hssf = new HSSFWorkbook(fs); } catch (ArrayIndexOutOfBoundsException e) {
throw new AssertionFailedError("Identified bug 42794");
}
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,65 +14,57 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestChartTitleFormatRecord extends TestCase import org.apache.poi.hssf.HSSFTestDataSamples;
{ import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
private String _test_file_path; import org.apache.poi.hssf.eventusermodel.HSSFListener;
private static final String _test_file_path_property = "HSSF.testdata.path"; import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*
*/
public final class TestChartTitleFormatRecord extends TestCase {
public TestChartTitleFormatRecord() public void testRecord() throws Exception {
{ POIFSFileSystem fs = new POIFSFileSystem(
super(); HSSFTestDataSamples.openSampleFileStream("WithFormattedGraphTitle.xls"));
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "WithFormattedGraphTitle.xls"; // Check we can open the file via usermodel
} HSSFWorkbook hssf = new HSSFWorkbook(fs);
public void testRecord() throws Exception { // Now process it through eventusermodel, and
POIFSFileSystem fs = new POIFSFileSystem( // look out for the title records
new FileInputStream(_test_file_path) ChartTitleFormatRecordGrabber grabber = new ChartTitleFormatRecordGrabber();
); InputStream din = fs.createDocumentInputStream("Workbook");
HSSFRequest req = new HSSFRequest();
// Check we can open the file via usermodel req.addListenerForAllRecords(grabber);
HSSFWorkbook hssf = new HSSFWorkbook(fs); HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, din);
// Now process it through eventusermodel, and din.close();
// look out for the title records
ChartTitleFormatRecordGrabber grabber = // Should've found one
new ChartTitleFormatRecordGrabber(); assertEquals(1, grabber.chartTitleFormatRecords.size());
InputStream din = fs.createDocumentInputStream("Workbook"); // And it should be of something interesting
HSSFRequest req = new HSSFRequest(); ChartTitleFormatRecord r =
req.addListenerForAllRecords(grabber); (ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0);
HSSFEventFactory factory = new HSSFEventFactory(); assertEquals(3, r.getFormatCount());
factory.processEvents(req, din); }
din.close();
private static final class ChartTitleFormatRecordGrabber implements HSSFListener {
// Should've found one private final List chartTitleFormatRecords;
assertEquals(1, grabber.chartTitleFormatRecords.size());
// And it should be of something interesting public ChartTitleFormatRecordGrabber() {
ChartTitleFormatRecord r = chartTitleFormatRecords = new ArrayList();
(ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0); }
assertEquals(3, r.getFormatCount());
}
public static class ChartTitleFormatRecordGrabber implements HSSFListener {
private ArrayList chartTitleFormatRecords = new ArrayList();
public void processRecord(Record record) { public void processRecord(Record record) {
if(record instanceof ChartTitleFormatRecord) { if(record instanceof ChartTitleFormatRecord) {
@ -82,6 +73,6 @@ public class TestChartTitleFormatRecord extends TestCase
); );
} }
} }
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,8 +14,6 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
@ -39,36 +36,29 @@ import junit.framework.TestCase;
* *
* @author Andrew C. Oliver * @author Andrew C. Oliver
*/ */
public class TestFormulaRecord public final class TestFormulaRecord extends TestCase {
extends TestCase
{
public TestFormulaRecord(String name) public void testCreateFormulaRecord () {
{ FormulaRecord record = new FormulaRecord();
super(name); record.setColumn((short)0);
} //record.setRow((short)1);
record.setRow(1);
public void testCreateFormulaRecord () { record.setXFIndex((short)4);
FormulaRecord record = new FormulaRecord();
record.setColumn((short)0); assertEquals(record.getColumn(),(short)0);
//record.setRow((short)1); //assertEquals(record.getRow(),(short)1);
record.setRow(1); assertEquals((short)record.getRow(),(short)1);
record.setXFIndex((short)4); assertEquals(record.getXFIndex(),(short)4);
}
assertEquals(record.getColumn(),(short)0);
//assertEquals(record.getRow(),(short)1); /**
assertEquals((short)record.getRow(),(short)1); * Make sure a NAN value is preserved
assertEquals(record.getXFIndex(),(short)4); * This formula record is a representation of =1/0 at row 0, column 0
} */
public void testCheckNanPreserve() {
/** byte[] formulaByte = new byte[29];
* Make sure a NAN value is preserved for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0;
* This formula record is a representation of =1/0 at row 0, column 0 formulaByte[4] = (byte)0x0F;
*/
public void testCheckNanPreserve() {
byte[] formulaByte = new byte[29];
for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0;
formulaByte[4] = (byte)0x0F;
formulaByte[6] = (byte)0x02; formulaByte[6] = (byte)0x02;
formulaByte[8] = (byte)0x07; formulaByte[8] = (byte)0x07;
formulaByte[12] = (byte)0xFF; formulaByte[12] = (byte)0xFF;
@ -80,7 +70,7 @@ public class TestFormulaRecord
formulaByte[23] = (byte)0x01; formulaByte[23] = (byte)0x01;
formulaByte[25] = (byte)0x1E; formulaByte[25] = (byte)0x1E;
formulaByte[28] = (byte)0x06; formulaByte[28] = (byte)0x06;
FormulaRecord record = new FormulaRecord(new TestcaseRecordInputStream(FormulaRecord.sid, (short)29, formulaByte)); FormulaRecord record = new FormulaRecord(new TestcaseRecordInputStream(FormulaRecord.sid, (short)29, formulaByte));
assertEquals("Row", 0, record.getRow()); assertEquals("Row", 0, record.getRow());
assertEquals("Column", 0, record.getColumn()); assertEquals("Column", 0, record.getColumn());
@ -92,19 +82,18 @@ public class TestFormulaRecord
for (int i = 5; i < 13;i++) { for (int i = 5; i < 13;i++) {
assertEquals("FormulaByte NaN doesn't match", formulaByte[i], output[i+4]); assertEquals("FormulaByte NaN doesn't match", formulaByte[i], output[i+4]);
} }
}
/**
* Tests to see if the shared formula cells properly reserialize the expPtg
*
*/
public void testExpFormula() {
byte[] formulaByte = new byte[27];
}
/**
* Tests to see if the shared formula cells properly reserialize the expPtg
*
*/
public void testExpFormula() {
byte[] formulaByte = new byte[27];
for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0; for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0;
formulaByte[4] =(byte)0x0F; formulaByte[4] =(byte)0x0F;
formulaByte[14]=(byte)0x08; formulaByte[14]=(byte)0x08;
formulaByte[18]=(byte)0xE0; formulaByte[18]=(byte)0xE0;
formulaByte[19]=(byte)0xFD; formulaByte[19]=(byte)0xFD;
@ -115,19 +104,19 @@ public class TestFormulaRecord
assertEquals("Column", 0, record.getColumn()); assertEquals("Column", 0, record.getColumn());
byte[] output = record.serialize(); byte[] output = record.serialize();
assertEquals("Output size", 31, output.length); //includes sid+recordlength assertEquals("Output size", 31, output.length); //includes sid+recordlength
assertEquals("Offset 22", 1, output[26]); assertEquals("Offset 22", 1, output[26]);
} }
public void testWithConcat() throws Exception { public void testWithConcat() throws Exception {
// =CHOOSE(2,A2,A3,A4) // =CHOOSE(2,A2,A3,A4)
byte[] data = new byte[] { byte[] data = new byte[] {
6, 0, 68, 0, 6, 0, 68, 0,
1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57, 1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57,
64, 0, 0, 12, 0, 12, -4, 46, 0, 64, 0, 0, 12, 0, 12, -4, 46, 0,
30, 2, 0, // Int - 2 30, 2, 0, // Int - 2
25, 4, 3, 0, // Attr 25, 4, 3, 0, // Attr
8, 0, // Concat 8, 0, // Concat
17, 0, // Range 17, 0, // Range
26, 0, 35, 0, // Bit like an attr 26, 0, 35, 0, // Bit like an attr
36, 1, 0, 0, -64, // Ref - A2 36, 1, 0, 0, -64, // Ref - A2
25, 8, 21, 0, // Attr 25, 8, 21, 0, // Attr
@ -136,43 +125,35 @@ public class TestFormulaRecord
36, 3, 0, 0, -64, // Ref - A4 36, 3, 0, 0, -64, // Ref - A4
25, 8, 3, 0, // Attr 25, 8, 3, 0, // Attr
66, 4, 100, 0 // CHOOSE 66, 4, 100, 0 // CHOOSE
}; };
RecordInputStream inp = new RecordInputStream( RecordInputStream inp = new RecordInputStream(
new ByteArrayInputStream(data) new ByteArrayInputStream(data)
); );
inp.nextRecord(); inp.nextRecord();
FormulaRecord fr = new FormulaRecord(inp); FormulaRecord fr = new FormulaRecord(inp);
assertEquals(14, fr.getNumberOfExpressionTokens()); assertEquals(14, fr.getNumberOfExpressionTokens());
assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass()); assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass());
assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass()); assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass()); assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass());
assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass()); assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass()); assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass()); assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass()); assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass()); assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass());
assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass()); assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass());
FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13); FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13);
assertEquals("CHOOSE", choose.getName()); assertEquals("CHOOSE", choose.getName());
} }
public static void main(String [] ignored_args) {
public static void main(String [] ignored_args) junit.textui.TestRunner.run(TestFormulaRecord.class);
{ }
String filename = System.getProperty("HSSF.testdata.path");
System.out
.println("Testing org.apache.poi.hssf.record.FormulaRecord");
junit.textui.TestRunner.run(TestFormulaRecord.class);
}
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,7 +14,6 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
@ -34,20 +32,8 @@ import org.apache.poi.util.HexRead;
* @author Andrew C. Oliver (acoliver at apache dot org) * @author Andrew C. Oliver (acoliver at apache dot org)
* @author Csaba Nagy (ncsaba at yahoo dot com) * @author Csaba Nagy (ncsaba at yahoo dot com)
*/ */
public final class TestRecordFactory extends TestCase {
public class TestRecordFactory
extends TestCase
{
/**
* Creates new TestRecordFactory
* @param testCaseName
*/
public TestRecordFactory(String testCaseName)
{
super(testCaseName);
}
/** /**
* TEST NAME: Test Basic Record Construction <P> * TEST NAME: Test Basic Record Construction <P>
@ -57,13 +43,9 @@ public class TestRecordFactory
* FAILURE: The wrong records are creates or contain the wrong values <P> * FAILURE: The wrong records are creates or contain the wrong values <P>
* *
*/ */
public void testBasicRecordConstruction() {
public void testBasicRecordConstruction()
throws Exception
{
short recType = BOFRecord.sid; short recType = BOFRecord.sid;
byte[] data = new byte[] byte[] data = {
{
0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0 0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0
}; };
short size = 16; short size = 16;
@ -106,13 +88,9 @@ public class TestRecordFactory
* FAILURE: The wrong records are created or contain the wrong values <P> * FAILURE: The wrong records are created or contain the wrong values <P>
* *
*/ */
public void testSpecial() {
public void testSpecial()
throws Exception
{
short recType = RKRecord.sid; short recType = RKRecord.sid;
byte[] data = new byte[] byte[] data = {
{
0, 0, 0, 0, 21, 0, 0, 0, 0, 0 0, 0, 0, 0, 21, 0, 0, 0, 0, 0
}; };
short size = 10; short size = 10;
@ -138,10 +116,8 @@ public class TestRecordFactory
* FAILURE: The wrong records are created or contain the wrong values <P> * FAILURE: The wrong records are created or contain the wrong values <P>
* *
*/ */
public void testContinuedUnknownRecord() public void testContinuedUnknownRecord() {
{ byte[] data = {
byte[] data = new byte[]
{
0, -1, 0, 0, // an unknown record with 0 length 0, -1, 0, 0, // an unknown record with 0 length
0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data 0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data
0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data 0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data
@ -178,7 +154,7 @@ public class TestRecordFactory
*/ */
public void testMixedContinue() throws Exception { public void testMixedContinue() throws Exception {
/** /**
* Taken from a real file $HSSF.testdata.path/39512.xls. See Bug 39512 for details. * Taken from a real test sample file 39512.xls. See Bug 39512 for details.
*/ */
String dump = String dump =
//OBJ //OBJ
@ -228,10 +204,7 @@ public class TestRecordFactory
assertTrue(Arrays.equals(data, ser)); assertTrue(Arrays.equals(data, ser));
} }
public static void main(String [] ignored_args) public static void main(String [] ignored_args) {
{
System.out
.println("Testing org.apache.poi.hssf.record.TestRecordFactory");
junit.textui.TestRunner.run(TestRecordFactory.class); junit.textui.TestRunner.run(TestRecordFactory.class);
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,51 +14,47 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import org.apache.poi.util.HexRead; import java.io.IOException;
import org.apache.poi.util.IntMapper; import java.io.InputStream;
import org.apache.poi.hssf.record.TestcaseRecordInputStream;
import java.io.File;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.util.HexRead;
import org.apache.poi.util.IntMapper;
/** /**
* Exercise the SSTDeserializer class. * Exercise the SSTDeserializer class.
* *
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public class TestSSTDeserializer public final class TestSSTDeserializer extends TestCase {
extends TestCase
{
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
public TestSSTDeserializer( String s )
{
super( s );
}
protected void setUp() throws Exception
{
_test_file_path = System.getProperty( _test_file_path_property );
}
private byte[] joinArray(byte[] array1, byte[] array2) { private byte[] joinArray(byte[] array1, byte[] array2) {
byte[] bigArray = new byte[array1.length+array2.length]; byte[] bigArray = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, bigArray, 0, array1.length); System.arraycopy(array1, 0, bigArray, 0, array1.length);
System.arraycopy(array2, 0, bigArray, array1.length, array2.length); System.arraycopy(array2, 0, bigArray, array1.length, array2.length);
return bigArray; return bigArray;
}
private static byte[] readSampleHexData(String sampleFileName, String sectionName) {
InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
try {
return HexRead.readData(is, sectionName);
} catch (IOException e) {
throw new RuntimeException(e);
}
} }
public void testSpanRichTextToPlainText() public void testSpanRichTextToPlainText()
throws Exception throws Exception
{ {
byte[] header = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "header" ); byte[] header = readSampleHexData("richtextdata.txt", "header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "continue1" ); byte[] continueBytes = readSampleHexData("richtextdata.txt", "continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -74,8 +69,8 @@ public class TestSSTDeserializer
public void testContinuationWithNoOverlap() public void testContinuationWithNoOverlap()
throws Exception throws Exception
{ {
byte[] header = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "header" ); byte[] header = readSampleHexData("evencontinuation.txt", "header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "continue1" ); byte[] continueBytes = readSampleHexData("evencontinuation.txt", "continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -93,10 +88,10 @@ public class TestSSTDeserializer
public void testStringAcross2Continuations() public void testStringAcross2Continuations()
throws Exception throws Exception
{ {
byte[] header = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "header" ); byte[] header = readSampleHexData("stringacross2continuations.txt", "header" );
byte[] continue1 = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "continue1" ); byte[] continue1 = readSampleHexData("stringacross2continuations.txt", "continue1" );
continue1 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue1.length, continue1); continue1 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue1.length, continue1);
byte[] continue2 = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "continue2" ); byte[] continue2 = readSampleHexData("stringacross2continuations.txt", "continue2" );
continue2 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue2.length, continue2); continue2 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue2.length, continue2);
byte[] bytes = joinArray(header, continue1); byte[] bytes = joinArray(header, continue1);
@ -111,11 +106,9 @@ public class TestSSTDeserializer
assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" ); assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" );
} }
public void testExtendedStrings() public void testExtendedStrings() {
throws Exception byte[] header = readSampleHexData("extendedtextstrings.txt", "rich-header" );
{ byte[] continueBytes = readSampleHexData("extendedtextstrings.txt", "rich-continue1" );
byte[] header = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "rich-header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "rich-continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -126,8 +119,8 @@ public class TestSSTDeserializer
assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" );
header = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-header" ); header = readSampleHexData("extendedtextstrings.txt", "norich-header" );
continueBytes = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-continue1" ); continueBytes = readSampleHexData("extendedtextstrings.txt", "norich-continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -136,7 +129,5 @@ public class TestSSTDeserializer
deserializer.manufactureStrings( 1, in); deserializer.manufactureStrings( 1, in);
assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" );
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,54 +14,33 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import junit.framework.TestCase; import java.io.ByteArrayInputStream;
import org.apache.poi.hssf.usermodel.HSSFSheet; import java.io.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.IOException;
import org.apache.poi.util.HexRead;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.TempFile;
import java.io.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.LittleEndian;
/** /**
* @author Marc Johnson (mjohnson at apache dot org) * @author Marc Johnson (mjohnson at apache dot org)
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public class TestSSTRecord public final class TestSSTRecord extends TestCase {
extends TestCase
{
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
/**
* Creates new TestSSTRecord
*
* @param name
*/
public TestSSTRecord( String name )
{
super( name );
_test_file_path = System.getProperty( _test_file_path_property );
}
/** /**
* test processContinueRecord * test processContinueRecord
*
* @exception IOException
*/ */
public void testProcessContinueRecord() {
public void testProcessContinueRecord()
throws IOException
{
//jmh byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" ); //jmh byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" );
//jmh byte[] input = new byte[testdata.length - 4]; //jmh byte[] input = new byte[testdata.length - 4];
//jmh //jmh
@ -182,9 +160,7 @@ public class TestSSTRecord
* @exception IOException * @exception IOException
*/ */
public void testHugeStrings() public void testHugeStrings() {
throws IOException
{
SSTRecord record = new SSTRecord(); SSTRecord record = new SSTRecord();
byte[][] bstrings = byte[][] bstrings =
{ {
@ -265,12 +241,8 @@ public class TestSSTRecord
/** /**
* test SSTRecord boundary conditions * test SSTRecord boundary conditions
*
* @exception IOException
*/ */
public void testSSTRecordBug() public void testSSTRecordBug() {
throws IOException
{
// create an SSTRecord and write a certain pattern of strings // create an SSTRecord and write a certain pattern of strings
// to it ... then serialize it and verify the content // to it ... then serialize it and verify the content
SSTRecord record = new SSTRecord(); SSTRecord record = new SSTRecord();
@ -349,38 +321,6 @@ public class TestSSTRecord
} }
} }
/**
* test reader constructor
*
* @exception IOException
*/
public void testReaderConstructor()
throws IOException
{
/* JMH this test case data is crap because it does not contain a full record. Ie the last string
is missing a record
byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" );
// byte[] input = new byte[testdata.length - 4];
System.arraycopy( testdata, 4, input, 0, input.length );
SSTRecord record = new SSTRecord( new TestcaseRecordInputStream(LittleEndian.getShort( testdata, 0 ),
LittleEndian.getShort( testdata, 2 ),
input) );
assertEquals( 1464, record.getNumStrings() );
assertEquals( 688, record.getNumUniqueStrings() );
assertEquals( 492, record.countStrings() );
assertEquals( 1, record.getDeserializer().getContinuationExpectedChars() );
assertEquals( "Consolidated B-24J Liberator The Dragon & His Tai",
record.getDeserializer().getUnfinishedString() );
// assertEquals( 52, record.getDeserializer().getTotalLength() );
// assertEquals( 3, record.getDeserializer().getStringDataOffset() );
assertTrue( !record.getDeserializer().isWideChar() );
*/
}
/** /**
* test simple constructor * test simple constructor
*/ */
@ -413,9 +353,7 @@ public class TestSSTRecord
* @param ignored_args * @param ignored_args
*/ */
public static void main( String[] ignored_args ) public static void main( String[] ignored_args ) {
{
System.out.println( "Testing hssf.record.SSTRecord functionality" );
junit.textui.TestRunner.run( TestSSTRecord.class ); junit.textui.TestRunner.run( TestSSTRecord.class );
} }
@ -425,25 +363,16 @@ public class TestSSTRecord
public void testReadWriteDuplicatedRichText1() public void testReadWriteDuplicatedRichText1()
throws Exception throws Exception
{ {
File file = new File( _test_file_path + File.separator + "duprich1.xls" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich1.xls");
InputStream stream = new FileInputStream( file );
HSSFWorkbook wb = new HSSFWorkbook( stream );
stream.close();
HSSFSheet sheet = wb.getSheetAt( 1 ); HSSFSheet sheet = wb.getSheetAt( 1 );
assertEquals( "01/05 (Wed)", sheet.getRow( 0 ).getCell( (short) 8 ).getStringCellValue() ); assertEquals( "01/05 (Wed)", sheet.getRow( 0 ).getCell( (short) 8 ).getStringCellValue() );
assertEquals( "01/05 (Wed)", sheet.getRow( 1 ).getCell( (short) 8 ).getStringCellValue() ); assertEquals( "01/05 (Wed)", sheet.getRow( 1 ).getCell( (short) 8 ).getStringCellValue() );
file = TempFile.createTempFile( "testout", "xls" ); ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream outStream = new FileOutputStream( file ); wb.write( baos );
wb.write( outStream );
outStream.close();
file.delete();
// test the second file. // test the second file.
file = new File( _test_file_path + File.separator + "duprich2.xls" ); wb = HSSFTestDataSamples.openSampleWorkbook("duprich2.xls");
stream = new FileInputStream( file );
wb = new HSSFWorkbook( stream );
stream.close();
sheet = wb.getSheetAt( 0 ); sheet = wb.getSheetAt( 0 );
int row = 0; int row = 0;
assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() );
@ -453,12 +382,6 @@ public class TestSSTRecord
assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() );
assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() );
// file = new File("/tryme.xls"); wb.write( baos );
file = TempFile.createTempFile( "testout", ".xls" );
outStream = new FileOutputStream( file );
wb.write( outStream );
outStream.close();
file.delete();
} }
} }

View File

@ -14,39 +14,23 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; /**
*
*/
public final class TestUnicodeNameRecord extends TestCase {
public class TestUnicodeNameRecord extends TestCase { public void testReadBook() {
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
public TestUnicodeNameRecord()
{
super();
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "unicodeNameRecord.xls";
}
public void testReadBook() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(
new FileInputStream(_test_file_path)
);
// This bit used to crash // This bit used to crash
HSSFWorkbook book = new HSSFWorkbook(fs); HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("unicodeNameRecord.xls");
HSSFSheet sheet = book.getSheetAt(0); book.getSheetAt(0);
} }
} }

View File

@ -29,6 +29,7 @@ import java.util.zip.CRC32;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.BlankRecord; import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
@ -250,22 +251,14 @@ public class TestValueRecordsAggregate extends TestCase
* *
*/ */
public void testSpuriousSharedFormulaFlag() { public void testSpuriousSharedFormulaFlag() {
File dataDir = new File(System.getProperty("HSSF.testdata.path"));
File testFile = new File(dataDir, ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE);
long actualCRC = getFileCRC(testFile); long actualCRC = getFileCRC(HSSFTestDataSamples.openSampleFileStream(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE));
long expectedCRC = 2277445406L; long expectedCRC = 2277445406L;
if(actualCRC != expectedCRC) { if(actualCRC != expectedCRC) {
System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC); System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC);
throw failUnexpectedTestFileChange(); throw failUnexpectedTestFileChange();
} }
HSSFWorkbook wb; HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE);
try {
FileInputStream in = new FileInputStream(testFile);
wb = new HSSFWorkbook(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
HSSFSheet s = wb.getSheetAt(0); // Sheet1 HSSFSheet s = wb.getSheetAt(0); // Sheet1
@ -311,11 +304,10 @@ public class TestValueRecordsAggregate extends TestCase
/** /**
* gets a CRC checksum for the content of a file * gets a CRC checksum for the content of a file
*/ */
private static long getFileCRC(File f) { private static long getFileCRC(InputStream is) {
CRC32 crc = new CRC32(); CRC32 crc = new CRC32();
byte[] buf = new byte[2048]; byte[] buf = new byte[2048];
try { try {
InputStream is = new FileInputStream(f);
while(true) { while(true) {
int bytesRead = is.read(buf); int bytesRead = is.read(buf);
if(bytesRead < 1) { if(bytesRead < 1) {

View File

@ -25,6 +25,7 @@ import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
@ -36,40 +37,27 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* @author Daniel Noll (daniel at nuix dot com dot au) * @author Daniel Noll (daniel at nuix dot com dot au)
*/ */
public abstract class AbstractPtgTestCase extends TestCase { public abstract class AbstractPtgTestCase extends TestCase {
/** Directory containing the test data. */
private static String dataDir = System.getProperty("HSSF.testdata.path");
/** /**
* Loads a workbook from the given filename in the test data dir. * Loads a workbook from the given filename in the test data dir.
* *
* @param filename the filename. * @param sampleFileName the filename.
* @return the loaded workbook. * @return the loaded workbook.
* @throws IOException if an error occurs loading the workbook.
*/ */
protected static final HSSFWorkbook loadWorkbook(String filename) protected static final HSSFWorkbook loadWorkbook(String sampleFileName) {
throws IOException { return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
File file = new File(dataDir, filename);
InputStream stream = new BufferedInputStream(new FileInputStream(file));
// TODO - temp workaround to keep stdout quiet due to warning msg in POIFS
// When that warning msg is disabled, remove this wrapper and the close() call,
InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(stream);
try {
return new HSSFWorkbook(wrappedStream);
} finally {
stream.close();
}
} }
/** /**
* Creates a new Workbook and adds one sheet with the specified name * Creates a new Workbook and adds one sheet with the specified name
*/ */
protected static final Workbook createWorkbookWithSheet(String sheetName) { protected static final Workbook createWorkbookWithSheet(String sheetName) {
Workbook book = Workbook.createWorkbook(); Workbook book = Workbook.createWorkbook();
// this creates sheet if it doesn't exist // this creates sheet if it doesn't exist
book.checkExternSheet(0); book.checkExternSheet(0);
// TODO - this call alone does not create the sheet even though the javadoc says it does // TODO - this call alone does not create the sheet even though the javadoc says it does
book.setSheetName(0, sheetName); book.setSheetName(0, sheetName);
return book; return book;
} }
} }

View File

@ -17,11 +17,9 @@
package org.apache.poi.hssf.record.formula; package org.apache.poi.hssf.record.formula;
import java.io.FileInputStream;
import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/** /**
@ -37,15 +35,7 @@ public final class TestExternalFunctionFormulas extends TestCase {
* tests <tt>NameXPtg.toFormulaString(Workbook)</tt> and logic in Workbook below that * tests <tt>NameXPtg.toFormulaString(Workbook)</tt> and logic in Workbook below that
*/ */
public void testReadFormulaContainingExternalFunction() { public void testReadFormulaContainingExternalFunction() {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls");
+ "externalFunctionExample.xls";
HSSFWorkbook wb;
try {
FileInputStream fin = new FileInputStream(filePath);
wb = new HSSFWorkbook( fin );
} catch (IOException e) {
throw new RuntimeException(e);
}
String expectedFormula = "YEARFRAC(B1,C1)"; String expectedFormula = "YEARFRAC(B1,C1)";
HSSFSheet sht = wb.getSheetAt(0); HSSFSheet sht = wb.getSheetAt(0);

View File

@ -17,9 +17,6 @@
package org.apache.poi.hssf.record.formula.eval; package org.apache.poi.hssf.record.formula.eval;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -27,6 +24,7 @@ import java.io.InputStream;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFRow;
@ -43,49 +41,13 @@ import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.CellValue;
*/ */
public final class TestFormulaBugs extends TestCase { public final class TestFormulaBugs extends TestCase {
private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path";
/**
* Opens a sample file from the standard HSSF test data directory
*
* @return an open <tt>InputStream</tt> for the specified sample file
*/
private static InputStream openSampleFileStream(String sampleFileName) {
// TODO - move this method somewhere common
String dataDirName = System
.getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME);
if (dataDirName == null) {
throw new RuntimeException("Must set system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME
+ "' before running tests");
}
File dataDir = new File(dataDirName);
if (!dataDir.exists()) {
throw new RuntimeException("Data dir '" + dataDirName
+ "' specified by system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist");
}
File f = new File(dataDir, sampleFileName);
if (!f.exists()) {
throw new RuntimeException("Sample file '" + sampleFileName
+ "' not found in data dir '" + dataDirName + "'");
}
InputStream is;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
return is;
}
/** /**
* Bug 27349 - VLOOKUP with reference to another sheet.<p/> This test was * Bug 27349 - VLOOKUP with reference to another sheet.<p/> This test was
* added <em>long</em> after the relevant functionality was fixed. * added <em>long</em> after the relevant functionality was fixed.
*/ */
public void test27349() { public void test27349() {
// 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622 // 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622
InputStream is = openSampleFileStream("27349-vlookupAcrossSheets.xls"); InputStream is = HSSFTestDataSamples.openSampleFileStream("27349-vlookupAcrossSheets.xls");
HSSFWorkbook wb; HSSFWorkbook wb;
try { try {
// original bug may have thrown exception here, or output warning to // original bug may have thrown exception here, or output warning to

View File

@ -17,13 +17,13 @@
package org.apache.poi.hssf.record.formula.eval; package org.apache.poi.hssf.record.formula.eval;
import java.io.FileInputStream;
import java.io.PrintStream; import java.io.PrintStream;
import junit.framework.Assert; import junit.framework.Assert;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.formula.functions.TestMathX; import org.apache.poi.hssf.record.formula.functions.TestMathX;
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
@ -154,9 +154,7 @@ public final class TestFormulasFromSpreadsheet extends TestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
if (workbook == null) { if (workbook == null) {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME; workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME);
FileInputStream fin = new FileInputStream( filePath );
workbook = new HSSFWorkbook( fin );
sheet = workbook.getSheetAt( 0 ); sheet = workbook.getSheetAt( 0 );
} }
_functionFailureCount = 0; _functionFailureCount = 0;
@ -177,14 +175,14 @@ public final class TestFormulasFromSpreadsheet extends TestCase {
String successMsg = "There were " String successMsg = "There were "
+ _evaluationSuccessCount + " successful evaluation(s) and " + _evaluationSuccessCount + " successful evaluation(s) and "
+ _functionSuccessCount + " function(s) without error"; + _functionSuccessCount + " function(s) without error";
if(_functionFailureCount > 0) { if(_functionFailureCount > 0) {
String msg = _functionFailureCount + " function(s) failed in " String msg = _functionFailureCount + " function(s) failed in "
+ _evaluationFailureCount + " evaluation(s). " + successMsg; + _evaluationFailureCount + " evaluation(s). " + successMsg;
throw new AssertionFailedError(msg); throw new AssertionFailedError(msg);
} }
if(false) { // normally no output for successful tests if(false) { // normally no output for successful tests
System.out.println(getClass().getName() + ": " + successMsg); System.out.println(getClass().getName() + ": " + successMsg);
} }
} }
/** /**

View File

@ -23,6 +23,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.RecordFormatException; import org.apache.poi.hssf.record.RecordFormatException;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -45,14 +46,7 @@ public final class TestReadMissingBuiltInFuncs extends TestCase {
private static HSSFSheet getSheet() { private static HSSFSheet getSheet() {
if (_sheet == null) { if (_sheet == null) {
String cwd = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_SPREADSHEET_FILE_NAME);
HSSFWorkbook wb;
try {
InputStream is = new FileInputStream(new File(cwd, SAMPLE_SPREADSHEET_FILE_NAME));
wb = new HSSFWorkbook(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
_sheet = wb.getSheetAt(0); _sheet = wb.getSheetAt(0);
} }
return _sheet; return _sheet;

View File

@ -26,6 +26,7 @@ import junit.framework.Assert;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.formula.eval.ErrorEval; import org.apache.poi.hssf.record.formula.eval.ErrorEval;
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
@ -66,17 +67,17 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
public final static String README_SHEET_NAME = "Read Me"; public final static String README_SHEET_NAME = "Read Me";
/** Row (zero-based) in each sheet where the evaluation cases start. */ /** Row (zero-based) in each sheet where the evaluation cases start. */
public static final int START_TEST_CASES_ROW_INDEX = 4; // Row '5' public static final int START_TEST_CASES_ROW_INDEX = 4; // Row '5'
/** Index of the column that contains the function names */ /** Index of the column that contains the function names */
public static final short COLUMN_INDEX_MARKER = 0; // Column 'A' public static final short COLUMN_INDEX_MARKER = 0; // Column 'A'
public static final short COLUMN_INDEX_EVALUATION = 1; // Column 'B' public static final short COLUMN_INDEX_EVALUATION = 1; // Column 'B'
public static final short COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C' public static final short COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C'
public static final short COLUMN_ROW_COMMENT = 3; // Column 'D' public static final short COLUMN_ROW_COMMENT = 3; // Column 'D'
/** Used to indicate when there are no more test cases on the current sheet */ /** Used to indicate when there are no more test cases on the current sheet */
public static final String TEST_CASES_END_MARKER = "<end>"; public static final String TEST_CASES_END_MARKER = "<end>";
/** Used to indicate that the test on the current row should be ignored */ /** Used to indicate that the test on the current row should be ignored */
public static final String SKIP_CURRENT_TEST_CASE_MARKER = "<skip>"; public static final String SKIP_CURRENT_TEST_CASE_MARKER = "<skip>";
} }
@ -90,8 +91,8 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
private static void confirmExpectedResult(String msg, HSSFCell expected, HSSFFormulaEvaluator.CellValue actual) { private static void confirmExpectedResult(String msg, HSSFCell expected, HSSFFormulaEvaluator.CellValue actual) {
if (expected == null) { if (expected == null) {
throw new AssertionFailedError(msg + " - Bad setup data expected value is null"); throw new AssertionFailedError(msg + " - Bad setup data expected value is null");
} }
if(actual == null) { if(actual == null) {
@ -108,21 +109,21 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
throw wrongTypeError(msg, expected, actual); throw wrongTypeError(msg, expected, actual);
} }
switch (expected.getCellType()) { switch (expected.getCellType()) {
case HSSFCell.CELL_TYPE_BOOLEAN: case HSSFCell.CELL_TYPE_BOOLEAN:
assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue()); assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue());
break; break;
case HSSFCell.CELL_TYPE_FORMULA: // will never be used, since we will call method after formula evaluation case HSSFCell.CELL_TYPE_FORMULA: // will never be used, since we will call method after formula evaluation
throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg); throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg);
case HSSFCell.CELL_TYPE_NUMERIC: case HSSFCell.CELL_TYPE_NUMERIC:
assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0); assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0);
break; break;
case HSSFCell.CELL_TYPE_STRING: case HSSFCell.CELL_TYPE_STRING:
assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString()); assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString());
break; break;
} }
} }
private static AssertionFailedError wrongTypeError(String msgPrefix, HSSFCell expectedCell, CellValue actualValue) { private static AssertionFailedError wrongTypeError(String msgPrefix, HSSFCell expectedCell, CellValue actualValue) {
@ -178,55 +179,48 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
_sheetFailureCount = 0; _sheetFailureCount = 0;
_sheetSuccessCount = 0; _sheetSuccessCount = 0;
_evaluationFailureCount = 0; _evaluationFailureCount = 0;
_evaluationSuccessCount = 0; _evaluationSuccessCount = 0;
} }
public void testFunctionsFromTestSpreadsheet() { public void testFunctionsFromTestSpreadsheet() {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME; HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME);
HSSFWorkbook workbook;
try {
FileInputStream fin = new FileInputStream( filePath );
workbook = new HSSFWorkbook( fin );
} catch (IOException e) {
throw new RuntimeException(e);
}
confirmReadMeSheet(workbook); confirmReadMeSheet(workbook);
int nSheets = workbook.getNumberOfSheets(); int nSheets = workbook.getNumberOfSheets();
for(int i=1; i< nSheets; i++) { for(int i=1; i< nSheets; i++) {
int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i)); int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i));
switch(sheetResult) { switch(sheetResult) {
case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break; case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break;
case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break; case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break;
} }
} }
// confirm results // confirm results
String successMsg = "There were " String successMsg = "There were "
+ _sheetSuccessCount + " successful sheets(s) and " + _sheetSuccessCount + " successful sheets(s) and "
+ _evaluationSuccessCount + " function(s) without error"; + _evaluationSuccessCount + " function(s) without error";
if(_sheetFailureCount > 0) { if(_sheetFailureCount > 0) {
String msg = _sheetFailureCount + " sheets(s) failed with " String msg = _sheetFailureCount + " sheets(s) failed with "
+ _evaluationFailureCount + " evaluation(s). " + successMsg; + _evaluationFailureCount + " evaluation(s). " + successMsg;
throw new AssertionFailedError(msg); throw new AssertionFailedError(msg);
} }
if(false) { // normally no output for successful tests if(false) { // normally no output for successful tests
System.out.println(getClass().getName() + ": " + successMsg); System.out.println(getClass().getName() + ": " + successMsg);
} }
} }
private int processTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName) { private int processTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName) {
HSSFSheet sheet = workbook.getSheetAt(sheetIndex); HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, workbook); HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, workbook);
int maxRows = sheet.getLastRowNum()+1; int maxRows = sheet.getLastRowNum()+1;
int result = Result.NO_EVALUATIONS_FOUND; // so far int result = Result.NO_EVALUATIONS_FOUND; // so far
String currentGroupComment = null; String currentGroupComment = null;
for(int rowIndex=SS.START_TEST_CASES_ROW_INDEX; rowIndex<maxRows; rowIndex++) { for(int rowIndex=SS.START_TEST_CASES_ROW_INDEX; rowIndex<maxRows; rowIndex++) {
HSSFRow r = sheet.getRow(rowIndex); HSSFRow r = sheet.getRow(rowIndex);
String newMarkerValue = getMarkerColumnValue(r); String newMarkerValue = getMarkerColumnValue(r);
if(r == null) { if(r == null) {
continue; continue;
@ -242,7 +236,7 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
if(newMarkerValue != null) { if(newMarkerValue != null) {
currentGroupComment = newMarkerValue; currentGroupComment = newMarkerValue;
} }
HSSFCell c = r.getCell(SS.COLUMN_INDEX_EVALUATION); HSSFCell c = r.getCell(SS.COLUMN_INDEX_EVALUATION);
if (c == null || c.getCellType() != HSSFCell.CELL_TYPE_FORMULA) { if (c == null || c.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {
continue; continue;
} }
@ -303,11 +297,11 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
} }
/** /**
* Asserts that the 'read me' comment page exists, and has this class' name in one of the * Asserts that the 'read me' comment page exists, and has this class' name in one of the
* cells. This back-link is to make it easy to find this class if a reader encounters the * cells. This back-link is to make it easy to find this class if a reader encounters the
* spreadsheet first. * spreadsheet first.
*/ */
private void confirmReadMeSheet(HSSFWorkbook workbook) { private void confirmReadMeSheet(HSSFWorkbook workbook) {
String firstSheetName = workbook.getSheetName(0); String firstSheetName = workbook.getSheetName(0);
if(!firstSheetName.equalsIgnoreCase(SS.README_SHEET_NAME)) { if(!firstSheetName.equalsIgnoreCase(SS.README_SHEET_NAME)) {
throw new RuntimeException("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'"); throw new RuntimeException("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'");
@ -319,9 +313,9 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
} }
/** /**
* Useful to keep output concise when expecting many failures to be reported by this test case * Useful to keep output concise when expecting many failures to be reported by this test case
*/ */
private static void printShortStackTrace(PrintStream ps, Throwable e) { private static void printShortStackTrace(PrintStream ps, Throwable e) {
StackTraceElement[] stes = e.getStackTrace(); StackTraceElement[] stes = e.getStackTrace();
@ -363,7 +357,7 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
/** /**
* @return <code>null</code> if cell is missing, empty or blank * @return <code>null</code> if cell is missing, empty or blank
*/ */
private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) { private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) {
if(r == null) { if(r == null) {
return null; return null;

View File

@ -14,42 +14,35 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.CellValue; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.CellValue;
import org.apache.poi.hssf.util.CellReference; import org.apache.poi.hssf.util.CellReference;
/**
*
*/
public final class TestBug42464 extends TestCase { public final class TestBug42464 extends TestCase {
String dirname;
protected void setUp() throws Exception {
super.setUp();
dirname = System.getProperty("HSSF.testdata.path");
}
public void testOKFile() throws Exception { public void testOKFile() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook( HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-ok.xls");
new FileInputStream(new File(dirname,"42464-ExpPtg-ok.xls"))
);
process(wb); process(wb);
} }
public void testExpSharedBadFile() throws Exception { public void testExpSharedBadFile() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook( HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls");
new FileInputStream(new File(dirname,"42464-ExpPtg-bad.xls"))
);
process(wb); process(wb);
} }
protected void process(HSSFWorkbook wb) { private static void process(HSSFWorkbook wb) {
for(int i=0; i<wb.getNumberOfSheets(); i++) { for(int i=0; i<wb.getNumberOfSheets(); i++) {
HSSFSheet s = wb.getSheetAt(i); HSSFSheet s = wb.getSheetAt(i);
HSSFFormulaEvaluator eval = HSSFFormulaEvaluator eval =
@ -64,7 +57,7 @@ public final class TestBug42464 extends TestCase {
} }
} }
protected void process(HSSFRow row, HSSFFormulaEvaluator eval) { private static void process(HSSFRow row, HSSFFormulaEvaluator eval) {
Iterator it = row.cellIterator(); Iterator it = row.cellIterator();
while(it.hasNext()) { while(it.hasNext()) {
HSSFCell cell = (HSSFCell)it.next(); HSSFCell cell = (HSSFCell)it.next();

File diff suppressed because it is too large Load Diff

View File

@ -14,31 +14,31 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.hssf.record.formula.AreaPtg;
import org.apache.poi.hssf.record.formula.FuncVarPtg;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.hssf.record.formula.AreaPtg;
import org.apache.poi.hssf.record.formula.FuncVarPtg;
/**
*
*/
public final class TestFormulaEvaluatorBugs extends TestCase { public final class TestFormulaEvaluatorBugs extends TestCase {
private String dirName;
private String tmpDirName; private String tmpDirName;
protected void setUp() throws Exception { protected void setUp() {
super.setUp();
dirName = System.getProperty("HSSF.testdata.path");
tmpDirName = System.getProperty("java.io.tmpdir"); tmpDirName = System.getProperty("java.io.tmpdir");
} }
/** /**
* An odd problem with evaluateFormulaCell giving the * An odd problem with evaluateFormulaCell giving the
* right values when file is opened, but changes * right values when file is opened, but changes
@ -51,39 +51,39 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
public void test44636() throws Exception { public void test44636() throws Exception {
// Open the existing file, tweak one value and // Open the existing file, tweak one value and
// re-calculate // re-calculate
FileInputStream in = new FileInputStream(new File(dirName,"44636.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44636.xls");
HSSFSheet sheet = wb.getSheetAt (0); HSSFSheet sheet = wb.getSheetAt (0);
HSSFRow row = sheet.getRow (0); HSSFRow row = sheet.getRow (0);
row.getCell((short)0).setCellValue(4.2); row.getCell((short)0).setCellValue(4.2);
row.getCell((short)2).setCellValue(25); row.getCell((short)2).setCellValue(25);
HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
assertEquals(4.2*25, row.getCell((short)3).getNumericCellValue(), 0.0001); assertEquals(4.2*25, row.getCell((short)3).getNumericCellValue(), 0.0001);
// Save // Save
File existing = new File(tmpDirName,"44636-existing.xls"); File existing = new File(tmpDirName,"44636-existing.xls");
FileOutputStream out = new FileOutputStream(existing); FileOutputStream out = new FileOutputStream(existing);
wb.write(out); wb.write(out);
out.close(); out.close();
System.err.println("Existing file for bug #44636 written to " + existing.toString()); System.err.println("Existing file for bug #44636 written to " + existing.toString());
// Now, do a new file from scratch // Now, do a new file from scratch
wb = new HSSFWorkbook(); wb = new HSSFWorkbook();
sheet = wb.createSheet(); sheet = wb.createSheet();
row = sheet.createRow(0); row = sheet.createRow(0);
row.createCell((short)0).setCellValue(1.2); row.createCell((short)0).setCellValue(1.2);
row.createCell((short)1).setCellValue(4.2); row.createCell((short)1).setCellValue(4.2);
row = sheet.createRow(1); row = sheet.createRow(1);
row.createCell((short)0).setCellFormula("SUM(A1:B1)"); row.createCell((short)0).setCellFormula("SUM(A1:B1)");
HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
assertEquals(5.4, row.getCell((short)0).getNumericCellValue(), 0.0001); assertEquals(5.4, row.getCell((short)0).getNumericCellValue(), 0.0001);
// Save // Save
File scratch = new File(tmpDirName,"44636-scratch.xls"); File scratch = new File(tmpDirName,"44636-scratch.xls");
out = new FileOutputStream(scratch); out = new FileOutputStream(scratch);
@ -99,72 +99,71 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public void test44297() throws IOException { public void test44297() {
FileInputStream in = new FileInputStream(new File(dirName, "44297.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
HSSFRow row; HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44297.xls");
HSSFCell cell;
HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row;
HSSFCell cell;
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); HSSFSheet sheet = wb.getSheetAt(0);
row = (HSSFRow)sheet.getRow(0); HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb);
cell = row.getCell((short)0);
assertEquals("31+46", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(77, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(1); row = sheet.getRow(0);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("30+53", cell.getCellFormula()); assertEquals("31+46", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(83, eva.evaluate(cell).getNumberValue(), 0); assertEquals(77, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(2); row = sheet.getRow(1);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("SUM(A1:A2)", cell.getCellFormula()); assertEquals("30+53", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(160, eva.evaluate(cell).getNumberValue(), 0); assertEquals(83, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(4); row = sheet.getRow(2);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("32767+32768", cell.getCellFormula()); assertEquals("SUM(A1:A2)", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0); assertEquals(160, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(7); row = sheet.getRow(4);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("32744+42333", cell.getCellFormula()); assertEquals("32767+32768", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0); assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(8); row = sheet.getRow(7);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("327680.0/32768", cell.getCellFormula()); assertEquals("32744+42333", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(10, eva.evaluate(cell).getNumberValue(), 0); assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(9); row = sheet.getRow(8);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("32767+32769", cell.getCellFormula()); assertEquals("327680.0/32768", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0); assertEquals(10, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(10); row = sheet.getRow(9);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("35000+36000", cell.getCellFormula()); assertEquals("32767+32769", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0); assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(11); row = sheet.getRow(10);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("-1000000.0-3000000.0", cell.getCellFormula()); assertEquals("35000+36000", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0);
}
row = sheet.getRow(11);
cell = row.getCell((short)0);
assertEquals("-1000000.0-3000000.0", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0);
}
/** /**
* Bug 44410: SUM(C:C) is valid in excel, and means a sum * Bug 44410: SUM(C:C) is valid in excel, and means a sum
@ -172,86 +171,85 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
* *
* @author Nick Burch * @author Nick Burch
*/ */
public void test44410() throws IOException { public void test44410() {
FileInputStream in = new FileInputStream(new File(dirName, "SingleLetterRanges.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
HSSFSheet sheet = wb.getSheetAt(0); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SingleLetterRanges.xls");
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); HSSFSheet sheet = wb.getSheetAt(0);
// =index(C:C,2,1) -> 2 HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb);
HSSFRow rowIDX = (HSSFRow)sheet.getRow(3);
// =sum(C:C) -> 6
HSSFRow rowSUM = (HSSFRow)sheet.getRow(4);
// =sum(C:D) -> 66
HSSFRow rowSUM2D = (HSSFRow)sheet.getRow(5);
// Test the sum
HSSFCell cellSUM = rowSUM.getCell((short)0);
FormulaRecordAggregate frec =
(FormulaRecordAggregate)cellSUM.getCellValueRecord();
List ops = frec.getFormulaRecord().getParsedExpression();
assertEquals(2, ops.size());
assertEquals(AreaPtg.class, ops.get(0).getClass());
assertEquals(FuncVarPtg.class, ops.get(1).getClass());
// Actually stored as C1 to C65536 // =index(C:C,2,1) -> 2
// (last row is -1 === 65535) HSSFRow rowIDX = sheet.getRow(3);
AreaPtg ptg = (AreaPtg)ops.get(0); // =sum(C:C) -> 6
assertEquals(2, ptg.getFirstColumn()); HSSFRow rowSUM = sheet.getRow(4);
assertEquals(2, ptg.getLastColumn()); // =sum(C:D) -> 66
assertEquals(0, ptg.getFirstRow()); HSSFRow rowSUM2D = sheet.getRow(5);
assertEquals(65535, ptg.getLastRow());
assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook())); // Test the sum
HSSFCell cellSUM = rowSUM.getCell((short)0);
// Will show as C:C, but won't know how many
// rows it covers as we don't have the sheet FormulaRecordAggregate frec =
// to hand when turning the Ptgs into a string (FormulaRecordAggregate)cellSUM.getCellValueRecord();
assertEquals("SUM(C:C)", cellSUM.getCellFormula()); List ops = frec.getFormulaRecord().getParsedExpression();
eva.setCurrentRow(rowSUM); assertEquals(2, ops.size());
assertEquals(AreaPtg.class, ops.get(0).getClass());
// But the evaluator knows the sheet, so it assertEquals(FuncVarPtg.class, ops.get(1).getClass());
// can do it properly
assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0); // Actually stored as C1 to C65536
// (last row is -1 === 65535)
AreaPtg ptg = (AreaPtg)ops.get(0);
// Test the index assertEquals(2, ptg.getFirstColumn());
// Again, the formula string will be right but assertEquals(2, ptg.getLastColumn());
// lacking row count, evaluated will be right assertEquals(0, ptg.getFirstRow());
HSSFCell cellIDX = rowIDX.getCell((short)0); assertEquals(65535, ptg.getLastRow());
assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula()); assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook()));
eva.setCurrentRow(rowIDX);
assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0); // Will show as C:C, but won't know how many
// rows it covers as we don't have the sheet
// Across two colums // to hand when turning the Ptgs into a string
HSSFCell cellSUM2D = rowSUM2D.getCell((short)0); assertEquals("SUM(C:C)", cellSUM.getCellFormula());
assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); eva.setCurrentRow(rowSUM);
eva.setCurrentRow(rowSUM2D);
assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); // But the evaluator knows the sheet, so it
} // can do it properly
assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0);
// Test the index
// Again, the formula string will be right but
// lacking row count, evaluated will be right
HSSFCell cellIDX = rowIDX.getCell((short)0);
assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula());
eva.setCurrentRow(rowIDX);
assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0);
// Across two colums
HSSFCell cellSUM2D = rowSUM2D.getCell((short)0);
assertEquals("SUM(C:D)", cellSUM2D.getCellFormula());
eva.setCurrentRow(rowSUM2D);
assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0);
}
/** /**
* Tests that we can evaluate boolean cells properly * Tests that we can evaluate boolean cells properly
*/ */
public void testEvaluateBooleanInCell_bug44508() { public void testEvaluateBooleanInCell_bug44508() {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
wb.setSheetName(0, "Sheet1"); wb.setSheetName(0, "Sheet1");
HSSFRow row = sheet.createRow(0); HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short)0); HSSFCell cell = row.createCell((short)0);
cell.setCellFormula("1=1"); cell.setCellFormula("1=1");
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb); HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb);
fe.setCurrentRow(row); fe.setCurrentRow(row);
try { try {
fe.evaluateInCell(cell); fe.evaluateInCell(cell);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
fail("Identified bug 44508"); fail("Identified bug 44508");
} }
assertEquals(true, cell.getBooleanCellValue()); assertEquals(true, cell.getBooleanCellValue());
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -17,18 +17,21 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
/** /**
@ -40,12 +43,26 @@ import org.apache.poi.util.TempFile;
*/ */
public final class TestHSSFCell extends TestCase { public final class TestHSSFCell extends TestCase {
private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
private static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
original.write(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new HSSFWorkbook(bais);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** /**
* test that Boolean and Error types (BoolErrRecord) are supported properly. * test that Boolean and Error types (BoolErrRecord) are supported properly.
*/ */
public void testBoolErr() public void testBoolErr()
throws java.io.IOException { throws java.io.IOException {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testBoolErr",".xls"); File file = TempFile.createTempFile("testBoolErr",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
@ -102,33 +119,24 @@ public final class TestHSSFCell extends TestCase {
public void testDateWindowingRead() throws Exception { public void testDateWindowingRead() throws Exception {
GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000
Date date = cal.getTime(); Date date = cal.getTime();
String path = System.getProperty("HSSF.testdata.path");
// first check a file with 1900 Date Windowing // first check a file with 1900 Date Windowing
String filename = path + "/1900DateWindowing.xls"; HSSFWorkbook workbook = openSample("1900DateWindowing.xls");
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
assertEquals("Date from file using 1900 Date Windowing", assertEquals("Date from file using 1900 Date Windowing",
date.getTime(), date.getTime(),
sheet.getRow(0).getCell((short)0) sheet.getRow(0).getCell((short)0)
.getDateCellValue().getTime()); .getDateCellValue().getTime());
stream.close();
// now check a file with 1904 Date Windowing // now check a file with 1904 Date Windowing
filename = path + "/1904DateWindowing.xls"; workbook = openSample("1904DateWindowing.xls");
stream = new FileInputStream(filename);
fs = new POIFSFileSystem(stream);
workbook = new HSSFWorkbook(fs);
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
assertEquals("Date from file using 1904 Date Windowing", assertEquals("Date from file using 1904 Date Windowing",
date.getTime(), date.getTime(),
sheet.getRow(0).getCell((short)0) sheet.getRow(0).getCell((short)0)
.getDateCellValue().getTime()); .getDateCellValue().getTime());
stream.close();
} }
/** /**
@ -140,55 +148,39 @@ public final class TestHSSFCell extends TestCase {
public void testDateWindowingWrite() throws Exception { public void testDateWindowingWrite() throws Exception {
GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000
Date date = cal.getTime(); Date date = cal.getTime();
String path = System.getProperty("HSSF.testdata.path");
// first check a file with 1900 Date Windowing // first check a file with 1900 Date Windowing
String filename = path + "/1900DateWindowing.xls"; HSSFWorkbook wb;
writeCell(filename, 0, (short) 1, date); wb = openSample("1900DateWindowing.xls");
setCell(wb, 0, 1, date);
wb = writeOutAndReadBack(wb);
assertEquals("Date from file using 1900 Date Windowing", assertEquals("Date from file using 1900 Date Windowing",
date.getTime(), date.getTime(),
readCell(filename, 0, (short) 1).getTime()); readCell(wb, 0, 1).getTime());
// now check a file with 1904 Date Windowing // now check a file with 1904 Date Windowing
filename = path + "/1904DateWindowing.xls"; wb = openSample("1904DateWindowing.xls");
writeCell(filename, 0, (short) 1, date); setCell(wb, 0, 1, date);
wb = writeOutAndReadBack(wb);
assertEquals("Date from file using 1900 Date Windowing", assertEquals("Date from file using 1900 Date Windowing",
date.getTime(), date.getTime(),
readCell(filename, 0, (short) 1).getTime()); readCell(wb, 0, 1).getTime());
} }
/** private static void setCell(HSSFWorkbook workbook, int rowIdx, int colIdx, Date date) {
* Sets cell value and writes file.
*/
private void writeCell(String filename,
int rowIdx, short colIdx, Date date) throws Exception {
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(rowIdx); HSSFRow row = sheet.getRow(rowIdx);
HSSFCell cell = row.getCell(colIdx); HSSFCell cell = row.getCell(colIdx);
if (cell == null) { if (cell == null) {
cell = row.createCell(colIdx); cell = row.createCell((short)colIdx);
} }
cell.setCellValue(date); cell.setCellValue(date);
// Write the file
stream.close();
FileOutputStream oStream = new FileOutputStream(filename);
workbook.write(oStream);
oStream.close();
} }
/** private static Date readCell(HSSFWorkbook workbook, int rowIdx, int colIdx) {
* Reads cell value from file.
*/
private Date readCell(String filename,
int rowIdx, short colIdx) throws Exception {
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(rowIdx); HSSFRow row = sheet.getRow(rowIdx);
HSSFCell cell = row.getCell(colIdx); HSSFCell cell = row.getCell(colIdx);
@ -201,12 +193,7 @@ public final class TestHSSFCell extends TestCase {
public void testActiveCell() throws Exception public void testActiveCell() throws Exception
{ {
//read in sample //read in sample
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook book = openSample("Simple.xls");
File sample = new File(dir + "/Simple.xls");
assertTrue("Simple.xls exists and is readable", sample.canRead());
FileInputStream fis = new FileInputStream(sample);
HSSFWorkbook book = new HSSFWorkbook(fis);
fis.close();
//check initial position //check initial position
HSSFSheet umSheet = book.getSheetAt(0); HSSFSheet umSheet = book.getSheetAt(0);
@ -225,14 +212,8 @@ public final class TestHSSFCell extends TestCase {
3, s.getActiveCellRow()); 3, s.getActiveCellRow());
//write book to temp file; read and verify that position is serialized //write book to temp file; read and verify that position is serialized
File temp = TempFile.createTempFile("testActiveCell", ".xls"); book = writeOutAndReadBack(book);
FileOutputStream fos = new FileOutputStream(temp);
book.write(fos);
fos.close();
fis = new FileInputStream(temp);
book = new HSSFWorkbook(fis);
fis.close();
umSheet = book.getSheetAt(0); umSheet = book.getSheetAt(0);
s = umSheet.getSheet(); s = umSheet.getSheet();
@ -245,12 +226,8 @@ public final class TestHSSFCell extends TestCase {
/** /**
* test that Cell Styles being applied to formulas remain intact * test that Cell Styles being applied to formulas remain intact
*/ */
public void testFormulaStyle() public void testFormulaStyle() {
throws java.io.IOException {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testFormulaStyle",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("testSheet1"); HSSFSheet s = wb.createSheet("testSheet1");
HSSFRow r = null; HSSFRow r = null;
@ -258,7 +235,7 @@ public final class TestHSSFCell extends TestCase {
HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs = wb.createCellStyle();
HSSFFont f = wb.createFont(); HSSFFont f = wb.createFont();
f.setFontHeightInPoints((short) 20); f.setFontHeightInPoints((short) 20);
f.setColor((short) HSSFColor.RED.index); f.setColor(HSSFColor.RED.index);
f.setBoldweight(f.BOLDWEIGHT_BOLD); f.setBoldweight(f.BOLDWEIGHT_BOLD);
f.setFontName("Arial Unicode MS"); f.setFontName("Arial Unicode MS");
cs.setFillBackgroundColor((short)3); cs.setFillBackgroundColor((short)3);
@ -273,13 +250,7 @@ public final class TestHSSFCell extends TestCase {
c.setCellStyle(cs); c.setCellStyle(cs);
c.setCellFormula("2*3"); c.setCellFormula("2*3");
wb.write(out); wb = writeOutAndReadBack(wb);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0); s = wb.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell((short)0); c = r.getCell((short)0);
@ -293,17 +264,14 @@ public final class TestHSSFCell extends TestCase {
assertTrue("Left Border", (cs.getBorderLeft() == (short)1)); assertTrue("Left Border", (cs.getBorderLeft() == (short)1));
assertTrue("Right Border", (cs.getBorderRight() == (short)1)); assertTrue("Right Border", (cs.getBorderRight() == (short)1));
assertTrue("Bottom Border", (cs.getBorderBottom() == (short)1)); assertTrue("Bottom Border", (cs.getBorderBottom() == (short)1));
in.close();
} }
/** /**
* Test reading hyperlinks * Test reading hyperlinks
*/ */
public void testWithHyperlink() throws Exception { public void testWithHyperlink() {
String dir = System.getProperty("HSSF.testdata.path");
File f = new File(dir, "WithHyperlink.xls"); HSSFWorkbook wb = openSample("WithHyperlink.xls");
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f));
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
HSSFCell cell = sheet.getRow(4).getCell((short)0); HSSFCell cell = sheet.getRow(4).getCell((short)0);
@ -320,10 +288,9 @@ public final class TestHSSFCell extends TestCase {
* Test reading hyperlinks * Test reading hyperlinks
*/ */
public void testWithTwoHyperlinks() throws Exception { public void testWithTwoHyperlinks() throws Exception {
String dir = System.getProperty("HSSF.testdata.path");
File f = new File(dir, "WithTwoHyperLinks.xls"); HSSFWorkbook wb = openSample("WithTwoHyperLinks.xls");
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f));
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
HSSFCell cell1 = sheet.getRow(4).getCell((short)0); HSSFCell cell1 = sheet.getRow(4).getCell((short)0);
@ -346,38 +313,38 @@ public final class TestHSSFCell extends TestCase {
/*tests the toString() method of HSSFCell*/ /*tests the toString() method of HSSFCell*/
public void testToString() throws Exception { public void testToString() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("Sheet1"); HSSFSheet s = wb.createSheet("Sheet1");
HSSFRow r = s.createRow(0); HSSFRow r = s.createRow(0);
HSSFCell c; HSSFCell c;
c=r.createCell((short) 0); c.setCellValue(true); c=r.createCell((short) 0); c.setCellValue(true);
assertEquals("Boolean", "TRUE", c.toString()); assertEquals("Boolean", "TRUE", c.toString());
c=r.createCell((short) 1); c.setCellValue(1.5); c=r.createCell((short) 1); c.setCellValue(1.5);
assertEquals("Numeric", "1.5", c.toString()); assertEquals("Numeric", "1.5", c.toString());
c=r.createCell((short)(2)); c.setCellValue("Astring"); c=r.createCell((short)(2)); c.setCellValue(new HSSFRichTextString("Astring"));
assertEquals("String", "Astring", c.toString()); assertEquals("String", "Astring", c.toString());
c=r.createCell((short) 3); c.setCellErrorValue((byte) 7); c=r.createCell((short) 3); c.setCellErrorValue((byte) 7);
assertEquals("Error", "#ERR7", c.toString()); assertEquals("Error", "#ERR7", c.toString());
c=r.createCell((short)4); c.setCellFormula("A1+B1"); c=r.createCell((short)4); c.setCellFormula("A1+B1");
assertEquals("Formula", "A1+B1", c.toString()); assertEquals("Formula", "A1+B1", c.toString());
//Write out the file, read it in, and then check cell values //Write out the file, read it in, and then check cell values
File f = File.createTempFile("testCellToString",".xls"); File f = File.createTempFile("testCellToString",".xls");
wb.write(new FileOutputStream(f)); wb.write(new FileOutputStream(f));
wb = new HSSFWorkbook(new FileInputStream(f)); wb = new HSSFWorkbook(new FileInputStream(f));
assertTrue("File exists and can be read", f.canRead()); assertTrue("File exists and can be read", f.canRead());
s = wb.getSheetAt(0);r=s.getRow(0); s = wb.getSheetAt(0);r=s.getRow(0);
c=r.getCell((short) 0); c=r.getCell((short) 0);
assertEquals("Boolean", "TRUE", c.toString()); assertEquals("Boolean", "TRUE", c.toString());
c=r.getCell((short) 1); c=r.getCell((short) 1);
assertEquals("Numeric", "1.5", c.toString()); assertEquals("Numeric", "1.5", c.toString());
c=r.getCell((short)(2)); c=r.getCell((short)(2));
assertEquals("String", "Astring", c.toString()); assertEquals("String", "Astring", c.toString());
c=r.getCell((short) 3); c=r.getCell((short) 3);
assertEquals("Error", "#ERR7", c.toString()); assertEquals("Error", "#ERR7", c.toString());
c=r.getCell((short)4); c=r.getCell((short)4);
assertEquals("Formula", "A1+B1", c.toString()); assertEquals("Formula", "A1+B1", c.toString());
} }
public void testSetStringInFormulaCell_bug44606() { public void testSetStringInFormulaCell_bug44606() {
@ -392,10 +359,7 @@ public final class TestHSSFCell extends TestCase {
} }
public static void main(String [] args) { public static void main(String [] args) {
System.out
.println("Testing org.apache.poi.hssf.usermodel.TestHSSFCell");
junit.textui.TestRunner.run(TestHSSFCell.class); junit.textui.TestRunner.run(TestHSSFCell.class);
} }
} }

View File

@ -20,13 +20,14 @@ import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests TestHSSFCellComment. * Tests TestHSSFCellComment.
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class TestHSSFComment extends TestCase {
public class TestHSSFComment extends TestCase {
/** /**
* Test that we can create cells and add comments to it. * Test that we can create cells and add comments to it.
@ -83,12 +84,9 @@ public class TestHSSFComment extends TestCase {
/** /**
* test that we can read cell comments from an existing workbook. * test that we can read cell comments from an existing workbook.
*/ */
public static void testReadComments() throws Exception { public static void testReadComments() {
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls");
FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls"));
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
@ -123,12 +121,9 @@ public class TestHSSFComment extends TestCase {
/** /**
* test that we can modify existing cell comments * test that we can modify existing cell comments
*/ */
public static void testModifyComments() throws Exception { public static void testModifyComments() throws IOException {
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls");
FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls"));
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);

View File

@ -19,16 +19,15 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.TimeZone; import java.util.TimeZone;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Class TestHSSFDateUtil * Class TestHSSFDateUtil
@ -40,16 +39,13 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* @author Alex Jacoby (ajacoby at gmail.com) * @author Alex Jacoby (ajacoby at gmail.com)
* @version %I%, %G% * @version %I%, %G%
*/ */
public class TestHSSFDateUtil extends TestCase {
public class TestHSSFDateUtil public static final int CALENDAR_JANUARY = 0;
extends TestCase public static final int CALENDAR_FEBRUARY = 1;
{ public static final int CALENDAR_MARCH = 2;
public static final int CALENDAR_APRIL = 3;
public static final int CALENDAR_JANUARY = 0; public static final int CALENDAR_JULY = 6;
public static final int CALENDAR_FEBRUARY = 1;
public static final int CALENDAR_MARCH = 2;
public static final int CALENDAR_APRIL = 3;
public static final int CALENDAR_JULY = 6;
public static final int CALENDAR_OCTOBER = 9; public static final int CALENDAR_OCTOBER = 9;
public TestHSSFDateUtil(String s) public TestHSSFDateUtil(String s)
@ -223,77 +219,77 @@ public class TestHSSFDateUtil
* Tests that we correctly detect date formats as such * Tests that we correctly detect date formats as such
*/ */
public void testIdentifyDateFormats() { public void testIdentifyDateFormats() {
// First up, try with a few built in date formats // First up, try with a few built in date formats
short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e }; short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e };
for(int i=0; i<builtins.length; i++) { for(int i=0; i<builtins.length; i++) {
String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]); String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]);
assertTrue( HSSFDateUtil.isInternalDateFormat(builtins[i]) ); assertTrue( HSSFDateUtil.isInternalDateFormat(builtins[i]) );
assertTrue( HSSFDateUtil.isADateFormat(builtins[i],formatStr) ); assertTrue( HSSFDateUtil.isADateFormat(builtins[i],formatStr) );
} }
// Now try a few built-in non date formats // Now try a few built-in non date formats
builtins = new short[] { 0x01, 0x02, 0x17, 0x1f, 0x30 }; builtins = new short[] { 0x01, 0x02, 0x17, 0x1f, 0x30 };
for(int i=0; i<builtins.length; i++) { for(int i=0; i<builtins.length; i++) {
String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]); String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]);
assertFalse( HSSFDateUtil.isInternalDateFormat(builtins[i]) ); assertFalse( HSSFDateUtil.isInternalDateFormat(builtins[i]) );
assertFalse( HSSFDateUtil.isADateFormat(builtins[i],formatStr) ); assertFalse( HSSFDateUtil.isADateFormat(builtins[i],formatStr) );
} }
// Now for some non-internal ones // Now for some non-internal ones
// These come after the real ones // These come after the real ones
int numBuiltins = HSSFDataFormat.getNumberOfBuiltinBuiltinFormats(); int numBuiltins = HSSFDataFormat.getNumberOfBuiltinBuiltinFormats();
assertTrue(numBuiltins < 60); assertTrue(numBuiltins < 60);
short formatId = 60; short formatId = 60;
assertFalse( HSSFDateUtil.isInternalDateFormat(formatId) ); assertFalse( HSSFDateUtil.isInternalDateFormat(formatId) );
// Valid ones first // Valid ones first
String[] formats = new String[] { String[] formats = new String[] {
"yyyy-mm-dd", "yyyy/mm/dd", "yy/mm/dd", "yy/mmm/dd", "yyyy-mm-dd", "yyyy/mm/dd", "yy/mm/dd", "yy/mmm/dd",
"dd/mm/yy", "dd/mm/yyyy", "dd/mmm/yy", "dd/mm/yy", "dd/mm/yyyy", "dd/mmm/yy",
"dd-mm-yy", "dd-mm-yyyy", "dd-mm-yy", "dd-mm-yyyy",
"DD-MM-YY", "DD-mm-YYYY", "DD-MM-YY", "DD-mm-YYYY",
"dd\\-mm\\-yy", // Sometimes escaped "dd\\-mm\\-yy", // Sometimes escaped
// These crazy ones are valid // These crazy ones are valid
"yyyy-mm-dd;@", "yyyy/mm/dd;@", "yyyy-mm-dd;@", "yyyy/mm/dd;@",
"dd-mm-yy;@", "dd-mm-yyyy;@", "dd-mm-yy;@", "dd-mm-yyyy;@",
// These even crazier ones are also valid // These even crazier ones are also valid
// (who knows what they mean though...) // (who knows what they mean though...)
"[$-F800]dddd\\,\\ mmm\\ dd\\,\\ yyyy", "[$-F800]dddd\\,\\ mmm\\ dd\\,\\ yyyy",
"[$-F900]ddd/mm/yyy", "[$-F900]ddd/mm/yyy",
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
// Then time based ones too // Then time based ones too
formats = new String[] { formats = new String[] {
"yyyy-mm-dd hh:mm:ss", "yyyy/mm/dd HH:MM:SS", "yyyy-mm-dd hh:mm:ss", "yyyy/mm/dd HH:MM:SS",
"mm/dd HH:MM", "yy/mmm/dd SS", "mm/dd HH:MM", "yy/mmm/dd SS",
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
// Then invalid ones // Then invalid ones
formats = new String[] { formats = new String[] {
"yyyy*mm*dd", "yyyy*mm*dd",
"0.0", "0.000", "0.0", "0.000",
"0%", "0.0%", "0%", "0.0%",
"", null "", null
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
// And these are ones we probably shouldn't allow, // And these are ones we probably shouldn't allow,
// but would need a better regexp // but would need a better regexp
formats = new String[] { formats = new String[] {
"yyyy:mm:dd", "yyyy:mm:dd",
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
// assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); // assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
} }
/** /**
@ -301,11 +297,8 @@ public class TestHSSFDateUtil
* correctly * correctly
*/ */
public void testOnARealFile() throws Exception { public void testOnARealFile() throws Exception {
String path = System.getProperty("HSSF.testdata.path");
String filename = path + "/DateFormats.xls"; HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
POIFSFileSystem fs =
new POIFSFileSystem(new FileInputStream(filename));
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
Workbook wb = workbook.getWorkbook(); Workbook wb = workbook.getWorkbook();

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,21 +14,17 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests row shifting capabilities. * Tests row shifting capabilities.
@ -37,117 +32,90 @@ import java.io.FileOutputStream;
* *
* @author Shawn Laubach (slaubach at apache dot com) * @author Shawn Laubach (slaubach at apache dot com)
*/ */
public final class TestHSSFHeaderFooter extends TestCase {
public class TestHSSFHeaderFooter extends TestCase { /**
* Tests that get header retreives the proper values.
/** *
* Constructor for TestHeaderFooter. * @author Shawn Laubach (slaubach at apache dot org)
* @param arg0 */
*/ public void testRetrieveCorrectHeader() {
public TestHSSFHeaderFooter(String arg0) { // Read initial file in
super(arg0); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("EmbeddedChartHeaderTest.xls");
} HSSFSheet s = wb.getSheetAt( 0 );
HSSFHeader head = s.getHeader();
/**
* Tests that get header retreives the proper values.
*
* @author Shawn Laubach (slaubach at apache dot org)
*/
public void testRetrieveCorrectHeader() throws Exception
{
// Read initial file in
String filename = System.getProperty( "HSSF.testdata.path" );
filename = filename + "/EmbeddedChartHeaderTest.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet s = wb.getSheetAt( 0 );
HSSFHeader head = s.getHeader();
assertEquals("Top Left", head.getLeft());
assertEquals("Top Center", head.getCenter());
assertEquals("Top Right", head.getRight());
}
/**
* Tests that get header retreives the proper values.
*
* @author Shawn Laubach (slaubach at apache dot org)
*/
public void testRetrieveCorrectFooter() throws Exception
{
// Read initial file in
String filename = System.getProperty( "HSSF.testdata.path" );
filename = filename + "/EmbeddedChartHeaderTest.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet s = wb.getSheetAt( 0 );
HSSFFooter foot = s.getFooter();
assertEquals("Bottom Left", foot.getLeft());
assertEquals("Bottom Center", foot.getCenter());
assertEquals("Bottom Right", foot.getRight());
}
/** assertEquals("Top Left", head.getLeft());
assertEquals("Top Center", head.getCenter());
assertEquals("Top Right", head.getRight());
}
/**
* Tests that get header retreives the proper values.
*
* @author Shawn Laubach (slaubach at apache dot org)
*/
public void testRetrieveCorrectFooter() {
// Read initial file in
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("EmbeddedChartHeaderTest.xls");
HSSFSheet s = wb.getSheetAt( 0 );
HSSFFooter foot = s.getFooter();
assertEquals("Bottom Left", foot.getLeft());
assertEquals("Bottom Center", foot.getCenter());
assertEquals("Bottom Right", foot.getRight());
}
/**
* Testcase for Bug 17039 HSSFHeader doesnot support DBCS * Testcase for Bug 17039 HSSFHeader doesnot support DBCS
*/ */
public void testHeaderHas16bitCharacter() throws Exception { public void testHeaderHas16bitCharacter() {
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet("Test"); HSSFSheet s = b.createSheet("Test");
HSSFHeader h = s.getHeader(); HSSFHeader h = s.getHeader();
h.setLeft("\u0391"); h.setLeft("\u0391");
h.setCenter("\u0392"); h.setCenter("\u0392");
h.setRight("\u0393"); h.setRight("\u0393");
ByteArrayOutputStream out = new ByteArrayOutputStream(); HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b);
b.write(out); HSSFHeader h2 = b2.getSheet("Test").getHeader();
HSSFWorkbook b2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); assertEquals(h2.getLeft(),"\u0391");
HSSFHeader h2 = b2.getSheet("Test").getHeader(); assertEquals(h2.getCenter(),"\u0392");
assertEquals(h2.getRight(),"\u0393");
assertEquals(h2.getLeft(),"\u0391");
assertEquals(h2.getCenter(),"\u0392");
assertEquals(h2.getRight(),"\u0393");
} }
/** /**
* Testcase for Bug 17039 HSSFFooter doesnot support DBCS * Testcase for Bug 17039 HSSFFooter doesnot support DBCS
*/ */
public void testFooterHas16bitCharacter() throws Exception{ public void testFooterHas16bitCharacter() {
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet("Test"); HSSFSheet s = b.createSheet("Test");
HSSFFooter f = s.getFooter(); HSSFFooter f = s.getFooter();
f.setLeft("\u0391"); f.setLeft("\u0391");
f.setCenter("\u0392"); f.setCenter("\u0392");
f.setRight("\u0393"); f.setRight("\u0393");
ByteArrayOutputStream out = new ByteArrayOutputStream(); HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b);
b.write(out); HSSFFooter f2 = b2.getSheet("Test").getFooter();
HSSFWorkbook b2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); assertEquals(f2.getLeft(),"\u0391");
HSSFFooter f2 = b2.getSheet("Test").getFooter(); assertEquals(f2.getCenter(),"\u0392");
assertEquals(f2.getRight(),"\u0393");
assertEquals(f2.getLeft(),"\u0391");
assertEquals(f2.getCenter(),"\u0392");
assertEquals(f2.getRight(),"\u0393");
} }
public void testReadDBCSHeaderFooter() throws Exception{ public void testReadDBCSHeaderFooter() {
String readFilename = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSHeader.xls");
FileInputStream in = new FileInputStream(readFilename+File.separator+"DBCSHeader.xls"); HSSFSheet s = wb.getSheetAt(0);
HSSFWorkbook wb = new HSSFWorkbook(in); HSSFHeader h = s.getHeader();
HSSFSheet s = wb.getSheetAt(0); assertEquals("Header Left " ,h.getLeft(),"\u090f\u0915");
HSSFHeader h = s.getHeader(); assertEquals("Header Center " ,h.getCenter(),"\u0939\u094b\u0917\u093e");
assertEquals("Header Left " ,h.getLeft(),"\u090f\u0915"); assertEquals("Header Right " ,h.getRight(),"\u091c\u093e");
assertEquals("Header Center " ,h.getCenter(),"\u0939\u094b\u0917\u093e");
assertEquals("Header Right " ,h.getRight(),"\u091c\u093e");
HSSFFooter f = s.getFooter(); HSSFFooter f = s.getFooter();
assertEquals("Footer Left " ,f.getLeft(),"\u091c\u093e"); assertEquals("Footer Left " ,f.getLeft(),"\u091c\u093e");
assertEquals("Footer Center " ,f.getCenter(),"\u091c\u093e"); assertEquals("Footer Center " ,f.getCenter(),"\u091c\u093e");
assertEquals("Footer Right " ,f.getRight(),"\u091c\u093e"); assertEquals("Footer Right " ,f.getRight(),"\u091c\u093e");
} }
} }

View File

@ -14,28 +14,28 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests HSSFHyperlink. * Tests HSSFHyperlink.
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public class TestHSSFHyperlink extends TestCase { public final class TestHSSFHyperlink extends TestCase {
protected String cwd = System.getProperty("HSSF.testdata.path");
/** /**
* Test that we can read hyperlinks. * Test that we can read hyperlinks.
*/ */
public void testRead() throws Exception { public void testRead() {
FileInputStream is = new FileInputStream(new File(cwd, "HyperlinksOnManySheets.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet; HSSFSheet sheet;
HSSFCell cell; HSSFCell cell;
@ -74,9 +74,7 @@ public class TestHSSFHyperlink extends TestCase {
} }
public void testModify() throws Exception { public void testModify() throws Exception {
FileInputStream is = new FileInputStream(new File(cwd, "HyperlinksOnManySheets.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet; HSSFSheet sheet;
HSSFCell cell; HSSFCell cell;
@ -168,10 +166,8 @@ public class TestHSSFHyperlink extends TestCase {
assertEquals("'Target Sheet'!A1", link.getAddress()); assertEquals("'Target Sheet'!A1", link.getAddress());
} }
public void testCloneSheet() throws Exception { public void testCloneSheet() {
FileInputStream is = new FileInputStream(new File(cwd, "HyperlinksOnManySheets.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFCell cell; HSSFCell cell;
HSSFHyperlink link; HSSFHyperlink link;

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,7 +14,7 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File; import java.io.File;
@ -25,6 +24,8 @@ import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.PaletteRecord; import org.apache.poi.hssf.record.PaletteRecord;
import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
@ -32,15 +33,10 @@ import org.apache.poi.util.TempFile;
/** /**
* @author Brian Sanders (bsanders at risklabs dot com) * @author Brian Sanders (bsanders at risklabs dot com)
*/ */
public class TestHSSFPalette extends TestCase public final class TestHSSFPalette extends TestCase {
{
private PaletteRecord palette; private PaletteRecord palette;
private HSSFPalette hssfPalette; private HSSFPalette hssfPalette;
public TestHSSFPalette(String name)
{
super(name);
}
public void setUp() public void setUp()
{ {
@ -54,12 +50,7 @@ public class TestHSSFPalette extends TestCase
public void testCustomPalette() throws IOException public void testCustomPalette() throws IOException
{ {
//reading sample xls //reading sample xls
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("Simple.xls");
File sample = new File(dir + "/Simple.xls");
assertTrue("Simple.xls exists and is readable", sample.canRead());
FileInputStream fis = new FileInputStream(sample);
HSSFWorkbook book = new HSSFWorkbook(fis);
fis.close();
//creating custom palette //creating custom palette
HSSFPalette palette = book.getCustomPalette(); HSSFPalette palette = book.getCustomPalette();
@ -72,7 +63,7 @@ public class TestHSSFPalette extends TestCase
book.write(fos); book.write(fos);
fos.close(); fos.close();
fis = new FileInputStream(temp); FileInputStream fis = new FileInputStream(temp);
book = new HSSFWorkbook(fis); book = new HSSFWorkbook(fis);
fis.close(); fis.close();
@ -98,14 +89,9 @@ public class TestHSSFPalette extends TestCase
/** /**
* Uses the palette from cell stylings * Uses the palette from cell stylings
*/ */
public void testPaletteFromCellColours() throws Exception { public void testPaletteFromCellColours() {
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("SimpleWithColours.xls");
File sample = new File(dir + "/SimpleWithColours.xls");
assertTrue("SimpleWithColours.xls exists and is readable", sample.canRead());
FileInputStream fis = new FileInputStream(sample);
HSSFWorkbook book = new HSSFWorkbook(fis);
fis.close();
HSSFPalette p = book.getCustomPalette(); HSSFPalette p = book.getCustomPalette();
HSSFCell cellA = book.getSheetAt(0).getRow(0).getCell((short)0); HSSFCell cellA = book.getSheetAt(0).getRow(0).getCell((short)0);
@ -161,46 +147,46 @@ public class TestHSSFPalette extends TestCase
} }
public void testFindSimilar() throws Exception { public void testFindSimilar() throws Exception {
HSSFWorkbook book = new HSSFWorkbook(); HSSFWorkbook book = new HSSFWorkbook();
HSSFPalette p = book.getCustomPalette(); HSSFPalette p = book.getCustomPalette();
// Add a few edge colours in // Add a few edge colours in
p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0); p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0);
p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0); p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0);
p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1); p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1);
// And some near a few of them // And some near a few of them
p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2); p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2);
p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10); p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10);
p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0); p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0);
p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0); p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0);
assertEquals( assertEquals(
"FFFF:0:0", p.getColor((short)8).getHexString() "FFFF:0:0", p.getColor((short)8).getHexString()
); );
// Now check we get the right stuff back // Now check we get the right stuff back
assertEquals( assertEquals(
p.getColor((short)8).getHexString(), p.getColor((short)8).getHexString(),
p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString() p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)8).getHexString(), p.getColor((short)8).getHexString(),
p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString() p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)8).getHexString(), p.getColor((short)8).getHexString(),
p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString() p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)11).getHexString(), p.getColor((short)11).getHexString(),
p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString() p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)12).getHexString(), p.getColor((short)12).getHexString(),
p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString() p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString()
); );
} }
/** /**

View File

@ -17,13 +17,13 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Test <code>HSSFPicture</code>. * Test <code>HSSFPicture</code>.
* *
@ -58,9 +58,8 @@ public final class TestHSSFPicture extends TestCase{
private static byte[] getTestDataFileContent(String fileName) { private static byte[] getTestDataFileContent(String fileName) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
String readFilename = System.getProperty("HSSF.testdata.path");
try { try {
InputStream fis = new FileInputStream(readFilename+File.separator+fileName); InputStream fis = HSSFTestDataSamples.openSampleFileStream(fileName);
byte[] buf = new byte[512]; byte[] buf = new byte[512];
while(true) { while(true) {

View File

@ -15,20 +15,19 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
/*
* HSSFWorkbook.java
*
* Created on September 30, 2001, 3:37 PM
*/
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import junit.framework.TestCase; import junit.framework.TestCase;
import javax.imageio.ImageIO; import org.apache.poi.hssf.HSSFTestDataSamples;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
/** /**
* Test <code>HSSFPictureData</code>. * Test <code>HSSFPictureData</code>.
@ -37,14 +36,11 @@ import java.awt.image.BufferedImage;
* @author Yegor Kozlov (yegor at apache dot org) * @author Yegor Kozlov (yegor at apache dot org)
* @author Trejkaz (trejkaz at trypticon dot org) * @author Trejkaz (trejkaz at trypticon dot org)
*/ */
public class TestHSSFPictureData extends TestCase{ public final class TestHSSFPictureData extends TestCase{
static String cwd = System.getProperty("HSSF.testdata.path");
public void testPictures() throws IOException { public void testPictures() throws IOException {
FileInputStream is = new FileInputStream(new File(cwd, "SimpleWithImages.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
List lst = wb.getAllPictures(); List lst = wb.getAllPictures();
//assertEquals(2, lst.size()); //assertEquals(2, lst.size());
@ -69,6 +65,5 @@ public class TestHSSFPictureData extends TestCase{
//TODO: test code for PICT, WMF and EMF //TODO: test code for PICT, WMF and EMF
} }
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -14,28 +14,22 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import junit.framework.*; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.NameRecord; import org.apache.poi.hssf.record.NameRecord;
/**
*
*/
public final class TestHSSFWorkbook extends TestCase {
private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
public class TestHSSFWorkbook extends TestCase public void testSetRepeatingRowsAndColumns() {
{
HSSFWorkbook hssfWorkbook;
String filename;
protected void setUp() throws Exception {
super.setUp();
filename = System.getProperty("HSSF.testdata.path");
}
public void testSetRepeatingRowsAndColumns() throws Exception
{
// Test bug 29747 // Test bug 29747
HSSFWorkbook b = new HSSFWorkbook( ); HSSFWorkbook b = new HSSFWorkbook( );
b.createSheet(); b.createSheet();
@ -46,9 +40,7 @@ public class TestHSSFWorkbook extends TestCase
assertEquals( 3, nameRecord.getIndexToSheet() ); assertEquals( 3, nameRecord.getIndexToSheet() );
} }
public void testDuplicateNames() public void testDuplicateNames() {
throws Exception
{
HSSFWorkbook b = new HSSFWorkbook( ); HSSFWorkbook b = new HSSFWorkbook( );
b.createSheet("Sheet1"); b.createSheet("Sheet1");
b.createSheet(); b.createSheet();
@ -105,15 +97,15 @@ public class TestHSSFWorkbook extends TestCase
public void testSheetSelection() { public void testSheetSelection() {
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
b.createSheet("Sheet One"); b.createSheet("Sheet One");
HSSFSheet s = b.createSheet("Sheet Two"); b.createSheet("Sheet Two");
b.setSelectedTab((short) 1); b.setSelectedTab((short) 1);
b.setDisplayedTab((short) 1); b.setDisplayedTab((short) 1);
assertEquals(b.getSelectedTab(), 1); assertEquals(b.getSelectedTab(), 1);
assertEquals(b.getDisplayedTab(), 1); assertEquals(b.getDisplayedTab(), 1);
} }
public void testSheetClone() throws Exception { public void testSheetClone() {
// First up, try a simple file // First up, try a simple file
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
assertEquals(0, b.getNumberOfSheets()); assertEquals(0, b.getNumberOfSheets());
b.createSheet("Sheet One"); b.createSheet("Sheet One");
@ -122,24 +114,20 @@ public class TestHSSFWorkbook extends TestCase
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b.getNumberOfSheets());
b.cloneSheet(0); b.cloneSheet(0);
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b.getNumberOfSheets());
// Now try a problem one with drawing records in it // Now try a problem one with drawing records in it
b = new HSSFWorkbook( b = openSample("SheetWithDrawing.xls");
new FileInputStream(new File(filename,"SheetWithDrawing.xls"))
);
assertEquals(1, b.getNumberOfSheets()); assertEquals(1, b.getNumberOfSheets());
b.cloneSheet(0); b.cloneSheet(0);
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b.getNumberOfSheets());
} }
public void testReadWriteWithCharts() throws Exception { public void testReadWriteWithCharts() {
HSSFWorkbook b; HSSFWorkbook b;
HSSFSheet s; HSSFSheet s;
// Single chart, two sheets // Single chart, two sheets
b = new HSSFWorkbook( b = openSample("44010-SingleChart.xls");
new FileInputStream(new File(filename,"44010-SingleChart.xls"))
);
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b.getNumberOfSheets());
s = b.getSheetAt(1); s = b.getSheetAt(1);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
@ -154,9 +142,7 @@ public class TestHSSFWorkbook extends TestCase
// We've now called getDrawingPatriarch() so // We've now called getDrawingPatriarch() so
// everything will be all screwy // everything will be all screwy
// So, start again // So, start again
b = new HSSFWorkbook( b = openSample("44010-SingleChart.xls");
new FileInputStream(new File(filename,"44010-SingleChart.xls"))
);
b = writeRead(b); b = writeRead(b);
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b.getNumberOfSheets());
@ -166,9 +152,7 @@ public class TestHSSFWorkbook extends TestCase
// Two charts, three sheets // Two charts, three sheets
b = new HSSFWorkbook( b = openSample("44010-TwoCharts.xls");
new FileInputStream(new File(filename,"44010-TwoCharts.xls"))
);
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b.getNumberOfSheets());
s = b.getSheetAt(1); s = b.getSheetAt(1);
@ -188,9 +172,7 @@ public class TestHSSFWorkbook extends TestCase
// We've now called getDrawingPatriarch() so // We've now called getDrawingPatriarch() so
// everything will be all screwy // everything will be all screwy
// So, start again // So, start again
b = new HSSFWorkbook( b = openSample("44010-TwoCharts.xls");
new FileInputStream(new File(filename,"44010-TwoCharts.xls"))
);
b = writeRead(b); b = writeRead(b);
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b.getNumberOfSheets());
@ -203,11 +185,7 @@ public class TestHSSFWorkbook extends TestCase
assertEquals(0, s.getLastRowNum()); assertEquals(0, s.getLastRowNum());
} }
private HSSFWorkbook writeRead(HSSFWorkbook b) throws Exception { private static HSSFWorkbook writeRead(HSSFWorkbook b) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); return HSSFTestDataSamples.writeOutAndReadBack(b);
b.write(baos);
return new HSSFWorkbook(
new ByteArrayInputStream(baos.toByteArray())
);
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,17 +14,9 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import org.apache.poi.hssf.util.AreaReference;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.TempFile;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -33,6 +24,12 @@ import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.util.AreaReference;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.util.TempFile;
/** /**
* *
@ -41,115 +38,69 @@ import java.io.IOException;
* @author Danny Mui (danny at muibros.com) * @author Danny Mui (danny at muibros.com)
* @author Amol S. Deshmukh &lt; amol at ap ache dot org &gt; * @author Amol S. Deshmukh &lt; amol at ap ache dot org &gt;
*/ */
public class TestNamedRange public final class TestNamedRange extends TestCase {
extends TestCase {
public TestNamedRange(String testName) {
super(testName);
}
public static void main(java.lang.String[] args) {
String filename = System.getProperty("HSSF.testdata.path");
// assume andy is running this in the debugger
if (filename == null)
{
if (args != null && args.length == 1) {
System.setProperty(
"HSSF.testdata.path",
args[0]);
} else {
System.err.println("Geesh, no HSSF.testdata.path system " +
"property, no command line arg with the path "+
"what do you expect me to do, guess where teh data " +
"files are? Sorry, I give up!");
}
}
junit.textui.TestRunner.run(TestNamedRange.class);
}
/** Test of TestCase method, of class test.RangeTest. */
public void testNamedRange()
throws IOException
{
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Simple.xls"; private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis); public static void main(String[] args) {
wb = new HSSFWorkbook(fs); junit.textui.TestRunner.run(TestNamedRange.class);
}
//Creating new Named Range /** Test of TestCase method, of class test.RangeTest. */
HSSFName newNamedRange = wb.createName(); public void testNamedRange()
throws IOException
//Getting Sheet Name for the reference {
String sheetName = wb.getSheetName(0); HSSFWorkbook wb = openSample("Simple.xls");
//Setting its name //Creating new Named Range
newNamedRange.setNameName("RangeTest"); HSSFName newNamedRange = wb.createName();
//Setting its reference
newNamedRange.setReference(sheetName + "!$D$4:$E$8"); //Getting Sheet Name for the reference
String sheetName = wb.getSheetName(0);
//Setting its name
newNamedRange.setNameName("RangeTest");
//Setting its reference
newNamedRange.setReference(sheetName + "!$D$4:$E$8");
//Getting NAmed Range //Getting NAmed Range
HSSFName namedRange1 = wb.getNameAt(0); HSSFName namedRange1 = wb.getNameAt(0);
//Getting it sheet name //Getting it sheet name
sheetName = namedRange1.getSheetName(); sheetName = namedRange1.getSheetName();
//Getting its reference //Getting its reference
String referece = namedRange1.getReference(); String referece = namedRange1.getReference();
// sanity check // sanity check
SanityChecker c = new SanityChecker(); SanityChecker c = new SanityChecker();
c.checkHSSFWorkbook(wb); c.checkHSSFWorkbook(wb);
File file = TempFile.createTempFile("testNamedRange", File file = TempFile.createTempFile("testNamedRange", ".xls");
".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut); wb.write(fileOut);
fis.close();
fileOut.close(); fileOut.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in); wb = new HSSFWorkbook(in);
HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest")); HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest"));
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference()); assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference());
} }
/** /**
* Reads an excel file already containing a named range. * Reads an excel file already containing a named range.
* <p> * <p>
* Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=9632" target="_bug">#9632</a> * Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=9632" target="_bug">#9632</a>
*/ */
public void testNamedRead() throws IOException public void testNamedRead() {
{ HSSFWorkbook wb = openSample("namedinput.xls");
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/namedinput.xls";
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis);
wb = new HSSFWorkbook(fs);
//Get index of the namedrange with the name = "NamedRangeName" , which was defined in input.xls as A1:D10 //Get index of the namedrange with the name = "NamedRangeName" , which was defined in input.xls as A1:D10
int NamedRangeIndex = wb.getNameIndex("NamedRangeName"); int NamedRangeIndex = wb.getNameIndex("NamedRangeName");
@ -161,103 +112,86 @@ public class TestNamedRange
//Getting its reference //Getting its reference
String reference = namedRange1.getReference(); String reference = namedRange1.getReference();
fis.close();
assertEquals(sheetName+"!$A$1:$D$10", reference); assertEquals(sheetName+"!$A$1:$D$10", reference);
HSSFName namedRange2 = wb.getNameAt(1); HSSFName namedRange2 = wb.getNameAt(1);
assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getReference()); assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getReference());
assertEquals("SecondNamedRange", namedRange2.getNameName()); assertEquals("SecondNamedRange", namedRange2.getNameName());
} }
/**
* Reads an excel file already containing a named range and updates it
* <p>
* Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=16411" target="_bug">#16411</a>
*/
public void testNamedReadModify() throws IOException
{
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/namedinput.xls"; /**
* Reads an excel file already containing a named range and updates it
* <p>
fis = new FileInputStream(filename); * Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=16411" target="_bug">#16411</a>
fs = new POIFSFileSystem(fis); */
wb = new HSSFWorkbook(fs); public void testNamedReadModify() {
HSSFWorkbook wb = openSample("namedinput.xls");
HSSFName name = wb.getNameAt(0); HSSFName name = wb.getNameAt(0);
String sheetName = wb.getSheetName(0); String sheetName = wb.getSheetName(0);
assertEquals(sheetName+"!$A$1:$D$10", name.getReference()); assertEquals(sheetName+"!$A$1:$D$10", name.getReference());
name = wb.getNameAt(1); name = wb.getNameAt(1);
String newReference = sheetName +"!$A$1:$C$36"; String newReference = sheetName +"!$A$1:$C$36";
name.setReference(newReference); name.setReference(newReference);
assertEquals(newReference, name.getReference()); assertEquals(newReference, name.getReference());
}
}
/** /**
* Test that multiple named ranges can be added written and read * Test that multiple named ranges can be added written and read
*/ */
public void testMultipleNamedWrite() public void testMultipleNamedWrite()
throws IOException throws IOException
{ {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("testSheet1"); HSSFSheet sheet = wb.createSheet("testSheet1");
String sheetName = wb.getSheetName(0); String sheetName = wb.getSheetName(0);
assertEquals("testSheet1", sheetName); assertEquals("testSheet1", sheetName);
//Creating new Named Range //Creating new Named Range
HSSFName newNamedRange = wb.createName(); HSSFName newNamedRange = wb.createName();
newNamedRange.setNameName("RangeTest"); newNamedRange.setNameName("RangeTest");
newNamedRange.setReference(sheetName + "!$D$4:$E$8"); newNamedRange.setReference(sheetName + "!$D$4:$E$8");
//Creating another new Named Range
HSSFName newNamedRange2 = wb.createName();
newNamedRange2.setNameName("AnotherTest");
newNamedRange2.setReference(sheetName + "!$F$1:$G$6");
//Creating another new Named Range
HSSFName newNamedRange2 = wb.createName();
newNamedRange2.setNameName("AnotherTest");
newNamedRange2.setReference(sheetName + "!$F$1:$G$6");
HSSFName namedRange1 = wb.getNameAt(0); HSSFName namedRange1 = wb.getNameAt(0);
String referece = namedRange1.getReference(); String referece = namedRange1.getReference();
File file = TempFile.createTempFile("testMultiNamedRange", ".xls"); File file = TempFile.createTempFile("testMultiNamedRange", ".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in); wb = new HSSFWorkbook(in);
HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest")); HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest"));
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertTrue("Reference is "+nm.getReference(),(wb.getSheetName(0)+"!$D$4:$E$8").equals(nm.getReference())); assertTrue("Reference is "+nm.getReference(),(wb.getSheetName(0)+"!$D$4:$E$8").equals(nm.getReference()));
nm = wb.getNameAt(wb.getNameIndex("AnotherTest")); nm = wb.getNameAt(wb.getNameIndex("AnotherTest"));
assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName())); assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName()));
assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference())); assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference()));
} }
/** /**
* Test case provided by czhang@cambian.com (Chun Zhang) * Test case provided by czhang@cambian.com (Chun Zhang)
@ -268,7 +202,7 @@ public class TestNamedRange
public void testMultiNamedRange() public void testMultiNamedRange()
throws IOException throws IOException
{ {
// Create a new workbook // Create a new workbook
HSSFWorkbook wb = new HSSFWorkbook (); HSSFWorkbook wb = new HSSFWorkbook ();
@ -276,14 +210,14 @@ public class TestNamedRange
// Create a worksheet 'sheet1' in the new workbook // Create a worksheet 'sheet1' in the new workbook
wb.createSheet (); wb.createSheet ();
wb.setSheetName (0, "sheet1"); wb.setSheetName (0, "sheet1");
// Create another worksheet 'sheet2' in the new workbook // Create another worksheet 'sheet2' in the new workbook
wb.createSheet (); wb.createSheet ();
wb.setSheetName (1, "sheet2"); wb.setSheetName (1, "sheet2");
// Create a new named range for worksheet 'sheet1' // Create a new named range for worksheet 'sheet1'
HSSFName namedRange1 = wb.createName(); HSSFName namedRange1 = wb.createName();
// Set the name for the named range for worksheet 'sheet1' // Set the name for the named range for worksheet 'sheet1'
namedRange1.setNameName("RangeTest1"); namedRange1.setNameName("RangeTest1");
@ -292,21 +226,21 @@ public class TestNamedRange
// Create a new named range for worksheet 'sheet2' // Create a new named range for worksheet 'sheet2'
HSSFName namedRange2 = wb.createName(); HSSFName namedRange2 = wb.createName();
// Set the name for the named range for worksheet 'sheet2' // Set the name for the named range for worksheet 'sheet2'
namedRange2.setNameName("RangeTest2"); namedRange2.setNameName("RangeTest2");
// Set the reference for the named range for worksheet 'sheet2' // Set the reference for the named range for worksheet 'sheet2'
namedRange2.setReference("sheet2" + "!$A$1:$O$21"); namedRange2.setReference("sheet2" + "!$A$1:$O$21");
// Write the workbook to a file // Write the workbook to a file
File file = TempFile.createTempFile("testMuiltipletNamedRanges", ".xls"); File file = TempFile.createTempFile("testMuiltipletNamedRanges", ".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
// Read the Excel file and verify its content // Read the Excel file and verify its content
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in); wb = new HSSFWorkbook(in);
@ -317,42 +251,42 @@ public class TestNamedRange
HSSFName nm2 =wb.getNameAt(wb.getNameIndex("RangeTest2")); HSSFName nm2 =wb.getNameAt(wb.getNameIndex("RangeTest2"));
assertTrue("Name is "+nm2.getNameName(),"RangeTest2".equals(nm2.getNameName())); assertTrue("Name is "+nm2.getNameName(),"RangeTest2".equals(nm2.getNameName()));
assertTrue("Reference is "+nm2.getReference(),(wb.getSheetName(1)+"!$A$1:$O$21").equals(nm2.getReference())); assertTrue("Reference is "+nm2.getReference(),(wb.getSheetName(1)+"!$A$1:$O$21").equals(nm2.getReference()));
} }
public void testUnicodeNamedRange() throws Exception { public void testUnicodeNamedRange() throws Exception {
HSSFWorkbook workBook = new HSSFWorkbook(); HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("Test"); HSSFSheet sheet = workBook.createSheet("Test");
HSSFName name = workBook.createName(); HSSFName name = workBook.createName();
name.setNameName("\u03B1"); name.setNameName("\u03B1");
name.setReference("Test!$D$3:$E$8"); name.setReference("Test!$D$3:$E$8");
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
workBook.write(out); workBook.write(out);
HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray()));
HSSFName name2 = workBook2.getNameAt(0); HSSFName name2 = workBook2.getNameAt(0);
assertEquals("\u03B1", name2.getNameName()); assertEquals("\u03B1", name2.getNameName());
assertEquals("Test!$D$3:$E$8", name2.getReference()); assertEquals("Test!$D$3:$E$8", name2.getReference());
} }
/** /**
* Test to see if the print areas can be retrieved/created in memory * Test to see if the print areas can be retrieved/created in memory
*/ */
public void testSinglePrintArea() public void testSinglePrintArea()
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1"; String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
} }
/** /**
@ -360,53 +294,31 @@ public class TestNamedRange
*/ */
public void testSinglePrintAreaWOSheet() public void testSinglePrintAreaWOSheet()
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = "$A$1:$B$1"; String reference = "$A$1:$B$1";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'" + sheetName + "'!" + reference, retrievedPrintArea); assertEquals("'" + sheetName + "'!" + reference, retrievedPrintArea);
} }
/** /**
* Test to see if the print area can be retrieved from an excel created file * Test to see if the print area can be retrieved from an excel created file
*/ */
public void testPrintAreaFileRead() public void testPrintAreaFileRead() {
throws IOException HSSFWorkbook workbook = openSample("SimpleWithPrintArea.xls");
{
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook workbook = null;
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithPrintArea.xls"; String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$C$5";
try {
assertEquals(reference, workbook.getPrintArea(0));
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis);
workbook = new HSSFWorkbook(fs);
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$C$5";
assertEquals(reference, workbook.getPrintArea(0));
} finally {
fis.close();
}
} }
@ -416,29 +328,29 @@ public class TestNamedRange
public void testPrintAreaFile() public void testPrintAreaFile()
throws IOException throws IOException
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1"; String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
File file = TempFile.createTempFile("testPrintArea",".xls"); File file = TempFile.createTempFile("testPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut); workbook.write(fileOut);
fileOut.close(); fileOut.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in); workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("References Match", "'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); assertEquals("References Match", "'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
} }
/** /**
@ -447,180 +359,178 @@ public class TestNamedRange
public void testMultiplePrintAreaFile() public void testMultiplePrintAreaFile()
throws IOException throws IOException
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1"); HSSFSheet sheet = workbook.createSheet("Sheet1");
sheet = workbook.createSheet("Sheet2"); sheet = workbook.createSheet("Sheet2");
sheet = workbook.createSheet("Sheet3"); sheet = workbook.createSheet("Sheet3");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = null; String reference = null;
reference = sheetName+"!$A$1:$B$1"; reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
sheetName = workbook.getSheetName(1); sheetName = workbook.getSheetName(1);
String reference2 = sheetName+"!$B$2:$D$5"; String reference2 = sheetName+"!$B$2:$D$5";
workbook.setPrintArea(1, reference2); workbook.setPrintArea(1, reference2);
sheetName = workbook.getSheetName(2); sheetName = workbook.getSheetName(2);
String reference3 = sheetName+"!$D$2:$F$5"; String reference3 = sheetName+"!$D$2:$F$5";
workbook.setPrintArea(2, reference3); workbook.setPrintArea(2, reference3);
File file = TempFile.createTempFile("testMultiPrintArea",".xls"); File file = TempFile.createTempFile("testMultiPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut); workbook.write(fileOut);
fileOut.close(); fileOut.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in); workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea);
assertEquals(reference, retrievedPrintArea); assertEquals(reference, retrievedPrintArea);
String retrievedPrintArea2 = workbook.getPrintArea(1); String retrievedPrintArea2 = workbook.getPrintArea(1);
assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2); assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2);
assertEquals(reference2, retrievedPrintArea2); assertEquals(reference2, retrievedPrintArea2);
String retrievedPrintArea3 = workbook.getPrintArea(2); String retrievedPrintArea3 = workbook.getPrintArea(2);
assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3); assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3);
assertEquals(reference3, retrievedPrintArea3); assertEquals(reference3, retrievedPrintArea3);
} }
/** /**
* Tests the setting of print areas with coordinates (Row/Column designations) * Tests the setting of print areas with coordinates (Row/Column designations)
* *
*/ */
public void testPrintAreaCoords(){ public void testPrintAreaCoords(){
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1"; String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, 0, 1, 0, 0); workbook.setPrintArea(0, 0, 1, 0, 0);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
}
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
/** assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
* Tests the parsing of union area expressions, and re-display in the presence of sheet names }
* with special characters.
*/
public void testPrintAreaUnion(){ /**
HSSFWorkbook workbook = new HSSFWorkbook(); * Tests the parsing of union area expressions, and re-display in the presence of sheet names
HSSFSheet sheet = workbook.createSheet("Test Print Area"); * with special characters.
*/
public void testPrintAreaUnion(){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = sheetName + "!$A$1:$B$1, " + sheetName + "!$D$1:$F$2"; String reference = sheetName + "!$A$1:$B$1, " + sheetName + "!$D$1:$F$2";
String expResult = "'" + sheetName + "'!$A$1:$B$1,'" + sheetName + "'!$D$1:$F$2"; String expResult = "'" + sheetName + "'!$A$1:$B$1,'" + sheetName + "'!$D$1:$F$2";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals(expResult, retrievedPrintArea); assertEquals(expResult, retrievedPrintArea);
} }
/** /**
* Verifies an existing print area is deleted * Verifies an existing print area is deleted
* *
*/ */
public void testPrintAreaRemove() { public void testPrintAreaRemove() {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1"; String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, 0, 1, 0, 0); workbook.setPrintArea(0, 0, 1, 0, 0);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
workbook.removePrintArea(0);
assertNull("PrintArea was not removed", workbook.getPrintArea(0));
}
/**
* Verifies correct functioning for "single cell named range" (aka "named cell")
*/
public void testNamedCell_1() {
// setup for this testcase
String sheetName = "Test Named Cell";
String cellName = "A name for a named cell";
String cellValue = "TEST Value";
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
sheet.createRow(0).createCell((short) 0).setCellValue(cellValue);
// create named range for a single cell using areareference
HSSFName namedCell = wb.createName();
namedCell.setNameName(cellName);
String reference = sheetName+"!A1:A1";
namedCell.setReference(reference);
// retrieve the newly created named range
int namedCellIdx = wb.getNameIndex(cellName);
HSSFName aNamedCell = wb.getNameAt(namedCellIdx);
assertNotNull(aNamedCell);
// retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getReference());
assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell());
CellReference cref = aref.getFirstCell();
assertNotNull(cref);
HSSFSheet s = wb.getSheet(cref.getSheetName());
assertNotNull(s);
HSSFRow r = sheet.getRow(cref.getRow());
HSSFCell c = r.getCell(cref.getCol());
String contents = c.getRichStringCellValue().getString();
assertEquals("Contents of cell retrieved by its named reference", contents, cellValue);
}
/** assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
* Verifies correct functioning for "single cell named range" (aka "named cell")
*/
public void testNamedCell_2() {
// setup for this testcase
String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sname);
sheet.createRow(0).createCell((short) 0).setCellValue(cvalue);
// create named range for a single cell using cellreference
HSSFName namedCell = wb.createName();
namedCell.setNameName(cname);
String reference = sname+"!A1";
namedCell.setReference(reference);
// retrieve the newly created named range
int namedCellIdx = wb.getNameIndex(cname);
HSSFName aNamedCell = wb.getNameAt(namedCellIdx);
assertNotNull(aNamedCell);
// retrieve the cell at the named range and test its contents
CellReference cref = new CellReference(aNamedCell.getReference());
assertNotNull(cref);
HSSFSheet s = wb.getSheet(cref.getSheetName());
HSSFRow r = sheet.getRow(cref.getRow());
HSSFCell c = r.getCell(cref.getCol());
String contents = c.getStringCellValue();
assertEquals("Contents of cell retrieved by its named reference", contents, cvalue);
}
workbook.removePrintArea(0);
assertNull("PrintArea was not removed", workbook.getPrintArea(0));
}
/**
* Verifies correct functioning for "single cell named range" (aka "named cell")
*/
public void testNamedCell_1() {
// setup for this testcase
String sheetName = "Test Named Cell";
String cellName = "A name for a named cell";
String cellValue = "TEST Value";
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
sheet.createRow(0).createCell((short) 0).setCellValue(cellValue);
// create named range for a single cell using areareference
HSSFName namedCell = wb.createName();
namedCell.setNameName(cellName);
String reference = sheetName+"!A1:A1";
namedCell.setReference(reference);
// retrieve the newly created named range
int namedCellIdx = wb.getNameIndex(cellName);
HSSFName aNamedCell = wb.getNameAt(namedCellIdx);
assertNotNull(aNamedCell);
// retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getReference());
assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell());
CellReference cref = aref.getFirstCell();
assertNotNull(cref);
HSSFSheet s = wb.getSheet(cref.getSheetName());
assertNotNull(s);
HSSFRow r = sheet.getRow(cref.getRow());
HSSFCell c = r.getCell(cref.getCol());
String contents = c.getRichStringCellValue().getString();
assertEquals("Contents of cell retrieved by its named reference", contents, cellValue);
}
/**
* Verifies correct functioning for "single cell named range" (aka "named cell")
*/
public void testNamedCell_2() {
// setup for this testcase
String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sname);
sheet.createRow(0).createCell((short) 0).setCellValue(cvalue);
// create named range for a single cell using cellreference
HSSFName namedCell = wb.createName();
namedCell.setNameName(cname);
String reference = sname+"!A1";
namedCell.setReference(reference);
// retrieve the newly created named range
int namedCellIdx = wb.getNameIndex(cname);
HSSFName aNamedCell = wb.getNameAt(namedCellIdx);
assertNotNull(aNamedCell);
// retrieve the cell at the named range and test its contents
CellReference cref = new CellReference(aNamedCell.getReference());
assertNotNull(cref);
HSSFSheet s = wb.getSheet(cref.getSheetName());
HSSFRow r = sheet.getRow(cref.getRow());
HSSFCell c = r.getCell(cref.getCol());
String contents = c.getStringCellValue();
assertEquals("Contents of cell retrieved by its named reference", contents, cvalue);
}
} }

View File

@ -17,36 +17,28 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestOLE2Embeding extends TestCase { import org.apache.poi.hssf.HSSFTestDataSamples;
public void testEmbeding() throws Exception {
String dirname = System.getProperty("HSSF.testdata.path");
String filename = dirname + "/ole2-embedding.xls";
File file = new File(filename); /**
FileInputStream in = new FileInputStream(file); *
HSSFWorkbook workbook; */
public final class TestOLE2Embeding extends TestCase {
public void testEmbeding() {
// This used to break, until bug #43116 was fixed // This used to break, until bug #43116 was fixed
workbook = new HSSFWorkbook(in); HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls");
in.close();
// Check we can get at the Escher layer still // Check we can get at the Escher layer still
workbook.getAllPictures(); workbook.getAllPictures();
} }
public void testEmbeddedObjects() throws Exception { public void testEmbeddedObjects() throws Exception {
String dirname = System.getProperty("HSSF.testdata.path"); HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls");
String filename = dirname + "/ole2-embedding.xls";
File file = new File(filename);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
List objects = workbook.getAllEmbeddedObjects(); List objects = workbook.getAllEmbeddedObjects();
assertEquals("Wrong number of objects", 2, objects.size()); assertEquals("Wrong number of objects", 2, objects.size());
assertEquals("Wrong name for first object", "MBD06CAB431", assertEquals("Wrong name for first object", "MBD06CAB431",
@ -56,6 +48,5 @@ public class TestOLE2Embeding extends TestCase {
((HSSFObjectData) ((HSSFObjectData)
objects.get(1)).getDirectory().getName()); objects.get(1)).getDirectory().getName());
} }
} }

View File

@ -17,32 +17,31 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.PropertySetFactory;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Old-style setting of POIFS properties doesn't work with POI 3.0.2 * Old-style setting of POIFS properties doesn't work with POI 3.0.2
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public class TestPOIFSProperties extends TestCase{ public class TestPOIFSProperties extends TestCase{
protected String cwd = System.getProperty("HSSF.testdata.path");
protected String title = "Testing POIFS properties"; private static final String title = "Testing POIFS properties";
public void testFail() throws Exception { public void testFail() throws Exception {
FileInputStream is = new FileInputStream(new File(cwd, "Simple.xls")); InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFWorkbook wb = new HSSFWorkbook(fs);
@ -62,19 +61,13 @@ public class TestPOIFSProperties extends TestCase{
POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
try { //failing assertion
//failing assertion assertEquals(title, summary2.getTitle());
assertEquals(title, summary2.getTitle());
} catch (AssertionError e){
assertTrue(true);
}
} }
public void testOK() throws Exception { public void testOK() throws Exception {
FileInputStream is = new FileInputStream(new File(cwd, "Simple.xls")); InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
//set POIFS properties before constructing HSSFWorkbook //set POIFS properties before constructing HSSFWorkbook
SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,47 +14,29 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.util.GregorianCalendar;
import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.EOFRecord; import org.apache.poi.hssf.record.EOFRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;
import java.util.GregorianCalendar;
import java.util.List;
/** /**
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public final class TestReadWriteChart extends TestCase {
public class TestReadWriteChart
extends TestCase
{
public TestReadWriteChart(String s)
{
super(s);
}
/** /**
* In the presence of a chart we need to make sure BOF/EOF records still exist. * In the presence of a chart we need to make sure BOF/EOF records still exist.
*/ */
public void testBOFandEOFRecords() {
public void testBOFandEOFRecords() HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls");
throws Exception
{
//System.out.println("made it in testBOFandEOF");
String path = System.getProperty("HSSF.testdata.path");
String filename = path + "/SimpleChart.xls";
//System.out.println("path is "+path);
POIFSFileSystem fs =
new POIFSFileSystem(new FileInputStream(filename));
//System.out.println("opened file");
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow firstRow = sheet.getRow(0); HSSFRow firstRow = sheet.getRow(0);
HSSFCell firstCell = firstRow.getCell(( short ) 0); HSSFCell firstCell = firstRow.getCell(( short ) 0);
@ -77,29 +58,7 @@ public class TestReadWriteChart
assertTrue(records.get(records.size() - 1) instanceof EOFRecord); assertTrue(records.get(records.size() - 1) instanceof EOFRecord);
} }
public static void main(String [] args) public static void main(String [] args) {
{
String filename = System.getProperty("HSSF.testdata.path");
// assume andy is running this in the debugger
if (filename == null)
{
if (args != null && args[0].length() == 1) {
System.setProperty(
"HSSF.testdata.path",
args[0]);
} else {
System.err.println("Geesh, no HSSF.testdata.path system " +
"property, no command line arg with the path "+
"what do you expect me to do, guess where teh data " +
"files are? Sorry, I give up!");
}
}
System.out
.println("Testing org.apache.poi.hssf.usermodel.TestReadWriteChart");
junit.textui.TestRunner.run(TestReadWriteChart.class); junit.textui.TestRunner.run(TestReadWriteChart.class);
} }
} }

View File

@ -14,40 +14,28 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests for how HSSFWorkbook behaves with XLS files * Tests for how HSSFWorkbook behaves with XLS files
* with a WORKBOOK directory entry (instead of the more * with a WORKBOOK directory entry (instead of the more
* usual, Workbook) * usual, Workbook)
*/ */
public class TestSheetHiding extends TestCase { public final class TestSheetHiding extends TestCase {
private String dirPath;
private String xlsHidden = "TwoSheetsOneHidden.xls";
private String xlsShown = "TwoSheetsNoneHidden.xls";
private HSSFWorkbook wbH; private HSSFWorkbook wbH;
private HSSFWorkbook wbU; private HSSFWorkbook wbU;
protected void setUp() throws Exception { protected void setUp() {
super.setUp(); wbH = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsOneHidden.xls");
wbU = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsNoneHidden.xls");
dirPath = System.getProperty("HSSF.testdata.path");
FileInputStream isH = new FileInputStream(dirPath + "/" + xlsHidden);
POIFSFileSystem fsH = new POIFSFileSystem(isH);
FileInputStream isU = new FileInputStream(dirPath + "/" + xlsShown);
POIFSFileSystem fsU = new POIFSFileSystem(isU);
wbH = new HSSFWorkbook(fsH);
wbU = new HSSFWorkbook(fsU);
} }
/** /**

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,20 +14,15 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.TempFile;
import java.io.File;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests row shifting capabilities. * Tests row shifting capabilities.
@ -37,16 +31,7 @@ import java.io.FileOutputStream;
* @author Shawn Laubach (slaubach at apache dot com) * @author Shawn Laubach (slaubach at apache dot com)
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public final class TestSheetShiftRows extends TestCase {
public class TestSheetShiftRows extends TestCase {
/**
* Constructor for TestSheetShiftRows.
* @param arg0
*/
public TestSheetShiftRows(String arg0) {
super(arg0);
}
/** /**
* Tests the shiftRows function. Does three different shifts. * Tests the shiftRows function. Does three different shifts.
@ -59,25 +44,16 @@ public class TestSheetShiftRows extends TestCase {
public void testShiftRows() throws Exception public void testShiftRows() throws Exception
{ {
// Read initial file in // Read initial file in
String filename = System.getProperty( "HSSF.testdata.path" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls");
filename = filename + "/SimpleMultiCell.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet s = wb.getSheetAt( 0 ); HSSFSheet s = wb.getSheetAt( 0 );
// Shift the second row down 1 and write to temp file // Shift the second row down 1 and write to temp file
s.shiftRows( 1, 1, 1 ); s.shiftRows( 1, 1, 1 );
File tempFile = TempFile.createTempFile( "shift", "test.xls" );
FileOutputStream fout = new FileOutputStream( tempFile ); wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
wb.write( fout );
fout.close();
// Read from temp file and check the number of cells in each // Read from temp file and check the number of cells in each
// row (in original file each row was unique) // row (in original file each row was unique)
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 1 ); assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 1 );
@ -89,15 +65,9 @@ public class TestSheetShiftRows extends TestCase {
// Shift rows 1-3 down 3 in the current one. This tests when // Shift rows 1-3 down 3 in the current one. This tests when
// 1 row is blank. Write to a another temp file // 1 row is blank. Write to a another temp file
s.shiftRows( 0, 2, 3 ); s.shiftRows( 0, 2, 3 );
tempFile = TempFile.createTempFile( "shift", "test.xls" ); wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
fout = new FileOutputStream( tempFile );
wb.write( fout );
fout.close();
// Read and ensure things are where they should be // Read and ensure things are where they should be
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertTrue( s.getRow( 0 ) == null || s.getRow( 0 ).getPhysicalNumberOfCells() == 0 ); assertTrue( s.getRow( 0 ) == null || s.getRow( 0 ).getPhysicalNumberOfCells() == 0 );
assertTrue( s.getRow( 1 ) == null || s.getRow( 1 ).getPhysicalNumberOfCells() == 0 ); assertTrue( s.getRow( 1 ) == null || s.getRow( 1 ).getPhysicalNumberOfCells() == 0 );
@ -107,22 +77,12 @@ public class TestSheetShiftRows extends TestCase {
assertEquals( s.getRow( 5 ).getPhysicalNumberOfCells(), 2 ); assertEquals( s.getRow( 5 ).getPhysicalNumberOfCells(), 2 );
// Read the first file again // Read the first file again
fin = new FileInputStream( filename ); wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls");
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
// Shift rows 3 and 4 up and write to temp file // Shift rows 3 and 4 up and write to temp file
s.shiftRows( 2, 3, -2 ); s.shiftRows( 2, 3, -2 );
tempFile = TempFile.createTempFile( "shift", "test.xls" ); wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
fout = new FileOutputStream( tempFile );
wb.write( fout );
fout.close();
// Read file and test
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 3 ); assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 3 );
assertEquals( s.getRow( 1 ).getPhysicalNumberOfCells(), 4 ); assertEquals( s.getRow( 1 ).getPhysicalNumberOfCells(), 4 );
@ -137,11 +97,11 @@ public class TestSheetShiftRows extends TestCase {
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public void testShiftRow(){ public void testShiftRow(){
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet(); HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1"); s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2"); s.createRow(3).createCell((short)0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
} }
/** /**
@ -150,13 +110,13 @@ public class TestSheetShiftRows extends TestCase {
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public void testShiftRow0(){ public void testShiftRow0(){
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet(); HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1"); s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2"); s.createRow(3).createCell((short)0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
} }
/** /**
* When shifting rows, the page breaks should go with it * When shifting rows, the page breaks should go with it
* *
@ -167,29 +127,25 @@ public class TestSheetShiftRows extends TestCase {
HSSFRow row = s.createRow(4); HSSFRow row = s.createRow(4);
row.createCell((short)0).setCellValue("test"); row.createCell((short)0).setCellValue("test");
s.setRowBreak(4); s.setRowBreak(4);
s.shiftRows(4, 4, 2); s.shiftRows(4, 4, 2);
assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6)); assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6));
} }
public void testShiftWithComments() throws Exception { public void testShiftWithComments() throws Exception {
String filename = System.getProperty( "HSSF.testdata.path" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("comments.xls");
filename = filename + "/comments.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet sheet = wb.getSheet("Sheet1"); HSSFSheet sheet = wb.getSheet("Sheet1");
assertEquals(3, sheet.getLastRowNum()); assertEquals(3, sheet.getLastRowNum());
// Verify comments are in the position expected // Verify comments are in the position expected
assertNotNull(sheet.getCellComment(0,0)); assertNotNull(sheet.getCellComment(0,0));
assertNull(sheet.getCellComment(1,0)); assertNull(sheet.getCellComment(1,0));
assertNotNull(sheet.getCellComment(2,0)); assertNotNull(sheet.getCellComment(2,0));
assertNotNull(sheet.getCellComment(3,0)); assertNotNull(sheet.getCellComment(3,0));
String comment1 = sheet.getCellComment(0,0).getString().getString(); String comment1 = sheet.getCellComment(0,0).getString().getString();
assertEquals(comment1,"comment top row1 (index0)\n"); assertEquals(comment1,"comment top row1 (index0)\n");
String comment3 = sheet.getCellComment(2,0).getString().getString(); String comment3 = sheet.getCellComment(2,0).getString().getString();
@ -197,7 +153,7 @@ public class TestSheetShiftRows extends TestCase {
String comment4 = sheet.getCellComment(3,0).getString().getString(); String comment4 = sheet.getCellComment(3,0).getString().getString();
assertEquals(comment4,"comment top row4 (index3)\n"); assertEquals(comment4,"comment top row4 (index3)\n");
// Shifting all but first line down to test comments shifting // Shifting all but first line down to test comments shifting
sheet.shiftRows(1, sheet.getLastRowNum(), 1, true, true); sheet.shiftRows(1, sheet.getLastRowNum(), 1, true, true);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wb.write(outputStream); wb.write(outputStream);
@ -216,7 +172,7 @@ public class TestSheetShiftRows extends TestCase {
assertEquals(comment3,comment3_shifted); assertEquals(comment3,comment3_shifted);
String comment4_shifted = sheet.getCellComment(4,0).getString().getString(); String comment4_shifted = sheet.getCellComment(4,0).getString().getString();
assertEquals(comment4,comment4_shifted); assertEquals(comment4,comment4_shifted);
// Write out and read back in again // Write out and read back in again
// Ensure that the changes were persisted // Ensure that the changes were persisted
wb = new HSSFWorkbook( new ByteArrayInputStream(outputStream.toByteArray()) ); wb = new HSSFWorkbook( new ByteArrayInputStream(outputStream.toByteArray()) );
@ -235,22 +191,18 @@ public class TestSheetShiftRows extends TestCase {
comment3_shifted = sheet.getCellComment(3,0).getString().getString(); comment3_shifted = sheet.getCellComment(3,0).getString().getString();
assertEquals(comment3,comment3_shifted); assertEquals(comment3,comment3_shifted);
comment4_shifted = sheet.getCellComment(4,0).getString().getString(); comment4_shifted = sheet.getCellComment(4,0).getString().getString();
assertEquals(comment4,comment4_shifted); assertEquals(comment4,comment4_shifted);
} }
/** /**
* See bug #34023 * See bug #34023
*/ */
public void testShiftWithFormulas() throws Exception { public void testShiftWithFormulas() {
String filename = System.getProperty( "HSSF.testdata.path" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ForShifting.xls");
filename = filename + "/ForShifting.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet sheet = wb.getSheet("Sheet1"); HSSFSheet sheet = wb.getSheet("Sheet1");
assertEquals(19, sheet.getLastRowNum()); assertEquals(19, sheet.getLastRowNum());
assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString()); assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula()); assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula());
assertEquals("cell B2 (ref)", sheet.getRow(1).getCell((short)3).getRichStringCellValue().toString()); assertEquals("cell B2 (ref)", sheet.getRow(1).getCell((short)3).getRichStringCellValue().toString());
@ -259,15 +211,15 @@ public class TestSheetShiftRows extends TestCase {
assertEquals("CONCATENATE(B3,\" (ref)\")", sheet.getRow(2).getCell((short)3).getCellFormula()); assertEquals("CONCATENATE(B3,\" (ref)\")", sheet.getRow(2).getCell((short)3).getCellFormula());
assertEquals("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString()); assertEquals("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B2,\" (ref)\")", sheet.getRow(6).getCell((short)1).getCellFormula()); assertEquals("CONCATENATE(B2,\" (ref)\")", sheet.getRow(6).getCell((short)1).getCellFormula());
sheet.shiftRows(1, 1, 10); sheet.shiftRows(1, 1, 10);
// Row 1 => Row 11 // Row 1 => Row 11
// So strings on row 11 unchanged, but reference in formula is // So strings on row 11 unchanged, but reference in formula is
assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString()); assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula()); assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula());
assertEquals(0, sheet.getRow(1).getPhysicalNumberOfCells()); assertEquals(0, sheet.getRow(1).getPhysicalNumberOfCells());
// still save b2 // still save b2
assertEquals("cell B2 (ref)", sheet.getRow(11).getCell((short)3).getRichStringCellValue().toString()); assertEquals("cell B2 (ref)", sheet.getRow(11).getCell((short)3).getRichStringCellValue().toString());
// but points to b12 // but points to b12
@ -275,7 +227,7 @@ public class TestSheetShiftRows extends TestCase {
assertEquals("cell B3 (ref)", sheet.getRow(2).getCell((short)3).getRichStringCellValue().toString()); assertEquals("cell B3 (ref)", sheet.getRow(2).getCell((short)3).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B3,\" (ref)\")", sheet.getRow(2).getCell((short)3).getCellFormula()); assertEquals("CONCATENATE(B3,\" (ref)\")", sheet.getRow(2).getCell((short)3).getCellFormula());
// one on a non-shifted row also updated // one on a non-shifted row also updated
assertEquals("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString()); assertEquals("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B12,\" (ref)\")", sheet.getRow(6).getCell((short)1).getCellFormula()); assertEquals("CONCATENATE(B12,\" (ref)\")", sheet.getRow(6).getCell((short)1).getCellFormula());

View File

@ -14,43 +14,36 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import junit.framework.AssertionFailedError;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.RecordFormatException;
/** /**
* @author aviks * @author aviks
* *
* This testcase contains tests for bugs that are yet to be fixed. * This testcase contains tests for bugs that are yet to be fixed. Therefore,
* Therefore, the standard ant test target does not run these tests. * the standard ant test target does not run these tests. Run this testcase with
* Run this testcase with the single-test target. * the single-test target. The names of the tests usually correspond to the
* The names of the tests usually correspond to the Bugzilla id's * Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are
* PLEASE MOVE tests from this class to TestBugs once the bugs are fixed, * fixed, so that they are then run automatically.
* so that they are then run automatically.
*/ */
public class TestUnfixedBugs extends TestCase { public final class TestUnfixedBugs extends TestCase {
public TestUnfixedBugs(String arg0) {
super(arg0);
public void test43493() {
// Has crazy corrupt sub-records on
// a EmbeddedObjectRefSubRecord
try {
HSSFTestDataSamples.openSampleWorkbook("43493.xls");
} catch (RecordFormatException e) {
if (e.getCause().getCause() instanceof ArrayIndexOutOfBoundsException) {
throw new AssertionFailedError("Identified bug 43493");
}
throw e;
}
} }
protected String cwd = System.getProperty("HSSF.testdata.path");
public void test43493() throws Exception {
// Has crazy corrup subrecords on
// a EmbeddedObjectRefSubRecord
File f = new File(cwd, "43493.xls");
HSSFWorkbook wb = new HSSFWorkbook(
new FileInputStream(f)
);
}
} }

View File

@ -14,37 +14,33 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Tests for how HSSFWorkbook behaves with XLS files * Tests for how HSSFWorkbook behaves with XLS files
* with a WORKBOOK directory entry (instead of the more * with a WORKBOOK directory entry (instead of the more
* usual, Workbook) * usual, Workbook)
*/ */
public class TestUppercaseWorkbook extends TestCase { public final class TestUppercaseWorkbook extends TestCase {
private String dirPath;
private String xlsA = "WORKBOOK_in_capitals.xls";
protected void setUp() throws Exception { private String xlsA = "WORKBOOK_in_capitals.xls";
super.setUp();
dirPath = System.getProperty("HSSF.testdata.path");
}
/** /**
* Test that we can open a file with WORKBOOK * Test that we can open a file with WORKBOOK
*/ */
public void testOpen() throws Exception { public void testOpen() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
@ -68,7 +64,7 @@ public class TestUppercaseWorkbook extends TestCase {
* Test that when we write out, we go back to the correct case * Test that when we write out, we go back to the correct case
*/ */
public void testWrite() throws Exception { public void testWrite() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
// Open the workbook, not preserving nodes // Open the workbook, not preserving nodes
@ -96,7 +92,7 @@ public class TestUppercaseWorkbook extends TestCase {
* correct case * correct case
*/ */
public void testWritePreserve() throws Exception { public void testWritePreserve() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
// Open the workbook, not preserving nodes // Open the workbook, not preserving nodes

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,11 +14,18 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.BackupRecord; import org.apache.poi.hssf.record.BackupRecord;
import org.apache.poi.hssf.record.LabelSSTRecord; import org.apache.poi.hssf.record.LabelSSTRecord;
@ -29,12 +35,6 @@ import org.apache.poi.hssf.util.Region;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
/** /**
* Class to test Workbook functionality * Class to test Workbook functionality
* *
@ -42,10 +42,7 @@ import java.util.Iterator;
* @author Greg Merrill * @author Greg Merrill
* @author Siggi Cherem * @author Siggi Cherem
*/ */
public class TestWorkbook extends TestCase {
public class TestWorkbook
extends TestCase
{
private static final String LAST_NAME_KEY = "lastName"; private static final String LAST_NAME_KEY = "lastName";
private static final String FIRST_NAME_KEY = "firstName"; private static final String FIRST_NAME_KEY = "firstName";
private static final String SSN_KEY = "ssn"; private static final String SSN_KEY = "ssn";
@ -58,15 +55,9 @@ public class TestWorkbook
private static final String SSN_VALUE = "555555555"; private static final String SSN_VALUE = "555555555";
private SanityChecker sanityChecker = new SanityChecker(); private SanityChecker sanityChecker = new SanityChecker();
/**
* Constructor TestWorkbook
*
* @param name
*/
public TestWorkbook(String name) private static HSSFWorkbook openSample(String sampleFileName) {
{ return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
super(name);
} }
/** /**
@ -178,21 +169,12 @@ public class TestWorkbook
* *
*/ */
public void testReadSimple() public void testReadSimple() {
throws IOException HSSFWorkbook workbook = openSample("Simple.xls");
{ HSSFSheet sheet = workbook.getSheetAt(0);
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Simple.xls"; HSSFCell cell = sheet.getRow(0).getCell(0);
FileInputStream stream = new FileInputStream(filename); assertEquals(REPLACE_ME, cell .getRichStringCellValue().getString());
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0);
assertEquals(REPLACE_ME,
sheet.getRow(( short ) 0).getCell(( short ) 0)
.getStringCellValue());
stream.close();
} }
/** /**
@ -204,24 +186,15 @@ public class TestWorkbook
* *
*/ */
public void testReadSimpleWithDataFormat() public void testReadSimpleWithDataFormat() {
throws IOException HSSFWorkbook workbook = openSample("SimpleWithDataFormat.xls");
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithDataFormat.xls";
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFDataFormat format = workbook.createDataFormat(); HSSFDataFormat format = workbook.createDataFormat();
HSSFCell cell = HSSFCell cell = sheet.getRow(0).getCell(0);
sheet.getRow(( short ) 0).getCell(( short ) 0);
assertEquals(1.25,cell.getNumericCellValue(), 1e-10); assertEquals(1.25,cell.getNumericCellValue(), 1e-10);
assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0"); assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0");
stream.close();
} }
/** /**
@ -236,23 +209,23 @@ public class TestWorkbook
public void testWriteDataFormat() public void testWriteDataFormat()
throws IOException throws IOException
{ {
File file = TempFile.createTempFile("testWriteDataFormat", File file = TempFile.createTempFile("testWriteDataFormat",
".xls"); ".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
HSSFDataFormat format = wb.createDataFormat(); HSSFDataFormat format = wb.createDataFormat();
HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs = wb.createCellStyle();
short df = format.getFormat("0.0"); short df = format.getFormat("0.0");
cs.setDataFormat(df); cs.setDataFormat(df);
r = s.createRow((short)0); r = s.createRow((short)0);
c = r.createCell((short)0); c = r.createCell((short)0);
c.setCellStyle(cs); c.setCellStyle(cs);
c.setCellValue(1.25); c.setCellValue(1.25);
wb.write(out); wb.write(out);
out.close(); out.close();
@ -261,16 +234,16 @@ public class TestWorkbook
POIFSFileSystem fs = new POIFSFileSystem(stream); POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs); HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell = HSSFCell cell =
sheet.getRow(( short ) 0).getCell(( short ) 0); sheet.getRow(( short ) 0).getCell(( short ) 0);
format = workbook.createDataFormat(); format = workbook.createDataFormat();
assertEquals(1.25,cell.getNumericCellValue(), 1e-10); assertEquals(1.25,cell.getNumericCellValue(), 1e-10);
assertEquals(format.getFormat(df), "0.0"); assertEquals(format.getFormat(df), "0.0");
assertEquals(format, workbook.createDataFormat());
assertEquals(format, workbook.createDataFormat());
stream.close(); stream.close();
} }
@ -283,30 +256,14 @@ public class TestWorkbook
* *
*/ */
public void testReadEmployeeSimple() public void testReadEmployeeSimple() {
throws IOException HSSFWorkbook workbook = openSample("Employee.xls");
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Employee.xls";
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
assertEquals(EMPLOYEE_INFORMATION, assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getStringCellValue());
sheet.getRow(1).getCell(( short ) 1) assertEquals(LAST_NAME_KEY, sheet.getRow(3).getCell(2).getStringCellValue());
.getStringCellValue()); assertEquals(FIRST_NAME_KEY, sheet.getRow(4).getCell(2).getStringCellValue());
assertEquals(LAST_NAME_KEY, assertEquals(SSN_KEY, sheet.getRow(5).getCell(2).getStringCellValue());
sheet.getRow(3).getCell(( short ) 2)
.getStringCellValue());
assertEquals(FIRST_NAME_KEY,
sheet.getRow(4).getCell(( short ) 2)
.getStringCellValue());
assertEquals(SSN_KEY,
sheet.getRow(5).getCell(( short ) 2)
.getStringCellValue());
stream.close();
} }
/** /**
@ -322,33 +279,17 @@ public class TestWorkbook
* *
*/ */
public void testModifySimple() public void testModifySimple() {
throws IOException HSSFWorkbook workbook = openSample("Simple.xls");
{ HSSFSheet sheet = workbook.getSheetAt(0);
String filename = System.getProperty("HSSF.testdata.path"); HSSFCell cell = sheet.getRow(0).getCell(0);
filename = filename + "/Simple.xls"; cell.setCellValue(new HSSFRichTextString(REPLACED));
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell =
sheet.getRow(( short ) 0).getCell(( short ) 0);
cell.setCellValue(REPLACED); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
File destination = TempFile.createTempFile("SimpleResult",
".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream);
instream.close();
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
cell = sheet.getRow(( short ) 0).getCell(( short ) 0); cell = sheet.getRow(0).getCell(0);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getRichStringCellValue().getString());
instream.close();
} }
/** /**
@ -364,42 +305,26 @@ public class TestWorkbook
* or is incorrect. <P> * or is incorrect. <P>
* *
*/ */
public void testModifySimpleWithSkip() {
public void testModifySimpleWithSkip() HSSFWorkbook workbook = openSample("SimpleWithSkip.xls");
throws IOException HSSFSheet sheet = workbook.getSheetAt(0);
{ HSSFCell cell = sheet.getRow(0).getCell(1);
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithSkip.xls";
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell =
sheet.getRow(( short ) 0).getCell(( short ) 1);
cell.setCellValue(REPLACED); cell.setCellValue(REPLACED);
cell = sheet.getRow(( short ) 1).getCell(( short ) 0); cell = sheet.getRow(1).getCell(0);
cell.setCellValue(REPLACED); cell.setCellValue(REPLACED);
File destination =
TempFile.createTempFile("SimpleWithSkipResult", ".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
instream.close();
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
cell = sheet.getRow(( short ) 0).getCell(( short ) 1); cell = sheet.getRow(0).getCell(1);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getStringCellValue());
cell = sheet.getRow(( short ) 0).getCell(( short ) 0); cell = sheet.getRow(0).getCell(0);
assertEquals(DO_NOT_REPLACE, cell.getStringCellValue()); assertEquals(DO_NOT_REPLACE, cell.getStringCellValue());
cell = sheet.getRow(( short ) 1).getCell(( short ) 0); cell = sheet.getRow(1).getCell(0);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getStringCellValue());
cell = sheet.getRow(( short ) 1).getCell(( short ) 1); cell = sheet.getRow(1).getCell(1);
assertEquals(DO_NOT_REPLACE, cell.getStringCellValue()); assertEquals(DO_NOT_REPLACE, cell.getStringCellValue());
instream.close();
} }
/** /**
@ -415,41 +340,26 @@ public class TestWorkbook
* is incorrect or has not been replaced. <P> * is incorrect or has not been replaced. <P>
* *
*/ */
public void testModifySimpleWithStyling() {
public void testModifySimpleWithStyling() HSSFWorkbook workbook = openSample("SimpleWithStyling.xls");
throws IOException
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithStyling.xls";
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
for (int k = 0; k < 4; k++) for (int k = 0; k < 4; k++)
{ {
HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0); HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0);
cell.setCellValue(REPLACED); cell.setCellValue(new HSSFRichTextString(REPLACED));
} }
File destination =
TempFile.createTempFile("SimpleWithStylingResult", ".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream);
instream.close(); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
for (int k = 0; k < 4; k++) for (int k = 0; k < 4; k++)
{ {
HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0); HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getRichStringCellValue().getString());
} }
instream.close();
} }
/** /**
@ -465,48 +375,23 @@ public class TestWorkbook
* is incorrect or has not been replaced. <P> * is incorrect or has not been replaced. <P>
* *
*/ */
public void testModifyEmployee() {
public void testModifyEmployee() HSSFWorkbook workbook = openSample("Employee.xls");
throws IOException
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Employee.xls";
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell = HSSFCell cell = sheet.getRow(3).getCell(2);
sheet.getRow(( short ) 3).getCell(( short ) 2);
cell.setCellValue(LAST_NAME_VALUE); cell.setCellValue(LAST_NAME_VALUE);
cell = sheet.getRow(( short ) 4).getCell(( short ) 2); cell = sheet.getRow(4).getCell(2);
cell.setCellValue(FIRST_NAME_VALUE); cell.setCellValue(FIRST_NAME_VALUE);
cell = sheet.getRow(( short ) 5).getCell(( short ) 2); cell = sheet.getRow(5).getCell(2);
cell.setCellValue(SSN_VALUE); cell.setCellValue(SSN_VALUE);
File destination = TempFile.createTempFile("EmployeeResult",
".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
instream.close();
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
assertEquals(EMPLOYEE_INFORMATION, assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getStringCellValue());
sheet.getRow(1).getCell(( short ) 1) assertEquals(LAST_NAME_VALUE, sheet.getRow(3).getCell(2).getStringCellValue());
.getStringCellValue()); assertEquals(FIRST_NAME_VALUE, sheet.getRow(4).getCell(2).getStringCellValue());
assertEquals(LAST_NAME_VALUE, assertEquals(SSN_VALUE, sheet.getRow(5).getCell(2).getStringCellValue());
sheet.getRow(3).getCell(( short ) 2)
.getStringCellValue());
assertEquals(FIRST_NAME_VALUE,
sheet.getRow(4).getCell(( short ) 2)
.getStringCellValue());
assertEquals(SSN_VALUE,
sheet.getRow(5).getCell(( short ) 2)
.getStringCellValue());
instream.close();
} }
/** /**
@ -517,21 +402,10 @@ public class TestWorkbook
* FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly indentifies the cell<P> * FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly indentifies the cell<P>
* *
*/ */
public void testReadSheetWithRK() {
public void testReadSheetWithRK() HSSFWorkbook h = openSample("rk.xls");
throws IOException
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/rk.xls";
// a.xls has a value on position (0,0)
FileInputStream in = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook h = new HSSFWorkbook(fs);
HSSFSheet s = h.getSheetAt(0); HSSFSheet s = h.getSheetAt(0);
HSSFRow r = s.getRow(0); HSSFCell c = s.getRow(0).getCell(0);
HSSFCell c = r.getCell(( short ) 0);
int a = c.getCellType(); int a = c.getCellType();
assertEquals(a, c.CELL_TYPE_NUMERIC); assertEquals(a, c.CELL_TYPE_NUMERIC);
@ -564,7 +438,6 @@ public class TestWorkbook
{ {
r = s.createRow(rownum); r = s.createRow(rownum);
// r.setRowNum(( short ) rownum);
for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2) for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2)
{ {
c = r.createCell(cellnum); c = r.createCell(cellnum);
@ -572,7 +445,7 @@ public class TestWorkbook
+ ((( double ) rownum / 1000) + ((( double ) rownum / 1000)
+ (( double ) cellnum / 10000))); + (( double ) cellnum / 10000)));
c = r.createCell(( short ) (cellnum + 1)); c = r.createCell(( short ) (cellnum + 1));
c.setCellValue("TEST"); c.setCellValue(new HSSFRichTextString("TEST"));
} }
} }
s.addMergedRegion(new Region(( short ) 0, ( short ) 0, ( short ) 10, s.addMergedRegion(new Region(( short ) 0, ( short ) 0, ( short ) 10,
@ -632,7 +505,7 @@ public class TestWorkbook
HSSFRow row = sheet.createRow(( short ) 2); HSSFRow row = sheet.createRow(( short ) 2);
HSSFCell cell = row.createCell(( short ) 1); HSSFCell cell = row.createCell(( short ) 1);
cell.setCellValue("Class"); cell.setCellValue(new HSSFRichTextString("Class"));
cell = row.createCell(( short ) 2); cell = row.createCell(( short ) 2);
// workbook.write(new FileOutputStream("/a2.xls")); // workbook.write(new FileOutputStream("/a2.xls"));
@ -687,49 +560,35 @@ public class TestWorkbook
in.close(); in.close();
file.deleteOnExit(); file.deleteOnExit();
} }
/** /**
* Generate a file to visually/programmatically verify repeating rows and cols made it * Generate a file to visually/programmatically verify repeating rows and cols made it
*/ */
public void testRepeatingColsRows() throws IOException public void testRepeatingColsRows() throws IOException
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Titles"); HSSFSheet sheet = workbook.createSheet("Test Print Titles");
String sheetName = workbook.getSheetName(0);
HSSFRow row = sheet.createRow(0);
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short)1);
HSSFCell cell = row.createCell((short)1); cell.setCellValue(new HSSFRichTextString("hi"));
cell.setCellValue("hi");
workbook.setRepeatingRowsAndColumns(0, 0, 1, 0, 0);
workbook.setRepeatingRowsAndColumns(0, 0, 1, 0, 0);
File file = TempFile.createTempFile("testPrintTitles",".xls");
File file = TempFile.createTempFile("testPrintTitles",".xls");
FileOutputStream fileOut = new FileOutputStream(file);
FileOutputStream fileOut = new FileOutputStream(file); workbook.write(fileOut);
workbook.write(fileOut); fileOut.close();
fileOut.close();
assertTrue("file exists",file.exists());
assertTrue("file exists",file.exists());
} }
public static void main(String [] ignored_args) public static void main(String [] ignored_args)
{ {
String filename = System.getProperty("HSSF.testdata.path");
// assume this is relative to basedir
if (filename == null)
{
System.setProperty(
"HSSF.testdata.path",
"src/testcases/org/apache/poi/hssf/data");
}
System.out
.println("Testing org.apache.poi.hssf.usermodel.HSSFWorkbook");
junit.textui.TestRunner.run(TestWorkbook.class); junit.textui.TestRunner.run(TestWorkbook.class);
} }
} }

View File

@ -14,24 +14,29 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.util; package org.apache.poi.hssf.util;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.NameRecord;
import org.apache.poi.hssf.record.formula.MemFuncPtg;
import org.apache.poi.hssf.record.formula.Area3DPtg;
import org.apache.poi.hssf.record.formula.UnionPtg;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.NameRecord;
import org.apache.poi.hssf.record.formula.Area3DPtg;
import org.apache.poi.hssf.record.formula.MemFuncPtg;
import org.apache.poi.hssf.record.formula.UnionPtg;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFName;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
*
*/
public final class TestAreaReference extends TestCase { public final class TestAreaReference extends TestCase {
public void testAreaRef1() { public void testAreaRef1() {
@ -99,7 +104,7 @@ public final class TestAreaReference extends TestCase {
TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7"); TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7");
} }
private static class HSSFWB extends HSSFWorkbook { private static final class HSSFWB extends HSSFWorkbook {
public HSSFWB(InputStream in) throws IOException { public HSSFWB(InputStream in) throws IOException {
super(in); super(in);
} }
@ -182,12 +187,9 @@ public final class TestAreaReference extends TestCase {
} }
public void testDiscontinousReference() throws Exception { public void testDiscontinousReference() throws Exception {
String filename = System.getProperty( "HSSF.testdata.path" ); InputStream is = HSSFTestDataSamples.openSampleFileStream("44167.xls");
filename = filename + "/44167.xls"; HSSFWB wb = new HSSFWB(is);
FileInputStream fin = new FileInputStream( filename );
HSSFWB wb = new HSSFWB( fin );
Workbook workbook = wb.getWorkbook(); Workbook workbook = wb.getWorkbook();
fin.close();
assertEquals(1, wb.getNumberOfNames()); assertEquals(1, wb.getNumberOfNames());
String sheetName = "Tabelle1"; String sheetName = "Tabelle1";
@ -269,5 +271,4 @@ public final class TestAreaReference extends TestCase {
public static void main(String[] args) { public static void main(String[] args) {
junit.textui.TestRunner.run(TestAreaReference.class); junit.textui.TestRunner.run(TestAreaReference.class);
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,58 +14,56 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Class to test that POIFS complains when given an Office 2007 XML document * Class to test that POIFS complains when given an Office 2007 XML document
* *
* @author Marc Johnson * @author Marc Johnson
*/ */
public class TestOffice2007XMLException extends TestCase {
public class TestOffice2007XMLException extends TestCase private static final InputStream openSampleStream(String sampleFileName) {
{ return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
public String dirname;
public void setUp() {
dirname = System.getProperty("HSSF.testdata.path");
} }
public void testXMLException() throws IOException public void testXMLException() throws IOException
{ {
FileInputStream in = new FileInputStream(dirname + "/sample.xlsx"); InputStream in = openSampleStream("sample.xlsx");
try { try {
new POIFSFileSystem(in); new POIFSFileSystem(in);
fail(); fail("expected exception was not thrown");
} catch(OfficeXmlFileException e) { } catch(OfficeXmlFileException e) {
// Good // expected during successful test
assertTrue(e.getMessage().indexOf("POI only supports OLE2 Office documents") > 0);
} }
} }
public void testDetectAsPOIFS() throws IOException { public void testDetectAsPOIFS() {
InputStream in;
// ooxml file isn't // ooxml file isn't
in = new PushbackInputStream( confirmIsPOIFS("SampleSS.xlsx", false);
new FileInputStream(dirname + "/SampleSS.xlsx"), 10
);
assertFalse(POIFSFileSystem.hasPOIFSHeader(in));
// xls file is // xls file is
in = new PushbackInputStream( confirmIsPOIFS("SampleSS.xls", true);
new FileInputStream(dirname + "/SampleSS.xls"), 10
);
assertTrue(POIFSFileSystem.hasPOIFSHeader(in));
// text file isn't // text file isn't
in = new PushbackInputStream( confirmIsPOIFS("SampleSS.txt", false);
new FileInputStream(dirname + "/SampleSS.txt"), 10 }
); private void confirmIsPOIFS(String sampleFileName, boolean expectedResult) {
assertFalse(POIFSFileSystem.hasPOIFSHeader(in)); InputStream in = new PushbackInputStream(openSampleStream(sampleFileName), 10);
boolean actualResult;
try {
actualResult = POIFSFileSystem.hasPOIFSHeader(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(expectedResult, actualResult);
} }
} }

View File

@ -17,14 +17,13 @@
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests for POIFSFileSystem * Tests for POIFSFileSystem
* *
@ -32,10 +31,6 @@ import junit.framework.TestCase;
*/ */
public final class TestPOIFSFileSystem extends TestCase { public final class TestPOIFSFileSystem extends TestCase {
public TestPOIFSFileSystem(String testName) {
super(testName);
}
/** /**
* Mock exception used to ensure correct error handling * Mock exception used to ensure correct error handling
*/ */
@ -121,16 +116,7 @@ public final class TestPOIFSFileSystem extends TestCase {
} }
private static InputStream openSampleStream(String sampleName) { private static InputStream openSampleStream(String sampleFileName) {
String dataDirName = System.getProperty("HSSF.testdata.path"); return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
if(dataDirName == null) {
throw new RuntimeException("Missing system property '" + "HSSF.testdata.path" + "'");
}
File f = new File(dataDirName + "/" + sampleName);
try {
return new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException("Sample file '" + f.getAbsolutePath() + "' not found");
}
} }
} }

View File

@ -18,12 +18,21 @@
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import junit.framework.TestCase; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import junit.framework.ComparisonFailure; import junit.framework.ComparisonFailure;
import junit.framework.TestCase;
import java.io.*; import org.apache.poi.hssf.HSSFTestDataSamples;
import java.util.*;
import org.apache.poi.poifs.property.DirectoryProperty; import org.apache.poi.poifs.property.DirectoryProperty;
import org.apache.poi.poifs.property.Property; import org.apache.poi.poifs.property.Property;
@ -36,45 +45,46 @@ import org.apache.poi.poifs.property.Property;
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public class TestPropertySorter extends TestCase { public final class TestPropertySorter extends TestCase {
//the correct order of entries in the test file //the correct order of entries in the test file
protected static final String[] _entries = { private static final String[] _entries = {
"dir", "JML", "UTIL", "Loader", "Sheet1", "Sheet2", "Sheet3", "dir", "JML", "UTIL", "Loader", "Sheet1", "Sheet2", "Sheet3",
"__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5", "__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5",
"ThisWorkbook", "_VBA_PROJECT", "ThisWorkbook", "_VBA_PROJECT",
}; };
protected File testFile; private static POIFSFileSystem openSampleFS() {
InputStream is = HSSFTestDataSamples.openSampleFileStream("39234.xls");
public void setUp(){ try {
String home = System.getProperty("HSSF.testdata.path"); return new POIFSFileSystem(is);
testFile = new File(home + "/39234.xls"); } catch (IOException e) {
throw new RuntimeException(e);
}
} }
/** /**
* Test sorting of properties in <code>DirectoryProperty</code> * Test sorting of properties in <code>DirectoryProperty</code>
*/ */
public void testSortProperties() throws IOException { public void testSortProperties() throws IOException {
InputStream is = new FileInputStream(testFile); POIFSFileSystem fs = openSampleFS();
POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
Property[] props = getVBAProperties(fs); Property[] props = getVBAProperties(fs);
assertEquals(_entries.length, props.length); assertEquals(_entries.length, props.length);
// (1). See that there is a problem with the old case-sensitive property comparartor // (1). See that there is a problem with the old case-sensitive property comparator
Arrays.sort(props, new CaseSensitivePropertyComparator()); Arrays.sort(props, OldCaseSensitivePropertyComparator);
try { try {
for (int i = 0; i < props.length; i++) { for (int i = 0; i < props.length; i++) {
assertEquals(_entries[i], props[i].getName()); assertEquals(_entries[i], props[i].getName());
} }
fail("case-sensitive property comparator returns properties in wrong order"); fail("expected old case-sensitive property comparator to return properties in wrong order");
} catch (ComparisonFailure e){ } catch (ComparisonFailure e){
; // as expected // expected during successful test
assertNotNull(e.getMessage());
} }
// (2) Verify that the fixed proeprty comparator works right // (2) Verify that the fixed property comparator works right
Arrays.sort(props, new DirectoryProperty.PropertyComparator()); Arrays.sort(props, new DirectoryProperty.PropertyComparator());
for (int i = 0; i < props.length; i++) { for (int i = 0; i < props.length; i++) {
assertEquals(_entries[i], props[i].getName()); assertEquals(_entries[i], props[i].getName());
@ -85,14 +95,12 @@ public class TestPropertySorter extends TestCase {
* Serialize file system and verify that the order of properties is the same as in the original file. * Serialize file system and verify that the order of properties is the same as in the original file.
*/ */
public void testSerialization() throws IOException { public void testSerialization() throws IOException {
InputStream is = new FileInputStream(testFile); POIFSFileSystem fs = openSampleFS();
POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
fs.writeFilesystem(out); fs.writeFilesystem(out);
out.close(); out.close();
is = new ByteArrayInputStream(out.toByteArray()); InputStream is = new ByteArrayInputStream(out.toByteArray());
fs = new POIFSFileSystem(is); fs = new POIFSFileSystem(is);
is.close(); is.close();
Property[] props = getVBAProperties(fs); Property[] props = getVBAProperties(fs);
@ -128,26 +136,17 @@ public class TestPropertySorter extends TestCase {
/** /**
* Old version of case-sensitive PropertyComparator to demonstrate the problem * Old version of case-sensitive PropertyComparator to demonstrate the problem
*/ */
private class CaseSensitivePropertyComparator implements Comparator private static final Comparator OldCaseSensitivePropertyComparator = new Comparator() {
{
public boolean equals(Object o) public int compare(Object o1, Object o2) {
{
return this == o;
}
public int compare(Object o1, Object o2)
{
String name1 = (( Property ) o1).getName(); String name1 = (( Property ) o1).getName();
String name2 = (( Property ) o2).getName(); String name2 = (( Property ) o2).getName();
int result = name1.length() - name2.length(); int result = name1.length() - name2.length();
if (result == 0) if (result == 0) {
{
result = name1.compareTo(name2); result = name1.compareTo(name2);
} }
return result; return result;
} }
} };
} }