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! -->
<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="add">Implement Sheet.removeShape(Shape shape) in HSLF</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! -->
<changes>
<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="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>

View File

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

View File

@ -15,17 +15,17 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi;
import junit.framework.TestCase;
import java.io.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.*;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
* 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)
*/
public class TestPOIDocumentMain extends TestCase {
public final class TestPOIDocumentMain extends TestCase {
// The POI Documents to work on
private POIDocument doc;
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
* a Word Document for our testing
* Set things up, two spreadsheets for our testing
*/
public void setUp() throws Exception {
String dirnameHSSF = System.getProperty("HSSF.testdata.path");
String filenameHSSF = dirnameHSSF + "/DateFormats.xls";
String filenameHSSF2 = dirnameHSSF + "/StringFormulas.xls";
public void setUp() {
FileInputStream fisHSSF = new FileInputStream(filenameHSSF);
pfs = new POIFSFileSystem(fisHSSF);
doc = new HSSFWorkbook(pfs);
FileInputStream fisHSSF2 = new FileInputStream(filenameHSSF2);
pfs2 = new POIFSFileSystem(fisHSSF2);
doc2 = new HSSFWorkbook(pfs2);
doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls");
}
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 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 {
// Just check we can write them back out into a filesystem
POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties();
doc.writeProperties(outFS);
// Should now hold them
assertNotNull(
outFS.createDocumentInputStream("\005SummaryInformation")
);
assertNotNull(
outFS.createDocumentInputStream("\005DocumentSummaryInformation")
);
}
public void testWriteProperties() throws Exception {
// Just check we can write them back out into a filesystem
POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties();
doc.writeProperties(outFS);
// Should now hold them
assertNotNull(
outFS.createDocumentInputStream("\005SummaryInformation")
);
assertNotNull(
outFS.createDocumentInputStream("\005DocumentSummaryInformation")
);
}
public void testWriteReadProperties() throws Exception {
public void testWriteReadProperties() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Write them out
POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties();
doc.writeProperties(outFS);
outFS.writeFilesystem(baos);
// Create a new version
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
POIFSFileSystem inFS = new POIFSFileSystem(bais);
// Check they're still there
doc.filesystem = inFS;
doc.readProperties();
// Delegate test
testReadProperties();
}
// Write them out
POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties();
doc.writeProperties(outFS);
outFS.writeFilesystem(baos);
// Create a new version
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
POIFSFileSystem inFS = new POIFSFileSystem(bais);
// Check they're still there
doc.filesystem = inFS;
doc.readProperties();
// Delegate test
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;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
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.DVRecord;
import org.apache.poi.hssf.record.EOFRecord;
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.WindowTwoRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.TestCase;
public class TestHSSFEventFactory extends TestCase {
private String dirname;
/**
*
*/
public final class TestHSSFEventFactory extends TestCase {
public TestHSSFEventFactory() {
dirname = System.getProperty("HSSF.testdata.path");
private static final InputStream openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
}
public void testWithMissingRecords() throws Exception {
File f = new File(dirname + "/SimpleWithSkip.xls");
HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f));
POIFSFileSystem fs = new POIFSFileSystem(openSample("SimpleWithSkip.xls"));
HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs);
Record[] recs = mockListen.getRecords();
// Check we got the records
System.out.println("Processed, found " + mockListen.records.size() + " records");
assertTrue( mockListen.records.size() > 100 );
assertTrue( recs.length > 100 );
// Check that the last few records are as we expect
// (Makes sure we don't accidently skip the end ones)
int numRec = mockListen.records.size();
assertEquals(WindowTwoRecord.class, mockListen.records.get(numRec-3).getClass());
assertEquals(SelectionRecord.class, mockListen.records.get(numRec-2).getClass());
assertEquals(EOFRecord.class, mockListen.records.get(numRec-1).getClass());
int numRec = recs.length;
assertEquals(WindowTwoRecord.class, recs[numRec-3].getClass());
assertEquals(SelectionRecord.class, recs[numRec-2].getClass());
assertEquals(EOFRecord.class, recs[numRec-1].getClass());
}
public void testWithCrazyContinueRecords() throws Exception {
// Some files have crazy ordering of their continue records
// Check that we don't break on them (bug #42844)
File f = new File(dirname + "/ContinueRecordProblem.xls");
HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f));
POIFSFileSystem fs = new POIFSFileSystem(openSample("ContinueRecordProblem.xls"));
HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs);
Record[] recs = mockListen.getRecords();
// Check we got the records
System.out.println("Processed, found " + mockListen.records.size() + " records");
assertTrue( mockListen.records.size() > 100 );
assertTrue( recs.length > 100 );
// And none of them are continue ones
Record[] r = (Record[])mockListen.records.toArray(
new Record[mockListen.records.size()] );
for(int i=0; i<r.length; i++) {
assertFalse( r[i] instanceof ContinueRecord );
for(int i=0; i<recs.length; i++) {
assertFalse( recs[i] instanceof ContinueRecord );
}
// Check that the last few records are as we expect
// (Makes sure we don't accidently skip the end ones)
int numRec = mockListen.records.size();
assertEquals(DVALRecord.class, mockListen.records.get(numRec-3).getClass());
assertEquals(DVRecord.class, mockListen.records.get(numRec-2).getClass());
assertEquals(EOFRecord.class, mockListen.records.get(numRec-1).getClass());
int numRec = recs.length;
assertEquals(DVALRecord.class, recs[numRec-3].getClass());
assertEquals(DVRecord.class, recs[numRec-2].getClass());
assertEquals(EOFRecord.class, recs[numRec-1].getClass());
}
/**
* Unknown records can be continued.
* Check that HSSFEventFactory doesn't break on them.
* (the test file was provided in a reopen of bug #42844)
*/
public void testUnknownContinueRecords() throws Exception {
File f = new File(dirname + "/42844.xls");
/**
* Unknown records can be continued.
* Check that HSSFEventFactory doesn't break on them.
* (the test file was provided in a reopen of bug #42844)
*/
public void testUnknownContinueRecords() throws Exception {
HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen);
HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f));
HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs);
POIFSFileSystem fs = new POIFSFileSystem(openSample("42844.xls"));
HSSFEventFactory factory = new HSSFEventFactory();
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 MockHSSFListener() {}
private ArrayList records = new ArrayList();
private final List records = new ArrayList();
public MockHSSFListener() {}
public Record[] getRecords() {
Record[] result = new Record[records.size()];
records.toArray(result);
return result;
}
public void processRecord(Record record) {
records.add(record);

View File

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

View File

@ -14,21 +14,36 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.extractor;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
public class TestExcelExtractor extends TestCase {
public void testSimple() throws Exception {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "Simple.xls");
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*
*/
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());
@ -37,11 +52,9 @@ public class TestExcelExtractor extends TestCase {
assertEquals("replaceMe\n", extractor.getText());
}
public void testNumericFormula() throws Exception {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "sumifformula.xls");
public void testNumericFormula() {
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin));
ExcelExtractor extractor = createExtractor("sumifformula.xls");
assertEquals(
"Sheet1\n" +
@ -68,11 +81,9 @@ public class TestExcelExtractor extends TestCase {
);
}
public void testwithContinueRecords() throws Exception {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "StringContinueRecords.xls");
public void testwithContinueRecords() {
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin));
ExcelExtractor extractor = createExtractor("StringContinueRecords.xls");
extractor.getText();
@ -82,11 +93,9 @@ public class TestExcelExtractor extends TestCase {
assertTrue(extractor.getText().length() > 40960);
}
public void testStringConcat() throws Exception {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "SimpleWithFormula.xls");
public void testStringConcat() {
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin));
ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls");
// Comes out as NaN if treated as a number
// 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());
}
public void testStringFormula() throws Exception {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "StringFormulas.xls");
public void testStringFormula() {
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin));
ExcelExtractor extractor = createExtractor("StringFormulas.xls");
// Comes out as NaN if treated as a number
// 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
contributor license agreements. See the NOTICE file distributed with
@ -15,36 +14,28 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.record;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.InputStream;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
public class TestBOFRecord extends TestCase
{
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
public TestBOFRecord()
{
super();
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "bug_42794.xls";
}
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
*
*/
public final class TestBOFRecord extends TestCase {
public void testBOFRecord() throws Exception {
POIFSFileSystem fs = new POIFSFileSystem(
new FileInputStream(_test_file_path)
);
// This used to throw an error before
HSSFWorkbook hssf = new HSSFWorkbook(fs);
InputStream is = HSSFTestDataSamples.openSampleFileStream("bug_42794.xls");
// This used to throw an error before
try {
new HSSFWorkbook(is);
} 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
contributor license agreements. See the NOTICE file distributed with
@ -15,65 +14,57 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.record;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
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 java.util.List;
import junit.framework.TestCase;
public class TestChartTitleFormatRecord extends TestCase
{
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
import org.apache.poi.hssf.HSSFTestDataSamples;
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.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*
*/
public final class TestChartTitleFormatRecord extends TestCase {
public TestChartTitleFormatRecord()
{
super();
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "WithFormattedGraphTitle.xls";
}
public void testRecord() throws Exception {
POIFSFileSystem fs = new POIFSFileSystem(
new FileInputStream(_test_file_path)
);
// Check we can open the file via usermodel
HSSFWorkbook hssf = new HSSFWorkbook(fs);
// Now process it through eventusermodel, and
// look out for the title records
ChartTitleFormatRecordGrabber grabber =
new ChartTitleFormatRecordGrabber();
InputStream din = fs.createDocumentInputStream("Workbook");
HSSFRequest req = new HSSFRequest();
req.addListenerForAllRecords(grabber);
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, din);
din.close();
// Should've found one
assertEquals(1, grabber.chartTitleFormatRecords.size());
// And it should be of something interesting
ChartTitleFormatRecord r =
(ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0);
assertEquals(3, r.getFormatCount());
}
public static class ChartTitleFormatRecordGrabber implements HSSFListener {
private ArrayList chartTitleFormatRecords = new ArrayList();
public void testRecord() throws Exception {
POIFSFileSystem fs = new POIFSFileSystem(
HSSFTestDataSamples.openSampleFileStream("WithFormattedGraphTitle.xls"));
// Check we can open the file via usermodel
HSSFWorkbook hssf = new HSSFWorkbook(fs);
// Now process it through eventusermodel, and
// look out for the title records
ChartTitleFormatRecordGrabber grabber = new ChartTitleFormatRecordGrabber();
InputStream din = fs.createDocumentInputStream("Workbook");
HSSFRequest req = new HSSFRequest();
req.addListenerForAllRecords(grabber);
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, din);
din.close();
// Should've found one
assertEquals(1, grabber.chartTitleFormatRecords.size());
// And it should be of something interesting
ChartTitleFormatRecord r =
(ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0);
assertEquals(3, r.getFormatCount());
}
private static final class ChartTitleFormatRecordGrabber implements HSSFListener {
private final List chartTitleFormatRecords;
public ChartTitleFormatRecordGrabber() {
chartTitleFormatRecords = new ArrayList();
}
public void processRecord(Record record) {
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
contributor license agreements. See the NOTICE file distributed with
@ -15,8 +14,6 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.record;
@ -39,36 +36,29 @@ import junit.framework.TestCase;
*
* @author Andrew C. Oliver
*/
public class TestFormulaRecord
extends TestCase
{
public final class TestFormulaRecord extends TestCase {
public TestFormulaRecord(String name)
{
super(name);
}
public void testCreateFormulaRecord () {
FormulaRecord record = new FormulaRecord();
record.setColumn((short)0);
//record.setRow((short)1);
record.setRow(1);
record.setXFIndex((short)4);
assertEquals(record.getColumn(),(short)0);
//assertEquals(record.getRow(),(short)1);
assertEquals((short)record.getRow(),(short)1);
assertEquals(record.getXFIndex(),(short)4);
}
/**
* Make sure a NAN value is preserved
* This formula record is a representation of =1/0 at row 0, column 0
*/
public void testCheckNanPreserve() {
byte[] formulaByte = new byte[29];
for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0;
formulaByte[4] = (byte)0x0F;
public void testCreateFormulaRecord () {
FormulaRecord record = new FormulaRecord();
record.setColumn((short)0);
//record.setRow((short)1);
record.setRow(1);
record.setXFIndex((short)4);
assertEquals(record.getColumn(),(short)0);
//assertEquals(record.getRow(),(short)1);
assertEquals((short)record.getRow(),(short)1);
assertEquals(record.getXFIndex(),(short)4);
}
/**
* Make sure a NAN value is preserved
* This formula record is a representation of =1/0 at row 0, column 0
*/
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[8] = (byte)0x07;
formulaByte[12] = (byte)0xFF;
@ -80,7 +70,7 @@ public class TestFormulaRecord
formulaByte[23] = (byte)0x01;
formulaByte[25] = (byte)0x1E;
formulaByte[28] = (byte)0x06;
FormulaRecord record = new FormulaRecord(new TestcaseRecordInputStream(FormulaRecord.sid, (short)29, formulaByte));
assertEquals("Row", 0, record.getRow());
assertEquals("Column", 0, record.getColumn());
@ -92,19 +82,18 @@ public class TestFormulaRecord
for (int i = 5; i < 13;i++) {
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;
formulaByte[4] =(byte)0x0F;
formulaByte[4] =(byte)0x0F;
formulaByte[14]=(byte)0x08;
formulaByte[18]=(byte)0xE0;
formulaByte[19]=(byte)0xFD;
@ -115,19 +104,19 @@ public class TestFormulaRecord
assertEquals("Column", 0, record.getColumn());
byte[] output = record.serialize();
assertEquals("Output size", 31, output.length); //includes sid+recordlength
assertEquals("Offset 22", 1, output[26]);
}
public void testWithConcat() throws Exception {
// =CHOOSE(2,A2,A3,A4)
byte[] data = new byte[] {
6, 0, 68, 0,
1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57,
assertEquals("Offset 22", 1, output[26]);
}
public void testWithConcat() throws Exception {
// =CHOOSE(2,A2,A3,A4)
byte[] data = new byte[] {
6, 0, 68, 0,
1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57,
64, 0, 0, 12, 0, 12, -4, 46, 0,
30, 2, 0, // Int - 2
30, 2, 0, // Int - 2
25, 4, 3, 0, // Attr
8, 0, // Concat
17, 0, // Range
8, 0, // Concat
17, 0, // Range
26, 0, 35, 0, // Bit like an attr
36, 1, 0, 0, -64, // Ref - A2
25, 8, 21, 0, // Attr
@ -136,43 +125,35 @@ public class TestFormulaRecord
36, 3, 0, 0, -64, // Ref - A4
25, 8, 3, 0, // Attr
66, 4, 100, 0 // CHOOSE
};
RecordInputStream inp = new RecordInputStream(
new ByteArrayInputStream(data)
);
inp.nextRecord();
FormulaRecord fr = new FormulaRecord(inp);
assertEquals(14, fr.getNumberOfExpressionTokens());
assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass());
assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass());
assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass());
assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass());
FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13);
assertEquals("CHOOSE", choose.getName());
}
public static void main(String [] ignored_args)
{
String filename = System.getProperty("HSSF.testdata.path");
System.out
.println("Testing org.apache.poi.hssf.record.FormulaRecord");
junit.textui.TestRunner.run(TestFormulaRecord.class);
}
};
RecordInputStream inp = new RecordInputStream(
new ByteArrayInputStream(data)
);
inp.nextRecord();
FormulaRecord fr = new FormulaRecord(inp);
assertEquals(14, fr.getNumberOfExpressionTokens());
assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass());
assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass());
assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass());
assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass());
FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13);
assertEquals("CHOOSE", choose.getName());
}
public static void main(String [] ignored_args) {
junit.textui.TestRunner.run(TestFormulaRecord.class);
}
}

View File

@ -1,4 +1,3 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@ -15,7 +14,6 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
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 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>
@ -57,13 +43,9 @@ public class TestRecordFactory
* FAILURE: The wrong records are creates or contain the wrong values <P>
*
*/
public void testBasicRecordConstruction()
throws Exception
{
public void testBasicRecordConstruction() {
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
};
short size = 16;
@ -106,13 +88,9 @@ public class TestRecordFactory
* FAILURE: The wrong records are created or contain the wrong values <P>
*
*/
public void testSpecial()
throws Exception
{
public void testSpecial() {
short recType = RKRecord.sid;
byte[] data = new byte[]
{
byte[] data = {
0, 0, 0, 0, 21, 0, 0, 0, 0, 0
};
short size = 10;
@ -138,10 +116,8 @@ public class TestRecordFactory
* FAILURE: The wrong records are created or contain the wrong values <P>
*
*/
public void testContinuedUnknownRecord()
{
byte[] data = new byte[]
{
public void testContinuedUnknownRecord() {
byte[] data = {
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, 1, 0, 4 // one more continuation record with 1 byte of data
@ -178,7 +154,7 @@ public class TestRecordFactory
*/
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 =
//OBJ
@ -228,10 +204,7 @@ public class TestRecordFactory
assertTrue(Arrays.equals(data, ser));
}
public static void main(String [] ignored_args)
{
System.out
.println("Testing org.apache.poi.hssf.record.TestRecordFactory");
public static void main(String [] ignored_args) {
junit.textui.TestRunner.run(TestRecordFactory.class);
}
}

View File

@ -1,4 +1,3 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@ -15,51 +14,47 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.record;
import org.apache.poi.util.HexRead;
import org.apache.poi.util.IntMapper;
import org.apache.poi.hssf.record.TestcaseRecordInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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.
*
* @author Glen Stampoultzis (glens at apache.org)
*/
public class TestSSTDeserializer
extends TestCase
{
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
public final class TestSSTDeserializer extends TestCase {
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) {
byte[] bigArray = new byte[array1.length+array2.length];
System.arraycopy(array1, 0, bigArray, 0, array1.length);
System.arraycopy(array2, 0, bigArray, array1.length, array2.length);
return bigArray;
byte[] bigArray = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, bigArray, 0, array1.length);
System.arraycopy(array2, 0, bigArray, array1.length, array2.length);
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()
throws Exception
{
byte[] header = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "continue1" );
byte[] header = readSampleHexData("richtextdata.txt", "header" );
byte[] continueBytes = readSampleHexData("richtextdata.txt", "continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -74,8 +69,8 @@ public class TestSSTDeserializer
public void testContinuationWithNoOverlap()
throws Exception
{
byte[] header = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "continue1" );
byte[] header = readSampleHexData("evencontinuation.txt", "header" );
byte[] continueBytes = readSampleHexData("evencontinuation.txt", "continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -93,10 +88,10 @@ public class TestSSTDeserializer
public void testStringAcross2Continuations()
throws Exception
{
byte[] header = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "header" );
byte[] continue1 = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "continue1" );
byte[] header = readSampleHexData("stringacross2continuations.txt", "header" );
byte[] continue1 = readSampleHexData("stringacross2continuations.txt", "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);
byte[] bytes = joinArray(header, continue1);
@ -111,11 +106,9 @@ public class TestSSTDeserializer
assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" );
}
public void testExtendedStrings()
throws Exception
{
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" );
public void testExtendedStrings() {
byte[] header = readSampleHexData("extendedtextstrings.txt", "rich-header" );
byte[] continueBytes = readSampleHexData("extendedtextstrings.txt", "rich-continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, 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 ) + "" );
header = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-header" );
continueBytes = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-continue1" );
header = readSampleHexData("extendedtextstrings.txt", "norich-header" );
continueBytes = readSampleHexData("extendedtextstrings.txt", "norich-continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -136,7 +129,5 @@ public class TestSSTDeserializer
deserializer.manufactureStrings( 1, in);
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
contributor license agreements. See the NOTICE file distributed with
@ -15,54 +14,33 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.record;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
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 Glen Stampoultzis (glens at apache.org)
*/
public class TestSSTRecord
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 );
}
public final class TestSSTRecord extends TestCase {
/**
* test processContinueRecord
*
* @exception IOException
*/
public void testProcessContinueRecord()
throws IOException
{
public void testProcessContinueRecord() {
//jmh byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" );
//jmh byte[] input = new byte[testdata.length - 4];
//jmh
@ -182,9 +160,7 @@ public class TestSSTRecord
* @exception IOException
*/
public void testHugeStrings()
throws IOException
{
public void testHugeStrings() {
SSTRecord record = new SSTRecord();
byte[][] bstrings =
{
@ -265,12 +241,8 @@ public class TestSSTRecord
/**
* test SSTRecord boundary conditions
*
* @exception IOException
*/
public void testSSTRecordBug()
throws IOException
{
public void testSSTRecordBug() {
// create an SSTRecord and write a certain pattern of strings
// to it ... then serialize it and verify the content
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
*/
@ -413,9 +353,7 @@ public class TestSSTRecord
* @param ignored_args
*/
public static void main( String[] ignored_args )
{
System.out.println( "Testing hssf.record.SSTRecord functionality" );
public static void main( String[] ignored_args ) {
junit.textui.TestRunner.run( TestSSTRecord.class );
}
@ -425,25 +363,16 @@ public class TestSSTRecord
public void testReadWriteDuplicatedRichText1()
throws Exception
{
File file = new File( _test_file_path + File.separator + "duprich1.xls" );
InputStream stream = new FileInputStream( file );
HSSFWorkbook wb = new HSSFWorkbook( stream );
stream.close();
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich1.xls");
HSSFSheet sheet = wb.getSheetAt( 1 );
assertEquals( "01/05 (Wed)", sheet.getRow( 0 ).getCell( (short) 8 ).getStringCellValue() );
assertEquals( "01/05 (Wed)", sheet.getRow( 1 ).getCell( (short) 8 ).getStringCellValue() );
file = TempFile.createTempFile( "testout", "xls" );
FileOutputStream outStream = new FileOutputStream( file );
wb.write( outStream );
outStream.close();
file.delete();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write( baos );
// test the second file.
file = new File( _test_file_path + File.separator + "duprich2.xls" );
stream = new FileInputStream( file );
wb = new HSSFWorkbook( stream );
stream.close();
wb = HSSFTestDataSamples.openSampleWorkbook("duprich2.xls");
sheet = wb.getSheetAt( 0 );
int row = 0;
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() );
// file = new File("/tryme.xls");
file = TempFile.createTempFile( "testout", ".xls" );
outStream = new FileOutputStream( file );
wb.write( outStream );
outStream.close();
file.delete();
wb.write( baos );
}
}

View File

@ -14,39 +14,23 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.record;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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.poifs.filesystem.POIFSFileSystem;
/**
*
*/
public final class TestUnicodeNameRecord extends TestCase {
public class TestUnicodeNameRecord extends TestCase {
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)
);
public void testReadBook() {
// This bit used to crash
HSSFWorkbook book = new HSSFWorkbook(fs);
HSSFSheet sheet = book.getSheetAt(0);
HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("unicodeNameRecord.xls");
book.getSheetAt(0);
}
}

View File

@ -29,6 +29,7 @@ import java.util.zip.CRC32;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.Record;
@ -250,22 +251,14 @@ public class TestValueRecordsAggregate extends TestCase
*
*/
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;
if(actualCRC != expectedCRC) {
System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC);
throw failUnexpectedTestFileChange();
}
HSSFWorkbook wb;
try {
FileInputStream in = new FileInputStream(testFile);
wb = new HSSFWorkbook(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE);
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
*/
private static long getFileCRC(File f) {
private static long getFileCRC(InputStream is) {
CRC32 crc = new CRC32();
byte[] buf = new byte[2048];
try {
InputStream is = new FileInputStream(f);
while(true) {
int bytesRead = is.read(buf);
if(bytesRead < 1) {

View File

@ -25,6 +25,7 @@ import java.io.InputStream;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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)
*/
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.
*
* @param filename the filename.
* @param sampleFileName the filename.
* @return the loaded workbook.
* @throws IOException if an error occurs loading the workbook.
*/
protected static final HSSFWorkbook loadWorkbook(String filename)
throws IOException {
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();
}
protected static final HSSFWorkbook loadWorkbook(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
/**
* Creates a new Workbook and adds one sheet with the specified name
*/
protected static final Workbook createWorkbookWithSheet(String sheetName) {
Workbook book = Workbook.createWorkbook();
// this creates sheet if it doesn't exist
book.checkExternSheet(0);
// TODO - this call alone does not create the sheet even though the javadoc says it does
book.setSheetName(0, sheetName);
return book;
}
Workbook book = Workbook.createWorkbook();
// this creates sheet if it doesn't exist
book.checkExternSheet(0);
// TODO - this call alone does not create the sheet even though the javadoc says it does
book.setSheetName(0, sheetName);
return book;
}
}

View File

@ -17,11 +17,9 @@
package org.apache.poi.hssf.record.formula;
import java.io.FileInputStream;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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
*/
public void testReadFormulaContainingExternalFunction() {
String filePath = System.getProperty("HSSF.testdata.path")+ "/"
+ "externalFunctionExample.xls";
HSSFWorkbook wb;
try {
FileInputStream fin = new FileInputStream(filePath);
wb = new HSSFWorkbook( fin );
} catch (IOException e) {
throw new RuntimeException(e);
}
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls");
String expectedFormula = "YEARFRAC(B1,C1)";
HSSFSheet sht = wb.getSheetAt(0);

View File

@ -17,9 +17,6 @@
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.IOException;
import java.io.InputStream;
@ -27,6 +24,7 @@ import java.io.InputStream;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
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 {
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
* added <em>long</em> after the relevant functionality was fixed.
*/
public void test27349() {
// 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622
InputStream is = openSampleFileStream("27349-vlookupAcrossSheets.xls");
InputStream is = HSSFTestDataSamples.openSampleFileStream("27349-vlookupAcrossSheets.xls");
HSSFWorkbook wb;
try {
// 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;
import java.io.FileInputStream;
import java.io.PrintStream;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.formula.functions.TestMathX;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
@ -154,9 +154,7 @@ public final class TestFormulasFromSpreadsheet extends TestCase {
protected void setUp() throws Exception {
if (workbook == null) {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME;
FileInputStream fin = new FileInputStream( filePath );
workbook = new HSSFWorkbook( fin );
workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME);
sheet = workbook.getSheetAt( 0 );
}
_functionFailureCount = 0;
@ -177,14 +175,14 @@ public final class TestFormulasFromSpreadsheet extends TestCase {
String successMsg = "There were "
+ _evaluationSuccessCount + " successful evaluation(s) and "
+ _functionSuccessCount + " function(s) without error";
if(_functionFailureCount > 0) {
if(_functionFailureCount > 0) {
String msg = _functionFailureCount + " function(s) failed in "
+ _evaluationFailureCount + " evaluation(s). " + successMsg;
throw new AssertionFailedError(msg);
}
if(false) { // normally no output for successful tests
System.out.println(getClass().getName() + ": " + successMsg);
}
if(false) { // normally no output for successful tests
System.out.println(getClass().getName() + ": " + successMsg);
}
}
/**

View File

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

View File

@ -26,6 +26,7 @@ import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.formula.eval.ErrorEval;
import org.apache.poi.hssf.usermodel.HSSFCell;
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";
/** 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'
/** 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_EVALUATION = 1; // Column 'B'
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_INDEX_MARKER = 0; // Column 'A'
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_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>";
/** 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>";
}
@ -90,8 +91,8 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
private static void confirmExpectedResult(String msg, HSSFCell expected, HSSFFormulaEvaluator.CellValue actual) {
if (expected == null) {
private static void confirmExpectedResult(String msg, HSSFCell expected, HSSFFormulaEvaluator.CellValue actual) {
if (expected == null) {
throw new AssertionFailedError(msg + " - Bad setup data expected value is null");
}
if(actual == null) {
@ -108,21 +109,21 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
throw wrongTypeError(msg, expected, actual);
}
switch (expected.getCellType()) {
case HSSFCell.CELL_TYPE_BOOLEAN:
assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue());
break;
assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue());
break;
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:
assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0);
break;
assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0);
break;
case HSSFCell.CELL_TYPE_STRING:
assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString());
break;
assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString());
break;
}
}
}
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 {
_sheetFailureCount = 0;
_sheetSuccessCount = 0;
_evaluationFailureCount = 0;
_evaluationSuccessCount = 0;
}
public void testFunctionsFromTestSpreadsheet() {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME;
HSSFWorkbook workbook;
try {
FileInputStream fin = new FileInputStream( filePath );
workbook = new HSSFWorkbook( fin );
} catch (IOException e) {
throw new RuntimeException(e);
}
_sheetFailureCount = 0;
_sheetSuccessCount = 0;
_evaluationFailureCount = 0;
_evaluationSuccessCount = 0;
}
public void testFunctionsFromTestSpreadsheet() {
HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME);
confirmReadMeSheet(workbook);
int nSheets = workbook.getNumberOfSheets();
for(int i=1; i< nSheets; i++) {
int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i));
switch(sheetResult) {
case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break;
case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break;
}
}
// confirm results
String successMsg = "There were "
+ _sheetSuccessCount + " successful sheets(s) and "
confirmReadMeSheet(workbook);
int nSheets = workbook.getNumberOfSheets();
for(int i=1; i< nSheets; i++) {
int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i));
switch(sheetResult) {
case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break;
case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break;
}
}
// confirm results
String successMsg = "There were "
+ _sheetSuccessCount + " successful sheets(s) and "
+ _evaluationSuccessCount + " function(s) without error";
if(_sheetFailureCount > 0) {
String msg = _sheetFailureCount + " sheets(s) failed with "
+ _evaluationFailureCount + " evaluation(s). " + successMsg;
throw new AssertionFailedError(msg);
}
throw new AssertionFailedError(msg);
}
if(false) { // normally no output for successful tests
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);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, workbook);
int maxRows = sheet.getLastRowNum()+1;
int result = Result.NO_EVALUATIONS_FOUND; // so far
int result = Result.NO_EVALUATIONS_FOUND; // so far
String currentGroupComment = null;
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);
if(r == null) {
continue;
@ -242,7 +236,7 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
if(newMarkerValue != null) {
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) {
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
* cells. This back-link is to make it easy to find this class if a reader encounters the
* spreadsheet first.
*/
private void confirmReadMeSheet(HSSFWorkbook workbook) {
* 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
* spreadsheet first.
*/
private void confirmReadMeSheet(HSSFWorkbook workbook) {
String firstSheetName = workbook.getSheetName(0);
if(!firstSheetName.equalsIgnoreCase(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) {
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
*/
*/
private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) {
if(r == null) {
return null;

View File

@ -14,42 +14,35 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.CellValue;
import org.apache.poi.hssf.util.CellReference;
/**
*
*/
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 {
HSSFWorkbook wb = new HSSFWorkbook(
new FileInputStream(new File(dirname,"42464-ExpPtg-ok.xls"))
);
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-ok.xls");
process(wb);
}
public void testExpSharedBadFile() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook(
new FileInputStream(new File(dirname,"42464-ExpPtg-bad.xls"))
);
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls");
process(wb);
}
protected void process(HSSFWorkbook wb) {
private static void process(HSSFWorkbook wb) {
for(int i=0; i<wb.getNumberOfSheets(); i++) {
HSSFSheet s = wb.getSheetAt(i);
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();
while(it.hasNext()) {
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
limitations under the License.
==================================================================== */
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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
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 {
private String dirName;
private String tmpDirName;
protected void setUp() throws Exception {
super.setUp();
dirName = System.getProperty("HSSF.testdata.path");
protected void setUp() {
tmpDirName = System.getProperty("java.io.tmpdir");
}
/**
* An odd problem with evaluateFormulaCell giving the
* right values when file is opened, but changes
@ -51,39 +51,39 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
public void test44636() throws Exception {
// Open the existing file, tweak one value and
// 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);
HSSFRow row = sheet.getRow (0);
row.getCell((short)0).setCellValue(4.2);
row.getCell((short)2).setCellValue(25);
HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
assertEquals(4.2*25, row.getCell((short)3).getNumericCellValue(), 0.0001);
// Save
File existing = new File(tmpDirName,"44636-existing.xls");
FileOutputStream out = new FileOutputStream(existing);
wb.write(out);
out.close();
System.err.println("Existing file for bug #44636 written to " + existing.toString());
// Now, do a new file from scratch
wb = new HSSFWorkbook();
sheet = wb.createSheet();
row = sheet.createRow(0);
row.createCell((short)0).setCellValue(1.2);
row.createCell((short)1).setCellValue(4.2);
row = sheet.createRow(1);
row.createCell((short)0).setCellFormula("SUM(A1:B1)");
HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
assertEquals(5.4, row.getCell((short)0).getNumericCellValue(), 0.0001);
// Save
File scratch = new File(tmpDirName,"44636-scratch.xls");
out = new FileOutputStream(scratch);
@ -99,72 +99,71 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
*
* @author Yegor Kozlov
*/
public void test44297() throws IOException {
FileInputStream in = new FileInputStream(new File(dirName, "44297.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
public void test44297() {
HSSFRow row;
HSSFCell cell;
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44297.xls");
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);
cell = row.getCell((short)0);
assertEquals("31+46", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(77, eva.evaluate(cell).getNumberValue(), 0);
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb);
row = (HSSFRow)sheet.getRow(1);
cell = row.getCell((short)0);
assertEquals("30+53", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(83, eva.evaluate(cell).getNumberValue(), 0);
row = sheet.getRow(0);
cell = row.getCell((short)0);
assertEquals("31+46", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(77, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(2);
cell = row.getCell((short)0);
assertEquals("SUM(A1:A2)", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(160, eva.evaluate(cell).getNumberValue(), 0);
row = sheet.getRow(1);
cell = row.getCell((short)0);
assertEquals("30+53", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(83, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(4);
cell = row.getCell((short)0);
assertEquals("32767+32768", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0);
row = sheet.getRow(2);
cell = row.getCell((short)0);
assertEquals("SUM(A1:A2)", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(160, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(7);
cell = row.getCell((short)0);
assertEquals("32744+42333", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0);
row = sheet.getRow(4);
cell = row.getCell((short)0);
assertEquals("32767+32768", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(8);
cell = row.getCell((short)0);
assertEquals("327680.0/32768", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(10, eva.evaluate(cell).getNumberValue(), 0);
row = sheet.getRow(7);
cell = row.getCell((short)0);
assertEquals("32744+42333", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(9);
cell = row.getCell((short)0);
assertEquals("32767+32769", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0);
row = sheet.getRow(8);
cell = row.getCell((short)0);
assertEquals("327680.0/32768", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(10, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(10);
cell = row.getCell((short)0);
assertEquals("35000+36000", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0);
row = sheet.getRow(9);
cell = row.getCell((short)0);
assertEquals("32767+32769", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)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);
}
row = sheet.getRow(10);
cell = row.getCell((short)0);
assertEquals("35000+36000", cell.getCellFormula());
eva.setCurrentRow(row);
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
@ -172,86 +171,85 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
*
* @author Nick Burch
*/
public void test44410() throws IOException {
FileInputStream in = new FileInputStream(new File(dirName, "SingleLetterRanges.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
public void test44410() {
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
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());
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb);
// Actually stored as C1 to C65536
// (last row is -1 === 65535)
AreaPtg ptg = (AreaPtg)ops.get(0);
assertEquals(2, ptg.getFirstColumn());
assertEquals(2, ptg.getLastColumn());
assertEquals(0, ptg.getFirstRow());
assertEquals(65535, ptg.getLastRow());
assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook()));
// Will show as C:C, but won't know how many
// rows it covers as we don't have the sheet
// to hand when turning the Ptgs into a string
assertEquals("SUM(C:C)", cellSUM.getCellFormula());
eva.setCurrentRow(rowSUM);
// 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);
}
// =index(C:C,2,1) -> 2
HSSFRow rowIDX = sheet.getRow(3);
// =sum(C:C) -> 6
HSSFRow rowSUM = sheet.getRow(4);
// =sum(C:D) -> 66
HSSFRow rowSUM2D = 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
// (last row is -1 === 65535)
AreaPtg ptg = (AreaPtg)ops.get(0);
assertEquals(2, ptg.getFirstColumn());
assertEquals(2, ptg.getLastColumn());
assertEquals(0, ptg.getFirstRow());
assertEquals(65535, ptg.getLastRow());
assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook()));
// Will show as C:C, but won't know how many
// rows it covers as we don't have the sheet
// to hand when turning the Ptgs into a string
assertEquals("SUM(C:C)", cellSUM.getCellFormula());
eva.setCurrentRow(rowSUM);
// 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
*/
public void testEvaluateBooleanInCell_bug44508() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(0, "Sheet1");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short)0);
public void testEvaluateBooleanInCell_bug44508() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(0, "Sheet1");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short)0);
cell.setCellFormula("1=1");
cell.setCellFormula("1=1");
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb);
fe.setCurrentRow(row);
try {
fe.evaluateInCell(cell);
} catch (NumberFormatException e) {
fail("Identified bug 44508");
}
assertEquals(true, cell.getBooleanCellValue());
}
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb);
fe.setCurrentRow(row);
try {
fe.evaluateInCell(cell);
} catch (NumberFormatException e) {
fail("Identified bug 44508");
}
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;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.TempFile;
/**
@ -40,12 +43,26 @@ import org.apache.poi.util.TempFile;
*/
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.
*/
public void testBoolErr()
throws java.io.IOException {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testBoolErr",".xls");
FileOutputStream out = new FileOutputStream(file);
@ -102,33 +119,24 @@ public final class TestHSSFCell extends TestCase {
public void testDateWindowingRead() throws Exception {
GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000
Date date = cal.getTime();
String path = System.getProperty("HSSF.testdata.path");
// first check a file with 1900 Date Windowing
String filename = path + "/1900DateWindowing.xls";
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFWorkbook workbook = openSample("1900DateWindowing.xls");
HSSFSheet sheet = workbook.getSheetAt(0);
assertEquals("Date from file using 1900 Date Windowing",
date.getTime(),
sheet.getRow(0).getCell((short)0)
.getDateCellValue().getTime());
stream.close();
// now check a file with 1904 Date Windowing
filename = path + "/1904DateWindowing.xls";
stream = new FileInputStream(filename);
fs = new POIFSFileSystem(stream);
workbook = new HSSFWorkbook(fs);
workbook = openSample("1904DateWindowing.xls");
sheet = workbook.getSheetAt(0);
assertEquals("Date from file using 1904 Date Windowing",
date.getTime(),
sheet.getRow(0).getCell((short)0)
.getDateCellValue().getTime());
stream.close();
}
/**
@ -140,55 +148,39 @@ public final class TestHSSFCell extends TestCase {
public void testDateWindowingWrite() throws Exception {
GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000
Date date = cal.getTime();
String path = System.getProperty("HSSF.testdata.path");
// first check a file with 1900 Date Windowing
String filename = path + "/1900DateWindowing.xls";
writeCell(filename, 0, (short) 1, date);
HSSFWorkbook wb;
wb = openSample("1900DateWindowing.xls");
setCell(wb, 0, 1, date);
wb = writeOutAndReadBack(wb);
assertEquals("Date from file using 1900 Date Windowing",
date.getTime(),
readCell(filename, 0, (short) 1).getTime());
readCell(wb, 0, 1).getTime());
// now check a file with 1904 Date Windowing
filename = path + "/1904DateWindowing.xls";
writeCell(filename, 0, (short) 1, date);
wb = openSample("1904DateWindowing.xls");
setCell(wb, 0, 1, date);
wb = writeOutAndReadBack(wb);
assertEquals("Date from file using 1900 Date Windowing",
date.getTime(),
readCell(filename, 0, (short) 1).getTime());
readCell(wb, 0, 1).getTime());
}
/**
* 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);
private static void setCell(HSSFWorkbook workbook, int rowIdx, int colIdx, Date date) {
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(rowIdx);
HSSFCell cell = row.getCell(colIdx);
if (cell == null) {
cell = row.createCell(colIdx);
cell = row.createCell((short)colIdx);
}
cell.setCellValue(date);
// Write the file
stream.close();
FileOutputStream oStream = new FileOutputStream(filename);
workbook.write(oStream);
oStream.close();
}
/**
* 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);
private static Date readCell(HSSFWorkbook workbook, int rowIdx, int colIdx) {
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(rowIdx);
HSSFCell cell = row.getCell(colIdx);
@ -201,12 +193,7 @@ public final class TestHSSFCell extends TestCase {
public void testActiveCell() throws Exception
{
//read in sample
String dir = System.getProperty("HSSF.testdata.path");
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();
HSSFWorkbook book = openSample("Simple.xls");
//check initial position
HSSFSheet umSheet = book.getSheetAt(0);
@ -225,14 +212,8 @@ public final class TestHSSFCell extends TestCase {
3, s.getActiveCellRow());
//write book to temp file; read and verify that position is serialized
File temp = TempFile.createTempFile("testActiveCell", ".xls");
FileOutputStream fos = new FileOutputStream(temp);
book.write(fos);
fos.close();
fis = new FileInputStream(temp);
book = new HSSFWorkbook(fis);
fis.close();
book = writeOutAndReadBack(book);
umSheet = book.getSheetAt(0);
s = umSheet.getSheet();
@ -245,12 +226,8 @@ public final class TestHSSFCell extends TestCase {
/**
* test that Cell Styles being applied to formulas remain intact
*/
public void testFormulaStyle()
throws java.io.IOException {
String readFilename = System.getProperty("HSSF.testdata.path");
public void testFormulaStyle() {
File file = TempFile.createTempFile("testFormulaStyle",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("testSheet1");
HSSFRow r = null;
@ -258,7 +235,7 @@ public final class TestHSSFCell extends TestCase {
HSSFCellStyle cs = wb.createCellStyle();
HSSFFont f = wb.createFont();
f.setFontHeightInPoints((short) 20);
f.setColor((short) HSSFColor.RED.index);
f.setColor(HSSFColor.RED.index);
f.setBoldweight(f.BOLDWEIGHT_BOLD);
f.setFontName("Arial Unicode MS");
cs.setFillBackgroundColor((short)3);
@ -273,13 +250,7 @@ public final class TestHSSFCell extends TestCase {
c.setCellStyle(cs);
c.setCellFormula("2*3");
wb.write(out);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
wb = writeOutAndReadBack(wb);
s = wb.getSheetAt(0);
r = s.getRow(0);
c = r.getCell((short)0);
@ -293,17 +264,14 @@ public final class TestHSSFCell extends TestCase {
assertTrue("Left Border", (cs.getBorderLeft() == (short)1));
assertTrue("Right Border", (cs.getBorderRight() == (short)1));
assertTrue("Bottom Border", (cs.getBorderBottom() == (short)1));
in.close();
}
/**
* Test reading hyperlinks
*/
public void testWithHyperlink() throws Exception {
String dir = System.getProperty("HSSF.testdata.path");
File f = new File(dir, "WithHyperlink.xls");
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f));
public void testWithHyperlink() {
HSSFWorkbook wb = openSample("WithHyperlink.xls");
HSSFSheet sheet = wb.getSheetAt(0);
HSSFCell cell = sheet.getRow(4).getCell((short)0);
@ -320,10 +288,9 @@ public final class TestHSSFCell extends TestCase {
* Test reading hyperlinks
*/
public void testWithTwoHyperlinks() throws Exception {
String dir = System.getProperty("HSSF.testdata.path");
File f = new File(dir, "WithTwoHyperLinks.xls");
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f));
HSSFWorkbook wb = openSample("WithTwoHyperLinks.xls");
HSSFSheet sheet = wb.getSheetAt(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*/
public void testToString() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("Sheet1");
HSSFRow r = s.createRow(0);
HSSFCell c;
c=r.createCell((short) 0); c.setCellValue(true);
assertEquals("Boolean", "TRUE", c.toString());
c=r.createCell((short) 1); c.setCellValue(1.5);
assertEquals("Numeric", "1.5", c.toString());
c=r.createCell((short)(2)); c.setCellValue("Astring");
assertEquals("String", "Astring", c.toString());
c=r.createCell((short) 3); c.setCellErrorValue((byte) 7);
assertEquals("Error", "#ERR7", c.toString());
c=r.createCell((short)4); c.setCellFormula("A1+B1");
assertEquals("Formula", "A1+B1", c.toString());
//Write out the file, read it in, and then check cell values
File f = File.createTempFile("testCellToString",".xls");
wb.write(new FileOutputStream(f));
wb = new HSSFWorkbook(new FileInputStream(f));
assertTrue("File exists and can be read", f.canRead());
s = wb.getSheetAt(0);r=s.getRow(0);
c=r.getCell((short) 0);
assertEquals("Boolean", "TRUE", c.toString());
c=r.getCell((short) 1);
assertEquals("Numeric", "1.5", c.toString());
c=r.getCell((short)(2));
assertEquals("String", "Astring", c.toString());
c=r.getCell((short) 3);
assertEquals("Error", "#ERR7", c.toString());
c=r.getCell((short)4);
assertEquals("Formula", "A1+B1", c.toString());
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("Sheet1");
HSSFRow r = s.createRow(0);
HSSFCell c;
c=r.createCell((short) 0); c.setCellValue(true);
assertEquals("Boolean", "TRUE", c.toString());
c=r.createCell((short) 1); c.setCellValue(1.5);
assertEquals("Numeric", "1.5", c.toString());
c=r.createCell((short)(2)); c.setCellValue(new HSSFRichTextString("Astring"));
assertEquals("String", "Astring", c.toString());
c=r.createCell((short) 3); c.setCellErrorValue((byte) 7);
assertEquals("Error", "#ERR7", c.toString());
c=r.createCell((short)4); c.setCellFormula("A1+B1");
assertEquals("Formula", "A1+B1", c.toString());
//Write out the file, read it in, and then check cell values
File f = File.createTempFile("testCellToString",".xls");
wb.write(new FileOutputStream(f));
wb = new HSSFWorkbook(new FileInputStream(f));
assertTrue("File exists and can be read", f.canRead());
s = wb.getSheetAt(0);r=s.getRow(0);
c=r.getCell((short) 0);
assertEquals("Boolean", "TRUE", c.toString());
c=r.getCell((short) 1);
assertEquals("Numeric", "1.5", c.toString());
c=r.getCell((short)(2));
assertEquals("String", "Astring", c.toString());
c=r.getCell((short) 3);
assertEquals("Error", "#ERR7", c.toString());
c=r.getCell((short)4);
assertEquals("Formula", "A1+B1", c.toString());
}
public void testSetStringInFormulaCell_bug44606() {
@ -392,10 +359,7 @@ public final class TestHSSFCell extends TestCase {
}
public static void main(String [] args) {
System.out
.println("Testing org.apache.poi.hssf.usermodel.TestHSSFCell");
junit.textui.TestRunner.run(TestHSSFCell.class);
}
}

View File

@ -20,13 +20,14 @@ import junit.framework.TestCase;
import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
/**
* Tests TestHSSFCellComment.
*
* @author Yegor Kozlov
*/
public class TestHSSFComment extends TestCase {
public final class TestHSSFComment extends TestCase {
/**
* 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.
*/
public static void testReadComments() throws Exception {
public static void testReadComments() {
String dir = System.getProperty("HSSF.testdata.path");
FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls"));
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls");
HSSFSheet sheet = wb.getSheetAt(0);
@ -123,12 +121,9 @@ public class TestHSSFComment extends TestCase {
/**
* 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");
FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls"));
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls");
HSSFSheet sheet = wb.getSheetAt(0);

View File

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

View File

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

View File

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

View File

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

View File

@ -15,20 +15,19 @@
limitations under the License.
==================================================================== */
/*
* HSSFWorkbook.java
*
* Created on September 30, 2001, 3:37 PM
*/
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 javax.imageio.ImageIO;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import org.apache.poi.hssf.HSSFTestDataSamples;
/**
* Test <code>HSSFPictureData</code>.
@ -37,14 +36,11 @@ import java.awt.image.BufferedImage;
* @author Yegor Kozlov (yegor at apache 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 {
FileInputStream is = new FileInputStream(new File(cwd, "SimpleWithImages.xls"));
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls");
List lst = wb.getAllPictures();
//assertEquals(2, lst.size());
@ -69,6 +65,5 @@ public class TestHSSFPictureData extends TestCase{
//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
* limitations under the License.
*/
package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import junit.framework.TestCase;
import junit.framework.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
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
{
HSSFWorkbook hssfWorkbook;
String filename;
protected void setUp() throws Exception {
super.setUp();
filename = System.getProperty("HSSF.testdata.path");
}
public void testSetRepeatingRowsAndColumns() throws Exception
{
public void testSetRepeatingRowsAndColumns() {
// Test bug 29747
HSSFWorkbook b = new HSSFWorkbook( );
b.createSheet();
@ -46,9 +40,7 @@ public class TestHSSFWorkbook extends TestCase
assertEquals( 3, nameRecord.getIndexToSheet() );
}
public void testDuplicateNames()
throws Exception
{
public void testDuplicateNames() {
HSSFWorkbook b = new HSSFWorkbook( );
b.createSheet("Sheet1");
b.createSheet();
@ -105,15 +97,15 @@ public class TestHSSFWorkbook extends TestCase
public void testSheetSelection() {
HSSFWorkbook b = new HSSFWorkbook();
b.createSheet("Sheet One");
HSSFSheet s = b.createSheet("Sheet Two");
b.createSheet("Sheet Two");
b.setSelectedTab((short) 1);
b.setDisplayedTab((short) 1);
assertEquals(b.getSelectedTab(), 1);
assertEquals(b.getDisplayedTab(), 1);
}
public void testSheetClone() throws Exception {
// First up, try a simple file
public void testSheetClone() {
// First up, try a simple file
HSSFWorkbook b = new HSSFWorkbook();
assertEquals(0, b.getNumberOfSheets());
b.createSheet("Sheet One");
@ -122,24 +114,20 @@ public class TestHSSFWorkbook extends TestCase
assertEquals(2, b.getNumberOfSheets());
b.cloneSheet(0);
assertEquals(3, b.getNumberOfSheets());
// Now try a problem one with drawing records in it
b = new HSSFWorkbook(
new FileInputStream(new File(filename,"SheetWithDrawing.xls"))
);
// Now try a problem one with drawing records in it
b = openSample("SheetWithDrawing.xls");
assertEquals(1, b.getNumberOfSheets());
b.cloneSheet(0);
assertEquals(2, b.getNumberOfSheets());
}
public void testReadWriteWithCharts() throws Exception {
public void testReadWriteWithCharts() {
HSSFWorkbook b;
HSSFSheet s;
// Single chart, two sheets
b = new HSSFWorkbook(
new FileInputStream(new File(filename,"44010-SingleChart.xls"))
);
b = openSample("44010-SingleChart.xls");
assertEquals(2, b.getNumberOfSheets());
s = b.getSheetAt(1);
assertEquals(0, s.getFirstRowNum());
@ -154,9 +142,7 @@ public class TestHSSFWorkbook extends TestCase
// We've now called getDrawingPatriarch() so
// everything will be all screwy
// So, start again
b = new HSSFWorkbook(
new FileInputStream(new File(filename,"44010-SingleChart.xls"))
);
b = openSample("44010-SingleChart.xls");
b = writeRead(b);
assertEquals(2, b.getNumberOfSheets());
@ -166,9 +152,7 @@ public class TestHSSFWorkbook extends TestCase
// Two charts, three sheets
b = new HSSFWorkbook(
new FileInputStream(new File(filename,"44010-TwoCharts.xls"))
);
b = openSample("44010-TwoCharts.xls");
assertEquals(3, b.getNumberOfSheets());
s = b.getSheetAt(1);
@ -188,9 +172,7 @@ public class TestHSSFWorkbook extends TestCase
// We've now called getDrawingPatriarch() so
// everything will be all screwy
// So, start again
b = new HSSFWorkbook(
new FileInputStream(new File(filename,"44010-TwoCharts.xls"))
);
b = openSample("44010-TwoCharts.xls");
b = writeRead(b);
assertEquals(3, b.getNumberOfSheets());
@ -203,11 +185,7 @@ public class TestHSSFWorkbook extends TestCase
assertEquals(0, s.getLastRowNum());
}
private HSSFWorkbook writeRead(HSSFWorkbook b) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.write(baos);
return new HSSFWorkbook(
new ByteArrayInputStream(baos.toByteArray())
);
private static HSSFWorkbook writeRead(HSSFWorkbook b) {
return HSSFTestDataSamples.writeOutAndReadBack(b);
}
}

View File

@ -1,4 +1,3 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@ -15,17 +14,9 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
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.ByteArrayOutputStream;
import java.io.File;
@ -33,6 +24,12 @@ import java.io.FileInputStream;
import java.io.FileOutputStream;
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 Amol S. Deshmukh &lt; amol at ap ache dot org &gt;
*/
public class TestNamedRange
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");
public final class TestNamedRange extends TestCase {
filename = filename + "/Simple.xls";
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis);
wb = new HSSFWorkbook(fs);
//Creating new Named Range
HSSFName newNamedRange = wb.createName();
//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");
private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(TestNamedRange.class);
}
/** Test of TestCase method, of class test.RangeTest. */
public void testNamedRange()
throws IOException
{
HSSFWorkbook wb = openSample("Simple.xls");
//Creating new Named Range
HSSFName newNamedRange = wb.createName();
//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
HSSFName namedRange1 = wb.getNameAt(0);
//Getting it sheet name
sheetName = namedRange1.getSheetName();
//Getting its reference
String referece = namedRange1.getReference();
//Getting NAmed Range
HSSFName namedRange1 = wb.getNameAt(0);
//Getting it sheet name
sheetName = namedRange1.getSheetName();
//Getting its reference
String referece = namedRange1.getReference();
// sanity check
SanityChecker c = new SanityChecker();
c.checkHSSFWorkbook(wb);
// sanity check
SanityChecker c = new SanityChecker();
c.checkHSSFWorkbook(wb);
File file = TempFile.createTempFile("testNamedRange",
".xls");
File file = TempFile.createTempFile("testNamedRange", ".xls");
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fis.close();
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest"));
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference());
}
/**
* Reads an excel file already containing a named range.
* <p>
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest"));
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference());
}
/**
* Reads an excel file already containing a named range.
* <p>
* Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=9632" target="_bug">#9632</a>
*/
public void testNamedRead() throws IOException
{
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);
*/
public void testNamedRead() {
HSSFWorkbook wb = openSample("namedinput.xls");
//Get index of the namedrange with the name = "NamedRangeName" , which was defined in input.xls as A1:D10
int NamedRangeIndex = wb.getNameIndex("NamedRangeName");
@ -161,103 +112,86 @@ public class TestNamedRange
//Getting its reference
String reference = namedRange1.getReference();
fis.close();
assertEquals(sheetName+"!$A$1:$D$10", reference);
HSSFName namedRange2 = wb.getNameAt(1);
assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getReference());
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";
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis);
wb = new HSSFWorkbook(fs);
/**
* 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() {
HSSFWorkbook wb = openSample("namedinput.xls");
HSSFName name = wb.getNameAt(0);
String sheetName = wb.getSheetName(0);
assertEquals(sheetName+"!$A$1:$D$10", name.getReference());
name = wb.getNameAt(1);
name = wb.getNameAt(1);
String newReference = sheetName +"!$A$1:$C$36";
name.setReference(newReference);
name.setReference(newReference);
assertEquals(newReference, name.getReference());
}
}
/**
* Test that multiple named ranges can be added written and read
*/
public void testMultipleNamedWrite()
throws IOException
throws IOException
{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("testSheet1");
String sheetName = wb.getSheetName(0);
assertEquals("testSheet1", sheetName);
assertEquals("testSheet1", sheetName);
//Creating new Named Range
HSSFName newNamedRange = wb.createName();
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);
String referece = namedRange1.getReference();
File file = TempFile.createTempFile("testMultiNamedRange", ".xls");
File file = TempFile.createTempFile("testMultiNamedRange", ".xls");
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest"));
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertTrue("Reference is "+nm.getReference(),(wb.getSheetName(0)+"!$D$4:$E$8").equals(nm.getReference()));
nm = wb.getNameAt(wb.getNameIndex("AnotherTest"));
assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName()));
assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference()));
}
nm = wb.getNameAt(wb.getNameIndex("AnotherTest"));
assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName()));
assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference()));
}
/**
* Test case provided by czhang@cambian.com (Chun Zhang)
@ -268,7 +202,7 @@ public class TestNamedRange
public void testMultiNamedRange()
throws IOException
{
// Create a new workbook
HSSFWorkbook wb = new HSSFWorkbook ();
@ -276,14 +210,14 @@ public class TestNamedRange
// Create a worksheet 'sheet1' in the new workbook
wb.createSheet ();
wb.setSheetName (0, "sheet1");
// Create another worksheet 'sheet2' in the new workbook
wb.createSheet ();
wb.setSheetName (1, "sheet2");
// Create a new named range for worksheet 'sheet1'
HSSFName namedRange1 = wb.createName();
// Set the name for the named range for worksheet 'sheet1'
namedRange1.setNameName("RangeTest1");
@ -292,21 +226,21 @@ public class TestNamedRange
// Create a new named range for worksheet 'sheet2'
HSSFName namedRange2 = wb.createName();
// Set the name for the named range for worksheet 'sheet2'
namedRange2.setNameName("RangeTest2");
// 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
File file = TempFile.createTempFile("testMuiltipletNamedRanges", ".xls");
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
// Read the Excel file and verify its content
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
@ -317,42 +251,42 @@ public class TestNamedRange
HSSFName nm2 =wb.getNameAt(wb.getNameIndex("RangeTest2"));
assertTrue("Name is "+nm2.getNameName(),"RangeTest2".equals(nm2.getNameName()));
assertTrue("Reference is "+nm2.getReference(),(wb.getSheetName(1)+"!$A$1:$O$21").equals(nm2.getReference()));
}
}
public void testUnicodeNamedRange() throws Exception {
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("Test");
HSSFName name = workBook.createName();
name.setNameName("\u03B1");
name.setReference("Test!$D$3:$E$8");
ByteArrayOutputStream out = new ByteArrayOutputStream();
workBook.write(out);
HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray()));
HSSFName name2 = workBook2.getNameAt(0);
assertEquals("\u03B1", name2.getNameName());
assertEquals("Test!$D$3:$E$8", name2.getReference());
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("Test");
HSSFName name = workBook.createName();
name.setNameName("\u03B1");
name.setReference("Test!$D$3:$E$8");
ByteArrayOutputStream out = new ByteArrayOutputStream();
workBook.write(out);
HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray()));
HSSFName name2 = workBook2.getNameAt(0);
assertEquals("\u03B1", name2.getNameName());
assertEquals("Test!$D$3:$E$8", name2.getReference());
}
/**
* Test to see if the print areas can be retrieved/created in memory
*/
public void testSinglePrintArea()
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference);
String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference);
String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
}
/**
@ -360,53 +294,31 @@ public class TestNamedRange
*/
public void testSinglePrintAreaWOSheet()
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0);
String reference = "$A$1:$B$1";
workbook.setPrintArea(0, reference);
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);
}
/**
* Test to see if the print area can be retrieved from an excel created file
*/
public void testPrintAreaFileRead()
throws IOException
{
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook workbook = null;
String filename = System.getProperty("HSSF.testdata.path");
public void testPrintAreaFileRead() {
HSSFWorkbook workbook = openSample("SimpleWithPrintArea.xls");
filename = filename + "/SimpleWithPrintArea.xls";
try {
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();
}
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$C$5";
assertEquals(reference, workbook.getPrintArea(0));
}
@ -416,29 +328,29 @@ public class TestNamedRange
public void testPrintAreaFile()
throws IOException
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference);
File file = TempFile.createTempFile("testPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
File file = TempFile.createTempFile("testPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("References Match", "'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
}
/**
@ -447,180 +359,178 @@ public class TestNamedRange
public void testMultiplePrintAreaFile()
throws IOException
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
sheet = workbook.createSheet("Sheet2");
sheet = workbook.createSheet("Sheet3");
String sheetName = workbook.getSheetName(0);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
sheet = workbook.createSheet("Sheet2");
sheet = workbook.createSheet("Sheet3");
String sheetName = workbook.getSheetName(0);
String reference = null;
reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference);
sheetName = workbook.getSheetName(1);
String reference2 = sheetName+"!$B$2:$D$5";
workbook.setPrintArea(1, reference2);
String reference2 = sheetName+"!$B$2:$D$5";
workbook.setPrintArea(1, reference2);
sheetName = workbook.getSheetName(2);
String reference3 = sheetName+"!$D$2:$F$5";
workbook.setPrintArea(2, reference3);
File file = TempFile.createTempFile("testMultiPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea);
assertEquals(reference, retrievedPrintArea);
String retrievedPrintArea2 = workbook.getPrintArea(1);
assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2);
assertEquals(reference2, retrievedPrintArea2);
String retrievedPrintArea3 = workbook.getPrintArea(2);
assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3);
assertEquals(reference3, retrievedPrintArea3);
File file = TempFile.createTempFile("testMultiPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea);
assertEquals(reference, retrievedPrintArea);
String retrievedPrintArea2 = workbook.getPrintArea(1);
assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2);
assertEquals(reference2, retrievedPrintArea2);
String retrievedPrintArea3 = workbook.getPrintArea(2);
assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3);
assertEquals(reference3, retrievedPrintArea3);
}
/**
* Tests the setting of print areas with coordinates (Row/Column designations)
*
*/
public void testPrintAreaCoords(){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
/**
* Tests the setting of print areas with coordinates (Row/Column designations)
*
*/
public void testPrintAreaCoords(){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, 0, 1, 0, 0);
String retrievedPrintArea = workbook.getPrintArea(0);
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();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
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();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
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";
workbook.setPrintArea(0, reference);
String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals(expResult, retrievedPrintArea);
}
/**
* Verifies an existing print area is deleted
*
*/
public void testPrintAreaRemove() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals(expResult, retrievedPrintArea);
}
/**
* Verifies an existing print area is deleted
*
*/
public void testPrintAreaRemove() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, 0, 1, 0, 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);
}
/**
* 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);
}
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);
}
/**
* 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;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import junit.framework.TestCase;
public class TestOLE2Embeding extends TestCase {
public void testEmbeding() throws Exception {
String dirname = System.getProperty("HSSF.testdata.path");
String filename = dirname + "/ole2-embedding.xls";
import org.apache.poi.hssf.HSSFTestDataSamples;
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
workbook = new HSSFWorkbook(in);
in.close();
HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls");
// Check we can get at the Escher layer still
workbook.getAllPictures();
}
public void testEmbeddedObjects() throws Exception {
String dirname = System.getProperty("HSSF.testdata.path");
String filename = dirname + "/ole2-embedding.xls";
HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls");
File file = new File(filename);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
List objects = workbook.getAllEmbeddedObjects();
assertEquals("Wrong number of objects", 2, objects.size());
assertEquals("Wrong name for first object", "MBD06CAB431",
@ -56,6 +48,5 @@ public class TestOLE2Embeding extends TestCase {
((HSSFObjectData)
objects.get(1)).getDirectory().getName());
}
}

View File

@ -17,32 +17,31 @@
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.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
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
*
* @author Yegor Kozlov
*/
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 {
FileInputStream is = new FileInputStream(new File(cwd, "Simple.xls"));
InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
HSSFWorkbook wb = new HSSFWorkbook(fs);
@ -62,19 +61,13 @@ public class TestPOIFSProperties extends TestCase{
POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
try {
//failing assertion
assertEquals(title, summary2.getTitle());
} catch (AssertionError e){
assertTrue(true);
}
//failing assertion
assertEquals(title, summary2.getTitle());
}
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);
is.close();
//set POIFS properties before constructing HSSFWorkbook
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
contributor license agreements. See the NOTICE file distributed with
@ -15,47 +14,29 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.usermodel;
import java.util.GregorianCalendar;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.record.BOFRecord;
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)
*/
public class TestReadWriteChart
extends TestCase
{
public TestReadWriteChart(String s)
{
super(s);
}
public final class TestReadWriteChart extends TestCase {
/**
* In the presence of a chart we need to make sure BOF/EOF records still exist.
*/
public void testBOFandEOFRecords()
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);
public void testBOFandEOFRecords() {
HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls");
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow firstRow = sheet.getRow(0);
HSSFCell firstCell = firstRow.getCell(( short ) 0);
@ -77,29 +58,7 @@ public class TestReadWriteChart
assertTrue(records.get(records.size() - 1) instanceof EOFRecord);
}
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");
public static void main(String [] args) {
junit.textui.TestRunner.run(TestReadWriteChart.class);
}
}

View File

@ -14,40 +14,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
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
* with a WORKBOOK directory entry (instead of the more
* usual, Workbook)
*/
public class TestSheetHiding extends TestCase {
private String dirPath;
private String xlsHidden = "TwoSheetsOneHidden.xls";
private String xlsShown = "TwoSheetsNoneHidden.xls";
public final class TestSheetHiding extends TestCase {
private HSSFWorkbook wbH;
private HSSFWorkbook wbU;
protected void setUp() throws Exception {
super.setUp();
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);
protected void setUp() {
wbH = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsOneHidden.xls");
wbU = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsNoneHidden.xls");
}
/**

View File

@ -1,4 +1,3 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@ -15,20 +14,15 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
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.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/**
* Tests row shifting capabilities.
@ -37,16 +31,7 @@ import java.io.FileOutputStream;
* @author Shawn Laubach (slaubach at apache dot com)
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/
public class TestSheetShiftRows extends TestCase {
/**
* Constructor for TestSheetShiftRows.
* @param arg0
*/
public TestSheetShiftRows(String arg0) {
super(arg0);
}
public final class TestSheetShiftRows extends TestCase {
/**
* Tests the shiftRows function. Does three different shifts.
@ -59,25 +44,16 @@ public class TestSheetShiftRows extends TestCase {
public void testShiftRows() throws Exception
{
// Read initial file in
String filename = System.getProperty( "HSSF.testdata.path" );
filename = filename + "/SimpleMultiCell.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls");
HSSFSheet s = wb.getSheetAt( 0 );
// Shift the second row down 1 and write to temp file
s.shiftRows( 1, 1, 1 );
File tempFile = TempFile.createTempFile( "shift", "test.xls" );
FileOutputStream fout = new FileOutputStream( tempFile );
wb.write( fout );
fout.close();
wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
// Read from temp file and check the number of cells in each
// row (in original file each row was unique)
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 );
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
// 1 row is blank. Write to a another temp file
s.shiftRows( 0, 2, 3 );
tempFile = TempFile.createTempFile( "shift", "test.xls" );
fout = new FileOutputStream( tempFile );
wb.write( fout );
fout.close();
wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
// Read and ensure things are where they should be
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 );
assertTrue( s.getRow( 0 ) == null || s.getRow( 0 ).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 );
// Read the first file again
fin = new FileInputStream( filename );
wb = new HSSFWorkbook( fin );
fin.close();
wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls");
s = wb.getSheetAt( 0 );
// Shift rows 3 and 4 up and write to temp file
s.shiftRows( 2, 3, -2 );
tempFile = TempFile.createTempFile( "shift", "test.xls" );
fout = new FileOutputStream( tempFile );
wb.write( fout );
fout.close();
// Read file and test
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
s = wb.getSheetAt( 0 );
assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 3 );
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)
*/
public void testShiftRow(){
HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2");
s.shiftRows(0,4,1);
HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2");
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)
*/
public void testShiftRow0(){
HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2");
s.shiftRows(0,4,1);
HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2");
s.shiftRows(0,4,1);
}
/**
* When shifting rows, the page breaks should go with it
*
@ -167,29 +127,25 @@ public class TestSheetShiftRows extends TestCase {
HSSFRow row = s.createRow(4);
row.createCell((short)0).setCellValue("test");
s.setRowBreak(4);
s.shiftRows(4, 4, 2);
assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6));
}
public void testShiftWithComments() throws Exception {
String filename = System.getProperty( "HSSF.testdata.path" );
filename = filename + "/comments.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("comments.xls");
HSSFSheet sheet = wb.getSheet("Sheet1");
assertEquals(3, sheet.getLastRowNum());
// Verify comments are in the position expected
assertNotNull(sheet.getCellComment(0,0));
assertNull(sheet.getCellComment(1,0));
assertNotNull(sheet.getCellComment(2,0));
assertNotNull(sheet.getCellComment(3,0));
String comment1 = sheet.getCellComment(0,0).getString().getString();
assertEquals(comment1,"comment top row1 (index0)\n");
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();
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);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wb.write(outputStream);
@ -216,7 +172,7 @@ public class TestSheetShiftRows extends TestCase {
assertEquals(comment3,comment3_shifted);
String comment4_shifted = sheet.getCellComment(4,0).getString().getString();
assertEquals(comment4,comment4_shifted);
// Write out and read back in again
// Ensure that the changes were persisted
wb = new HSSFWorkbook( new ByteArrayInputStream(outputStream.toByteArray()) );
@ -235,22 +191,18 @@ public class TestSheetShiftRows extends TestCase {
comment3_shifted = sheet.getCellComment(3,0).getString().getString();
assertEquals(comment3,comment3_shifted);
comment4_shifted = sheet.getCellComment(4,0).getString().getString();
assertEquals(comment4,comment4_shifted);
assertEquals(comment4,comment4_shifted);
}
/**
* See bug #34023
*/
public void testShiftWithFormulas() throws Exception {
String filename = System.getProperty( "HSSF.testdata.path" );
filename = filename + "/ForShifting.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
public void testShiftWithFormulas() {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ForShifting.xls");
HSSFSheet sheet = wb.getSheet("Sheet1");
assertEquals(19, sheet.getLastRowNum());
assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula());
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("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B2,\" (ref)\")", sheet.getRow(6).getCell((short)1).getCellFormula());
sheet.shiftRows(1, 1, 10);
// Row 1 => Row 11
// So strings on row 11 unchanged, but reference in formula is
assertEquals("cell B1 (ref)", sheet.getRow(0).getCell((short)3).getRichStringCellValue().toString());
assertEquals("CONCATENATE(B1,\" (ref)\")", sheet.getRow(0).getCell((short)3).getCellFormula());
assertEquals(0, sheet.getRow(1).getPhysicalNumberOfCells());
// still save b2
assertEquals("cell B2 (ref)", sheet.getRow(11).getCell((short)3).getRichStringCellValue().toString());
// 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("CONCATENATE(B3,\" (ref)\")", sheet.getRow(2).getCell((short)3).getCellFormula());
// one on a non-shifted row also updated
assertEquals("cell B2 (ref)", sheet.getRow(6).getCell((short)1).getRichStringCellValue().toString());
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
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.RecordFormatException;
/**
* @author aviks
*
* This testcase contains tests for bugs that are yet to be fixed.
* Therefore, the standard ant test target does not run these tests.
* Run this testcase with the single-test target.
* The names of the tests usually correspond to the Bugzilla id's
* PLEASE MOVE tests from this class to TestBugs once the bugs are fixed,
* so that they are then run automatically.
*
* This testcase contains tests for bugs that are yet to be fixed. Therefore,
* the standard ant test target does not run these tests. Run this testcase with
* the single-test target. The names of the tests usually correspond to the
* Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are
* fixed, so that they are then run automatically.
*/
public class TestUnfixedBugs extends TestCase {
public TestUnfixedBugs(String arg0) {
super(arg0);
public final class TestUnfixedBugs extends TestCase {
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
* limitations under the License.
*/
package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.InputStream;
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
* with a WORKBOOK directory entry (instead of the more
* usual, Workbook)
*/
public class TestUppercaseWorkbook extends TestCase {
private String dirPath;
private String xlsA = "WORKBOOK_in_capitals.xls";
public final class TestUppercaseWorkbook extends TestCase {
protected void setUp() throws Exception {
super.setUp();
dirPath = System.getProperty("HSSF.testdata.path");
}
private String xlsA = "WORKBOOK_in_capitals.xls";
/**
* Test that we can open a file with WORKBOOK
*/
public void testOpen() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA);
InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
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
*/
public void testWrite() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA);
InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is);
// Open the workbook, not preserving nodes
@ -96,7 +92,7 @@ public class TestUppercaseWorkbook extends TestCase {
* correct case
*/
public void testWritePreserve() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA);
InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is);
// Open the workbook, not preserving nodes

View File

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

View File

@ -14,24 +14,29 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
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.InputStream;
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 void testAreaRef1() {
@ -99,7 +104,7 @@ public final class TestAreaReference extends TestCase {
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 {
super(in);
}
@ -182,12 +187,9 @@ public final class TestAreaReference extends TestCase {
}
public void testDiscontinousReference() throws Exception {
String filename = System.getProperty( "HSSF.testdata.path" );
filename = filename + "/44167.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWB wb = new HSSFWB( fin );
InputStream is = HSSFTestDataSamples.openSampleFileStream("44167.xls");
HSSFWB wb = new HSSFWB(is);
Workbook workbook = wb.getWorkbook();
fin.close();
assertEquals(1, wb.getNumberOfNames());
String sheetName = "Tabelle1";
@ -269,5 +271,4 @@ public final class TestAreaReference extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(TestAreaReference.class);
}
}

View File

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

View File

@ -18,12 +18,21 @@
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.TestCase;
import java.io.*;
import java.util.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.property.DirectoryProperty;
import org.apache.poi.poifs.property.Property;
@ -36,45 +45,46 @@ import org.apache.poi.poifs.property.Property;
*
* @author Yegor Kozlov
*/
public class TestPropertySorter extends TestCase {
public final class TestPropertySorter extends TestCase {
//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",
"__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5",
"ThisWorkbook", "_VBA_PROJECT",
};
protected File testFile;
public void setUp(){
String home = System.getProperty("HSSF.testdata.path");
testFile = new File(home + "/39234.xls");
private static POIFSFileSystem openSampleFS() {
InputStream is = HSSFTestDataSamples.openSampleFileStream("39234.xls");
try {
return new POIFSFileSystem(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Test sorting of properties in <code>DirectoryProperty</code>
*/
public void testSortProperties() throws IOException {
InputStream is = new FileInputStream(testFile);
POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
POIFSFileSystem fs = openSampleFS();
Property[] props = getVBAProperties(fs);
assertEquals(_entries.length, props.length);
// (1). See that there is a problem with the old case-sensitive property comparartor
Arrays.sort(props, new CaseSensitivePropertyComparator());
// (1). See that there is a problem with the old case-sensitive property comparator
Arrays.sort(props, OldCaseSensitivePropertyComparator);
try {
for (int i = 0; i < props.length; i++) {
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){
; // 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());
for (int i = 0; i < props.length; i++) {
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.
*/
public void testSerialization() throws IOException {
InputStream is = new FileInputStream(testFile);
POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
POIFSFileSystem fs = openSampleFS();
ByteArrayOutputStream out = new ByteArrayOutputStream();
fs.writeFilesystem(out);
out.close();
is = new ByteArrayInputStream(out.toByteArray());
InputStream is = new ByteArrayInputStream(out.toByteArray());
fs = new POIFSFileSystem(is);
is.close();
Property[] props = getVBAProperties(fs);
@ -128,26 +136,17 @@ public class TestPropertySorter extends TestCase {
/**
* 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)
{
return this == o;
}
public int compare(Object o1, Object o2)
{
public int compare(Object o1, Object o2) {
String name1 = (( Property ) o1).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);
}
return result;
}
}
};
}