diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2015-09-07 20:19:50 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2015-09-07 20:19:50 +0000 |
commit | a3d2eb57ff4ac10ae215b9b7404260103eb6f538 (patch) | |
tree | 7b44ec32a7cdd0e0828779c793061ac6a00e4c00 /src/testcases/org/apache | |
parent | f2e85496125f7fc68f7434244b9d9d5bb026933d (diff) | |
download | poi-a3d2eb57ff4ac10ae215b9b7404260103eb6f538.tar.gz poi-a3d2eb57ff4ac10ae215b9b7404260103eb6f538.zip |
Bug 58326 - Forbidden APIs patches - first set of changes for locale and timezone settings
also includes fixes for
- name shadowing
- unused deprecated method "getClipRect" in classes extending Graphics2d
- HexDump - replaced intermediate String.format calls with custom padding
- convert testcases to junit4
- closing resources
also tested with an arbitary timezone (PST) and locale (ru)
supresses forbidden apis check for
- LocaleUtil (the only place where Locale.getDefault() and TimeZone.getDefault() should be called)
- Classes using FontMetrics - without the actual text it's difficult to return something sane
Some usage of UTC and Locale.ROOT might be still wrong, e.g. in MapiMessage we don't access the
extended mapi properties, which might contain the timezone
DataFormatter has now a Observable property which need to be observed when custom formats are used
and the Locale changes
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1701688 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/testcases/org/apache')
32 files changed, 1549 insertions, 1327 deletions
diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java index 6efa51bb5f..045f66f78d 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java @@ -38,6 +38,7 @@ import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Date; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import org.apache.poi.POIDataSamples; @@ -117,8 +118,8 @@ public class TestWrite * * @exception IOException if an I/O exception occurs */ - @Test - public void withoutAFormatID() throws IOException + @Test(expected=NoFormatIDException.class) + public void withoutAFormatID() throws Exception { final File filename = TempFile.createTempFile(POI_FS, ".doc"); @@ -131,8 +132,7 @@ public class TestWrite ps.addSection(new MutableSection()); /* Write it to a POIFS and the latter to disk: */ - try - { + try { final ByteArrayOutputStream psStream = new ByteArrayOutputStream(); ps.write(psStream); psStream.close(); @@ -140,15 +140,8 @@ public class TestWrite poiFs.createDocument(new ByteArrayInputStream(streamData), SummaryInformation.DEFAULT_STREAM_NAME); poiFs.writeFilesystem(out); - out.close(); - fail("Should have thrown a NoFormatIDException."); - } - catch (Exception ex) - { - assertTrue(ex instanceof NoFormatIDException); - } - finally - { + } finally { + poiFs.close(); out.close(); } } @@ -185,6 +178,7 @@ public class TestWrite poiFs.createDocument(new ByteArrayInputStream(streamData), SummaryInformation.DEFAULT_STREAM_NAME); poiFs.writeFilesystem(out); + poiFs.close(); out.close(); /* Read the POIFS: */ @@ -236,6 +230,7 @@ public class TestWrite poiFs.createDocument(ps.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME); poiFs.writeFilesystem(out); + poiFs.close(); out.close(); /* Read the POIFS: */ @@ -317,6 +312,7 @@ public class TestWrite poiFs.createDocument(ps.toInputStream(), STREAM_NAME); poiFs.writeFilesystem(out); + poiFs.close(); out.close(); /* Read the POIFS: */ @@ -755,6 +751,7 @@ public class TestWrite psf1[i].getName()); poiFs.writeFilesystem(out); } + poiFs.close(); out.close(); @@ -805,6 +802,7 @@ public class TestWrite Integer.valueOf(codepage)); poiFs.createDocument(ps1.toInputStream(), "Test"); poiFs.writeFilesystem(out); + poiFs.close(); out.close(); /* Read back: */ @@ -1010,7 +1008,7 @@ public class TestWrite // or via sun.misc.Cleaner, but this is regarded unsafe // http://stackoverflow.com/questions/2972986 // http://bugs.java.com/view_bug.do?bug_id=4724038 - Assume.assumeFalse(System.getProperty("os.name").toLowerCase().contains("win")); + Assume.assumeFalse(System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")); throw e; } } @@ -1022,7 +1020,7 @@ public class TestWrite * @throws IOException * @throws HPSFException */ - @Test + @Test(expected=IllegalPropertySetDataException.class) public void dictionaryWithInvalidCodepage() throws IOException, HPSFException { final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); @@ -1039,8 +1037,7 @@ public class TestWrite m.put(Long.valueOf(2), "String 2"); m.put(Long.valueOf(3), "String 3"); - try - { + try { s.setDictionary(m); s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID[0]); int codepage = 12345; @@ -1048,13 +1045,9 @@ public class TestWrite Integer.valueOf(codepage)); poiFs.createDocument(ps1.toInputStream(), "Test"); poiFs.writeFilesystem(out); + } finally { + poiFs.close(); out.close(); - fail("This testcase did not detect the invalid codepage value."); - } - catch (IllegalPropertySetDataException ex) - { - out.close(); - assertTrue(true); } } @@ -1069,7 +1062,7 @@ public class TestWrite { final String charSetName = System.getProperty("file.encoding"); final Charset charSet = Charset.forName(charSetName); - return charSet.displayName(); + return charSet.displayName(Locale.ROOT); } diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java b/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java index b58b4cd8f0..6769861e46 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java @@ -17,6 +17,12 @@ package org.apache.poi.hpsf.basic; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; @@ -26,45 +32,47 @@ import java.io.IOException; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; -import java.util.GregorianCalendar; import java.util.HashMap; -import java.util.Locale; import java.util.Map; -import junit.framework.TestCase; - import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.*; +import org.apache.poi.hpsf.CustomProperties; +import org.apache.poi.hpsf.CustomProperty; +import org.apache.poi.hpsf.DocumentSummaryInformation; +import org.apache.poi.hpsf.MarkUnsupportedException; +import org.apache.poi.hpsf.MutableProperty; +import org.apache.poi.hpsf.MutableSection; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; +import org.apache.poi.hpsf.Variant; +import org.apache.poi.hpsf.VariantSupport; +import org.apache.poi.hpsf.WritingNotSupportedException; import org.apache.poi.hpsf.wellknown.SectionIDMap; import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; +import org.apache.poi.util.IOUtils; +import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.TempFile; +import org.junit.BeforeClass; +import org.junit.Test; /** * <p>Tests HPSF's high-level writing functionality for the well-known property * set "SummaryInformation" and "DocumentSummaryInformation".</p> - * - * @author Rainer Klute - * <a href="mailto:klute@rainer-klute.de">klute@rainer-klute.de</a> */ -public class TestWriteWellKnown extends TestCase { +public class TestWriteWellKnown { private static final String POI_FS = "TestWriteWellKnown.doc"; - - /** - * @see TestCase#setUp() - */ - @Override - public void setUp() - { + @BeforeClass + public static void setUp() { VariantSupport.setLogUnsupportedTypes(false); } - - /** * <p>This test method checks whether DocumentSummary information streams * can be read. This is done by opening all "Test*" files in the 'poifs' directrory @@ -72,6 +80,7 @@ public class TestWriteWellKnown extends TestCase { * the document summary information stream in the root directory and calling * its get... methods.</p> */ + @Test public void testReadDocumentSummaryInformation() throws FileNotFoundException, IOException, NoPropertySetStreamException, MarkUnsupportedException, @@ -88,36 +97,18 @@ public class TestWriteWellKnown extends TestCase { } }); - for (int i = 0; i < docs.length; i++) - { + for (final File doc : docs) { + NPOIFSFileSystem poifs = null; try { - final File doc = docs[i]; - /* Read a test document <em>doc</em> into a POI filesystem. */ - final POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream(doc)); + poifs = new NPOIFSFileSystem(doc, true); final DirectoryEntry dir = poifs.getRoot(); - DocumentEntry dsiEntry = null; - try - { - dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - } - catch (FileNotFoundException ex) - { - /* - * A missing document summary information stream is not an error - * and therefore silently ignored here. - */ - } - /* * If there is a document summry information stream, read it from * the POI filesystem. */ - if (dsiEntry != null) - { - final DocumentInputStream dis = new DocumentInputStream(dsiEntry); - final PropertySet ps = new PropertySet(dis); - final DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps); + if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { + final DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); /* Execute the get... methods. */ dsi.getByteCount(); @@ -139,12 +130,72 @@ public class TestWriteWellKnown extends TestCase { dsi.getSlideCount(); } } catch (Exception e) { - throw new IOException("While handling file " + docs[i], e); + throw new IOException("While handling file " + doc, e); + } finally { + if (poifs != null) poifs.close(); } } } - + static final String P_APPLICATION_NAME = "ApplicationName"; + static final String P_AUTHOR = "Author"; + static final int P_CHAR_COUNT = 4712; + static final String P_COMMENTS = "Comments"; + static final Date P_CREATE_DATE_TIME; + static final long P_EDIT_TIME = 4713 * 1000 * 10; + static final String P_KEYWORDS = "Keywords"; + static final String P_LAST_AUTHOR = "LastAuthor"; + static final Date P_LAST_PRINTED; + static final Date P_LAST_SAVE_DATE_TIME; + static final int P_PAGE_COUNT = 4714; + static final String P_REV_NUMBER = "RevNumber"; + static final int P_SECURITY = 1; + static final String P_SUBJECT = "Subject"; + static final String P_TEMPLATE = "Template"; + // FIXME (byte array properties not yet implemented): static final byte[] P_THUMBNAIL = new byte[123]; + static final String P_TITLE = "Title"; + static final int P_WORD_COUNT = 4715; + + static final int P_BYTE_COUNT = 4716; + static final String P_CATEGORY = "Category"; + static final String P_COMPANY = "Company"; + // FIXME (byte array properties not yet implemented): static final byte[] P_DOCPARTS = new byte[123]; + // FIXME (byte array properties not yet implemented): static final byte[] P_HEADING_PAIR = new byte[123]; + static final int P_HIDDEN_COUNT = 4717; + static final int P_LINE_COUNT = 4718; + static final boolean P_LINKS_DIRTY = true; + static final String P_MANAGER = "Manager"; + static final int P_MM_CLIP_COUNT = 4719; + static final int P_NOTE_COUNT = 4720; + static final int P_PAR_COUNT = 4721; + static final String P_PRESENTATION_FORMAT = "PresentationFormat"; + static final boolean P_SCALE = false; + static final int P_SLIDE_COUNT = 4722; + static final Date now = new Date(); + + static final Integer POSITIVE_INTEGER = new Integer(2222); + static final Long POSITIVE_LONG = new Long(3333); + static final Double POSITIVE_DOUBLE = new Double(4444); + static final Integer NEGATIVE_INTEGER = new Integer(2222); + static final Long NEGATIVE_LONG = new Long(3333); + static final Double NEGATIVE_DOUBLE = new Double(4444); + + static final Integer MAX_INTEGER = new Integer(Integer.MAX_VALUE); + static final Integer MIN_INTEGER = new Integer(Integer.MIN_VALUE); + static final Long MAX_LONG = new Long(Long.MAX_VALUE); + static final Long MIN_LONG = new Long(Long.MIN_VALUE); + static final Double MAX_DOUBLE = new Double(Double.MAX_VALUE); + static final Double MIN_DOUBLE = new Double(Double.MIN_VALUE); + + static { + Calendar cal = LocaleUtil.getLocaleCalendar(2000, 6, 6, 6, 6, 6); + P_CREATE_DATE_TIME = cal.getTime(); + cal.set(2001, 7, 7, 7, 7, 7); + P_LAST_PRINTED = cal.getTime(); + cal.set(2002, 8, 8, 8, 8, 8); + P_LAST_SAVE_DATE_TIME = cal.getTime(); + } + /** * <p>This test method test the writing of properties in the well-known * property set streams "SummaryInformation" and @@ -192,19 +243,35 @@ public class TestWriteWellKnown extends TestCase { * @throws UnexpectedPropertySetTypeException * @throws WritingNotSupportedException */ - public void testWriteWellKnown() throws IOException, - NoPropertySetStreamException, MarkUnsupportedException, - UnexpectedPropertySetTypeException, WritingNotSupportedException - { + @Test + public void testWriteWellKnown() throws Exception { POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File doc1 = new File(dataDir, POI_FS); - + + final File doc1 = TempFile.createTempFile("POI_HPSF_Test1.", ".tmp"); + final File doc2 = TempFile.createTempFile("POI_HPSF_Test2.", ".tmp"); + final File doc3 = TempFile.createTempFile("POI_HPSF_Test3.", ".tmp"); + + FileInputStream fis = new FileInputStream(_samples.getFile(POI_FS)); + FileOutputStream fos = new FileOutputStream(doc1); + IOUtils.copy(fis, fos); + fos.close(); + fis.close(); + + CustomProperties cps1 = write1stFile(doc1, doc2); + CustomProperties cps2 = write2ndFile(doc2, doc3); + write3rdFile(doc3, null); + + assertEquals(cps1, cps2); + } + + /* + * Write all properties supported by HPSF to the summary information + * (e.g. author, edit date, application name) and to the document + * summary information (e.g. company, manager). + */ + private static CustomProperties write1stFile(File fileIn, File fileOut) throws Exception { /* Read a test document <em>doc1</em> into a POI filesystem. */ - POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream(doc1)); - DirectoryEntry dir = poifs.getRoot(); - DocumentEntry siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - DocumentEntry dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); + NPOIFSFileSystem poifs = new NPOIFSFileSystem(fileIn, false); /* * Read the summary information stream and the document summary @@ -216,76 +283,8 @@ public class TestWriteWellKnown extends TestCase { * explicitly (overwriting the former contents). Then the POI filesystem * should be saved to a file. */ - DocumentInputStream dis = new DocumentInputStream(siEntry); - PropertySet ps = new PropertySet(dis); - SummaryInformation si = new SummaryInformation(ps); - dis = new DocumentInputStream(dsiEntry); - ps = new PropertySet(dis); - DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps); - - /* - * Write all properties supported by HPSF to the summary information - * (e.g. author, edit date, application name) and to the document - * summary information (e.g. company, manager). - */ - Calendar cal = new GregorianCalendar(Locale.ROOT); - cal.set(2000, 6, 6, 6, 6, 6); - final long time1 = cal.getTimeInMillis(); - cal.set(2001, 7, 7, 7, 7, 7); - final long time2 = cal.getTimeInMillis(); - cal.set(2002, 8, 8, 8, 8, 8); - final long time3 = cal.getTimeInMillis(); - - int nr = 4711; - final String P_APPLICATION_NAME = "ApplicationName"; - final String P_AUTHOR = "Author"; - final int P_CHAR_COUNT = ++nr; - final String P_COMMENTS = "Comments"; - final Date P_CREATE_DATE_TIME = new Date(time1); - final long P_EDIT_TIME = ++nr * 1000 * 10; - final String P_KEYWORDS = "Keywords"; - final String P_LAST_AUTHOR = "LastAuthor"; - final Date P_LAST_PRINTED = new Date(time2); - final Date P_LAST_SAVE_DATE_TIME = new Date(time3); - final int P_PAGE_COUNT = ++nr; - final String P_REV_NUMBER = "RevNumber"; - final int P_SECURITY = 1; - final String P_SUBJECT = "Subject"; - final String P_TEMPLATE = "Template"; - // FIXME (byte array properties not yet implemented): final byte[] P_THUMBNAIL = new byte[123]; - final String P_TITLE = "Title"; - final int P_WORD_COUNT = ++nr; - - final int P_BYTE_COUNT = ++nr; - final String P_CATEGORY = "Category"; - final String P_COMPANY = "Company"; - // FIXME (byte array properties not yet implemented): final byte[] P_DOCPARTS = new byte[123]; - // FIXME (byte array properties not yet implemented): final byte[] P_HEADING_PAIR = new byte[123]; - final int P_HIDDEN_COUNT = ++nr; - final int P_LINE_COUNT = ++nr; - final boolean P_LINKS_DIRTY = true; - final String P_MANAGER = "Manager"; - final int P_MM_CLIP_COUNT = ++nr; - final int P_NOTE_COUNT = ++nr; - final int P_PAR_COUNT = ++nr; - final String P_PRESENTATION_FORMAT = "PresentationFormat"; - final boolean P_SCALE = false; - final int P_SLIDE_COUNT = ++nr; - final Date now = new Date(); - - final Integer POSITIVE_INTEGER = new Integer(2222); - final Long POSITIVE_LONG = new Long(3333); - final Double POSITIVE_DOUBLE = new Double(4444); - final Integer NEGATIVE_INTEGER = new Integer(2222); - final Long NEGATIVE_LONG = new Long(3333); - final Double NEGATIVE_DOUBLE = new Double(4444); - - final Integer MAX_INTEGER = new Integer(Integer.MAX_VALUE); - final Integer MIN_INTEGER = new Integer(Integer.MIN_VALUE); - final Long MAX_LONG = new Long(Long.MAX_VALUE); - final Long MIN_LONG = new Long(Long.MIN_VALUE); - final Double MAX_DOUBLE = new Double(Double.MAX_VALUE); - final Double MIN_DOUBLE = new Double(Double.MIN_VALUE); + SummaryInformation si = getSummaryInformation(poifs); + DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); si.setApplicationName(P_APPLICATION_NAME); si.setAuthor(P_AUTHOR); @@ -322,76 +321,71 @@ public class TestWriteWellKnown extends TestCase { dsi.setScale(P_SCALE); dsi.setSlideCount(P_SLIDE_COUNT); - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) - customProperties = new CustomProperties(); - customProperties.put("Schl\u00fcssel \u00e4", "Wert \u00e4"); - customProperties.put("Schl\u00fcssel \u00e4\u00f6", "Wert \u00e4\u00f6"); - customProperties.put("Schl\u00fcssel \u00e4\u00f6\u00fc", "Wert \u00e4\u00f6\u00fc"); - customProperties.put("Schl\u00fcssel \u00e4\u00f6\u00fc\u00d6", "Wert \u00e4\u00f6\u00fc\u00d6"); - customProperties.put("positive_Integer", POSITIVE_INTEGER); - customProperties.put("positive_Long", POSITIVE_LONG); - customProperties.put("positive_Double", POSITIVE_DOUBLE); - customProperties.put("negative_Integer", NEGATIVE_INTEGER); - customProperties.put("negative_Long", NEGATIVE_LONG); - customProperties.put("negative_Double", NEGATIVE_DOUBLE); - customProperties.put("Boolean", Boolean.TRUE); - customProperties.put("Date", now); - customProperties.put("max_Integer", MAX_INTEGER); - customProperties.put("min_Integer", MIN_INTEGER); - customProperties.put("max_Long", MAX_LONG); - customProperties.put("min_Long", MIN_LONG); - customProperties.put("max_Double", MAX_DOUBLE); - customProperties.put("min_Double", MIN_DOUBLE); + CustomProperties cps = dsi.getCustomProperties(); + assertNull(cps); + cps = new CustomProperties(); + cps.put("Schl\u00fcssel \u00e4", "Wert \u00e4"); + cps.put("Schl\u00fcssel \u00e4\u00f6", "Wert \u00e4\u00f6"); + cps.put("Schl\u00fcssel \u00e4\u00f6\u00fc", "Wert \u00e4\u00f6\u00fc"); + cps.put("Schl\u00fcssel \u00e4\u00f6\u00fc\u00d6", "Wert \u00e4\u00f6\u00fc\u00d6"); + cps.put("positive_Integer", POSITIVE_INTEGER); + cps.put("positive_Long", POSITIVE_LONG); + cps.put("positive_Double", POSITIVE_DOUBLE); + cps.put("negative_Integer", NEGATIVE_INTEGER); + cps.put("negative_Long", NEGATIVE_LONG); + cps.put("negative_Double", NEGATIVE_DOUBLE); + cps.put("Boolean", Boolean.TRUE); + cps.put("Date", now); + cps.put("max_Integer", MAX_INTEGER); + cps.put("min_Integer", MIN_INTEGER); + cps.put("max_Long", MAX_LONG); + cps.put("min_Long", MIN_LONG); + cps.put("max_Double", MAX_DOUBLE); + cps.put("min_Double", MIN_DOUBLE); // Check the keys went in - assertTrue(customProperties.containsKey("Schl\u00fcssel \u00e4")); - assertTrue(customProperties.containsKey("Boolean")); + assertTrue(cps.containsKey("Schl\u00fcssel \u00e4")); + assertTrue(cps.containsKey("Boolean")); // Check the values went in - assertEquals("Wert \u00e4", customProperties.get("Schl\u00fcssel \u00e4")); - assertEquals(Boolean.TRUE, customProperties.get("Boolean")); - assertTrue(customProperties.containsValue(Boolean.TRUE)); - assertTrue(customProperties.containsValue("Wert \u00e4")); + assertEquals("Wert \u00e4", cps.get("Schl\u00fcssel \u00e4")); + assertEquals(Boolean.TRUE, cps.get("Boolean")); + assertTrue(cps.containsValue(Boolean.TRUE)); + assertTrue(cps.containsValue("Wert \u00e4")); // Check that things that aren't in aren't in - assertFalse(customProperties.containsKey("False Boolean")); - assertFalse(customProperties.containsValue(Boolean.FALSE)); + assertFalse(cps.containsKey("False Boolean")); + assertFalse(cps.containsValue(Boolean.FALSE)); // Save as our custom properties - dsi.setCustomProperties(customProperties); + dsi.setCustomProperties(cps); /* Write the summary information stream and the document summary * information stream to the POI filesystem. */ - si.write(dir, siEntry.getName()); - dsi.write(dir, dsiEntry.getName()); + si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); + dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); /* Write the POI filesystem to a (temporary) file <em>doc2</em> * and close the latter. */ - final File doc2 = TempFile.createTempFile("POI_HPSF_Test.", ".tmp"); - doc2.deleteOnExit(); - OutputStream out = new FileOutputStream(doc2); + OutputStream out = new FileOutputStream(fileOut); poifs.writeFilesystem(out); out.close(); - - /* - * Open <em>doc2</em> for reading and check summary information and - * document summary information. All properties written before must be - * found in the property streams of <em>doc2</em> and have the correct - * values. - */ - poifs = new POIFSFileSystem(new FileInputStream(doc2)); - dir = poifs.getRoot(); - siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - dis = new DocumentInputStream(siEntry); - ps = new PropertySet(dis); - si = new SummaryInformation(ps); - dis = new DocumentInputStream(dsiEntry); - ps = new PropertySet(dis); - dsi = new DocumentSummaryInformation(ps); + poifs.close(); + + return cps; + } + + /* + * Open <em>doc2</em> for reading and check summary information and + * document summary information. All properties written before must be + * found in the property streams of <em>doc2</em> and have the correct + * values. + */ + private static CustomProperties write2ndFile(File fileIn, File fileOut) throws Exception { + NPOIFSFileSystem poifs = new NPOIFSFileSystem(fileIn, false); + SummaryInformation si = getSummaryInformation(poifs); + DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); assertEquals(P_APPLICATION_NAME, si.getApplicationName()); assertEquals(P_AUTHOR, si.getAuthor()); @@ -429,7 +423,7 @@ public class TestWriteWellKnown extends TestCase { assertEquals(P_SLIDE_COUNT, dsi.getSlideCount()); final CustomProperties cps = dsi.getCustomProperties(); - assertEquals(customProperties, cps); + assertNotNull(cps); assertNull(cps.get("No value available")); assertEquals("Wert \u00e4", cps.get("Schl\u00fcssel \u00e4")); assertEquals("Wert \u00e4\u00f6", cps.get("Schl\u00fcssel \u00e4\u00f6")); @@ -492,93 +486,108 @@ public class TestWriteWellKnown extends TestCase { /* * <li><p>Write the summary information stream and the document summary * information stream to the POI filesystem. */ - si.write(dir, siEntry.getName()); - dsi.write(dir, dsiEntry.getName()); + si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); + dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); /* * <li><p>Write the POI filesystem to a (temporary) file <em>doc3</em> * and close the latter. */ - final File doc3 = TempFile.createTempFile("POI_HPSF_Test.", ".tmp"); - doc3.deleteOnExit(); - out = new FileOutputStream(doc3); + FileOutputStream out = new FileOutputStream(fileOut); poifs.writeFilesystem(out); out.close(); + poifs.close(); + + return cps; + } + + /* + * Open <em>doc3</em> for reading and check summary information + * and document summary information. All properties removed before must not + * be found in the property streams of <em>doc3</em>. + */ + private static CustomProperties write3rdFile(File fileIn, File fileOut) throws Exception { + NPOIFSFileSystem poifs = new NPOIFSFileSystem(fileIn, false); + SummaryInformation si = getSummaryInformation(poifs); + DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - /* - * Open <em>doc3</em> for reading and check summary information - * and document summary information. All properties removed before must not - * be found in the property streams of <em>doc3</em>. - */ - poifs = new POIFSFileSystem(new FileInputStream(doc3)); - dir = poifs.getRoot(); - siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - dis = new DocumentInputStream(siEntry); - ps = new PropertySet(dis); - si = new SummaryInformation(ps); - dis = new DocumentInputStream(dsiEntry); - ps = new PropertySet(dis); - dsi = new DocumentSummaryInformation(ps); - - assertEquals(null, si.getApplicationName()); - assertEquals(null, si.getAuthor()); + assertNull(si.getApplicationName()); + assertNull(si.getAuthor()); assertEquals(0, si.getCharCount()); assertTrue(si.wasNull()); - assertEquals(null, si.getComments()); - assertEquals(null, si.getCreateDateTime()); + assertNull(si.getComments()); + assertNull(si.getCreateDateTime()); assertEquals(0, si.getEditTime()); assertTrue(si.wasNull()); - assertEquals(null, si.getKeywords()); - assertEquals(null, si.getLastAuthor()); - assertEquals(null, si.getLastPrinted()); - assertEquals(null, si.getLastSaveDateTime()); + assertNull(si.getKeywords()); + assertNull(si.getLastAuthor()); + assertNull(si.getLastPrinted()); + assertNull(si.getLastSaveDateTime()); assertEquals(0, si.getPageCount()); assertTrue(si.wasNull()); - assertEquals(null, si.getRevNumber()); + assertNull(si.getRevNumber()); assertEquals(0, si.getSecurity()); assertTrue(si.wasNull()); - assertEquals(null, si.getSubject()); - assertEquals(null, si.getTemplate()); - assertEquals(null, si.getThumbnail()); - assertEquals(null, si.getTitle()); + assertNull(si.getSubject()); + assertNull(si.getTemplate()); + assertNull(si.getThumbnail()); + assertNull(si.getTitle()); assertEquals(0, si.getWordCount()); assertTrue(si.wasNull()); assertEquals(0, dsi.getByteCount()); assertTrue(dsi.wasNull()); - assertEquals(null, dsi.getCategory()); - assertEquals(null, dsi.getCustomProperties()); - // FIXME (byte array properties not yet implemented): assertEquals(null, dsi.getDocparts()); - // FIXME (byte array properties not yet implemented): assertEquals(null, dsi.getHeadingPair()); + assertNull(dsi.getCategory()); + assertNull(dsi.getCustomProperties()); + // FIXME (byte array properties not yet implemented): assertNull(dsi.getDocparts()); + // FIXME (byte array properties not yet implemented): assertNull(dsi.getHeadingPair()); assertEquals(0, dsi.getHiddenCount()); assertTrue(dsi.wasNull()); assertEquals(0, dsi.getLineCount()); assertTrue(dsi.wasNull()); - assertEquals(false, dsi.getLinksDirty()); + assertFalse(dsi.getLinksDirty()); assertTrue(dsi.wasNull()); - assertEquals(null, dsi.getManager()); + assertNull(dsi.getManager()); assertEquals(0, dsi.getMMClipCount()); assertTrue(dsi.wasNull()); assertEquals(0, dsi.getNoteCount()); assertTrue(dsi.wasNull()); assertEquals(0, dsi.getParCount()); assertTrue(dsi.wasNull()); - assertEquals(null, dsi.getPresentationFormat()); - assertEquals(false, dsi.getScale()); + assertNull(dsi.getPresentationFormat()); + assertFalse(dsi.getScale()); assertTrue(dsi.wasNull()); assertEquals(0, dsi.getSlideCount()); assertTrue(dsi.wasNull()); + poifs.close(); + + return dsi.getCustomProperties(); } + private static SummaryInformation getSummaryInformation(NPOIFSFileSystem poifs) throws Exception { + DocumentInputStream dis = poifs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME); + PropertySet ps = new PropertySet(dis); + SummaryInformation si = new SummaryInformation(ps); + dis.close(); + return si; + } + + private static DocumentSummaryInformation getDocumentSummaryInformation(NPOIFSFileSystem poifs) throws Exception { + DocumentInputStream dis = poifs.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME); + PropertySet ps = new PropertySet(dis); + DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps); + dis.close(); + return dsi; + } - + + /** * <p>Tests the simplified custom properties by reading them from the * available test files.</p> * * @throws Throwable if anything goes wrong. */ + @Test public void testReadCustomPropertiesFromFiles() throws Throwable { final AllDataFilesTester.TestTask task = new AllDataFilesTester.TestTask() @@ -590,43 +599,35 @@ public class TestWriteWellKnown extends TestCase { UnexpectedPropertySetTypeException { /* Read a test document <em>doc</em> into a POI filesystem. */ - final POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream(file)); - final DirectoryEntry dir = poifs.getRoot(); - DocumentEntry dsiEntry = null; - try - { - dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - } - catch (FileNotFoundException ex) - { + NPOIFSFileSystem poifs = null; + try { + poifs = new NPOIFSFileSystem(file); + final DirectoryEntry dir = poifs.getRoot(); /* - * A missing document summary information stream is not an error - * and therefore silently ignored here. + * If there is a document summry information stream, read it from + * the POI filesystem, else create a new one. */ - } - - /* - * If there is a document summry information stream, read it from - * the POI filesystem, else create a new one. - */ - DocumentSummaryInformation dsi; - if (dsiEntry != null) - { - final DocumentInputStream dis = new DocumentInputStream(dsiEntry); - final PropertySet ps = new PropertySet(dis); - dsi = new DocumentSummaryInformation(ps); - } - else - dsi = PropertySetFactory.newDocumentSummaryInformation(); - final CustomProperties cps = dsi.getCustomProperties(); - - if (cps == null) - /* The document does not have custom properties. */ - return; - - for (CustomProperty cp : cps.values()) { - cp.getName(); - cp.getValue(); + DocumentSummaryInformation dsi; + if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { + final DocumentInputStream dis = poifs.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME); + final PropertySet ps = new PropertySet(dis); + dsi = new DocumentSummaryInformation(ps); + dis.close(); + } else { + dsi = PropertySetFactory.newDocumentSummaryInformation(); + } + final CustomProperties cps = dsi.getCustomProperties(); + + if (cps == null) + /* The document does not have custom properties. */ + return; + + for (CustomProperty cp : cps.values()) { + cp.getName(); + cp.getValue(); + } + } finally { + if (poifs != null) poifs.close(); } } }; @@ -657,6 +658,7 @@ public class TestWriteWellKnown extends TestCase { /** * <p>Tests basic custom property features.</p> */ + @Test public void testCustomerProperties() { final String KEY = "Schl\u00fcssel \u00e4"; @@ -695,6 +697,7 @@ public class TestWriteWellKnown extends TestCase { * <p>Tests reading custom properties from a section including reading * custom properties which are not pure.</p> */ + @Test public void testGetCustomerProperties() { final int ID_1 = 2; @@ -709,7 +712,7 @@ public class TestWriteWellKnown extends TestCase { /* A document summary information set stream by default does have custom properties. */ cps = dsi.getCustomProperties(); - assertEquals(null, cps); + assertNull(cps); /* Test an empty custom properties set. */ s = new MutableSection(); diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java index 793215a028..15f4a3cb0b 100644 --- a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java +++ b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java @@ -17,10 +17,13 @@ package org.apache.poi.hssf.extractor; -import java.io.IOException; -import java.io.InputStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; -import junit.framework.TestCase; +import java.io.File; +import java.io.IOException; +import java.util.Locale; import org.apache.poi.POIDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples; @@ -28,24 +31,22 @@ import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; /** * */ -public final class TestExcelExtractor extends TestCase { - - private static ExcelExtractor createExtractor(String sampleFileName) { - - InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); +public final class TestExcelExtractor { - try { - return new ExcelExtractor(new POIFSFileSystem(is)); - } catch (IOException e) { - throw new RuntimeException(e); - } + @SuppressWarnings("resource") + private static ExcelExtractor createExtractor(String sampleFileName) throws IOException { + File file = HSSFTestDataSamples.getSampleFile(sampleFileName); + return new ExcelExtractor(new POIFSFileSystem(file)); } + @Test public void testSimple() throws IOException { ExcelExtractor extractor = createExtractor("Simple.xls"); @@ -60,7 +61,8 @@ public final class TestExcelExtractor extends TestCase { } } - public void testNumericFormula() { + @Test + public void testNumericFormula() throws IOException { ExcelExtractor extractor = createExtractor("sumifformula.xls"); @@ -87,9 +89,12 @@ public final class TestExcelExtractor extends TestCase { "Sheet2\nSheet3\n", extractor.getText() ); + + extractor.close(); } - public void testwithContinueRecords() { + @Test + public void testwithContinueRecords() throws IOException { ExcelExtractor extractor = createExtractor("StringContinueRecords.xls"); @@ -99,9 +104,12 @@ public final class TestExcelExtractor extends TestCase { // Until we fixed bug #41064, this would've // failed by now assertTrue(extractor.getText().length() > 40960); + + extractor.close(); } - public void testStringConcat() { + @Test + public void testStringConcat() throws IOException { ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls"); @@ -112,9 +120,12 @@ public final class TestExcelExtractor extends TestCase { extractor.setFormulasNotResults(true); assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText()); + + extractor.close(); } - public void testStringFormula() { + @Test + public void testStringFormula() throws IOException { ExcelExtractor extractor = createExtractor("StringFormulas.xls"); @@ -125,40 +136,49 @@ public final class TestExcelExtractor extends TestCase { extractor.setFormulasNotResults(true); assertEquals("Sheet1\nUPPER(\"xyz\")\nSheet2\nSheet3\n", extractor.getText()); + + extractor.close(); } - public void testEventExtractor() throws Exception { + @Test + public void testEventExtractor() throws Exception { // First up, a simple file with string // based formulas in it - EventBasedExcelExtractor extractor = new EventBasedExcelExtractor( - new POIFSFileSystem( - HSSFTestDataSamples.openSampleFileStream("SimpleWithFormula.xls") - ) - ); + EventBasedExcelExtractor extractor1 = null; try { - extractor.setIncludeSheetNames(true); - - String text = extractor.getText(); + extractor1 = new EventBasedExcelExtractor( + new POIFSFileSystem( + HSSFTestDataSamples.openSampleFileStream("SimpleWithFormula.xls") + ) + ); + extractor1.setIncludeSheetNames(true); + + String text = extractor1.getText(); assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", text); - extractor.setIncludeSheetNames(false); - extractor.setFormulasNotResults(true); + extractor1.setIncludeSheetNames(false); + extractor1.setFormulasNotResults(true); - text = extractor.getText(); + text = extractor1.getText(); assertEquals("replaceme\nreplaceme\nCONCATENATE(A1,A2)\n", text); + } finally { + if (extractor1 != null) extractor1.close(); + } + + // Now, a slightly longer file with numeric formulas + EventBasedExcelExtractor extractor2 = null; + try { + extractor2 = new EventBasedExcelExtractor( + new POIFSFileSystem( + HSSFTestDataSamples.openSampleFileStream("sumifformula.xls") + ) + ); + + extractor2.setIncludeSheetNames(false); + extractor2.setFormulasNotResults(true); - - // Now, a slightly longer file with numeric formulas - extractor = new EventBasedExcelExtractor( - new POIFSFileSystem( - HSSFTestDataSamples.openSampleFileStream("sumifformula.xls") - ) - ); - extractor.setIncludeSheetNames(false); - extractor.setFormulasNotResults(true); - - text = extractor.getText(); + String text = extractor2.getText(); assertEquals( "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + "2000\t2\n" + @@ -168,11 +188,12 @@ public final class TestExcelExtractor extends TestCase { text ); } finally { - extractor.close(); + if (extractor2 != null) extractor2.close(); } } - public void testWithComments() { + @Test + public void testWithComments() throws IOException { ExcelExtractor extractor = createExtractor("SimpleWithComments.xls"); extractor.setIncludeSheetNames(false); @@ -192,9 +213,12 @@ public final class TestExcelExtractor extends TestCase { "3\tthree Comment by Yegor Kozlov: Yegor Kozlov: third cell\n", extractor.getText() ); + + extractor.close(); } - public void testWithBlank() { + @Test + public void testWithBlank() throws IOException { ExcelExtractor extractor = createExtractor("MissingBits.xls"); String def = extractor.getText(); extractor.setIncludeBlankCells(true); @@ -213,136 +237,145 @@ public final class TestExcelExtractor extends TestCase { "Hello\n" + "11\t\t\t23\n" )); + + extractor.close(); } - public void testFormatting() throws Exception { - ExcelExtractor extractor = createExtractor("Formatting.xls"); - extractor.setIncludeBlankCells(false); - extractor.setIncludeSheetNames(false); - String text = extractor.getText(); - - // Note - not all the formats in the file - // actually quite match what they claim to - // be, as some are auto-local builtins... - - assertTrue(text.startsWith( - "Dates, all 24th November 2006\n" - )); - assertTrue( - text.indexOf( - "yyyy/mm/dd\t2006/11/24\n" - ) > -1 - ); - assertTrue( - text.indexOf( - "yyyy-mm-dd\t2006-11-24\n" - ) > -1 - ); - assertTrue( - text.indexOf( - "dd-mm-yy\t24-11-06\n" - ) > -1 - ); - - assertTrue("Had: " + text + ", but should contain 'nn.nn\\t10.52\\n'", - text.indexOf( - "nn.nn\t10.52\n" - ) > -1 - ); - assertTrue( - text.indexOf( - "nn.nnn\t10.520\n" - ) > -1 - ); - assertTrue( - text.indexOf( - "\u00a3nn.nn\t\u00a310.52\n" - ) > -1 - ); + @Test + public void testFormatting() throws Exception { + Locale userLocale = LocaleUtil.getUserLocale(); + LocaleUtil.setUserLocale(Locale.ROOT); + try { + ExcelExtractor extractor = createExtractor("Formatting.xls"); + extractor.setIncludeBlankCells(false); + extractor.setIncludeSheetNames(false); + String text = extractor.getText(); + + // Note - not all the formats in the file + // actually quite match what they claim to + // be, as some are auto-local builtins... + + assertTrue(text.startsWith( + "Dates, all 24th November 2006\n" + )); + assertTrue( + text.indexOf( + "yyyy/mm/dd\t2006/11/24\n" + ) > -1 + ); + assertTrue( + text.indexOf( + "yyyy-mm-dd\t2006-11-24\n" + ) > -1 + ); + assertTrue( + text.indexOf( + "dd-mm-yy\t24-11-06\n" + ) > -1 + ); + + assertTrue("Had: " + text + ", but should contain 'nn.nn\\t10.52\\n'", + text.indexOf( + "nn.nn\t10.52\n" + ) > -1 + ); + assertTrue( + text.indexOf( + "nn.nnn\t10.520\n" + ) > -1 + ); + assertTrue( + text.indexOf( + "\u00a3nn.nn\t\u00a310.52\n" + ) > -1 + ); + extractor.close(); + } finally { + LocaleUtil.setUserLocale(userLocale); + } } /** * Embeded in a non-excel file */ - public void testWithEmbeded() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem( - POIDataSamples.getDocumentInstance().openResourceAsStream("word_with_embeded.doc") - ); - - DirectoryNode objPool = (DirectoryNode) fs.getRoot().getEntry("ObjectPool"); - DirectoryNode dirA = (DirectoryNode) objPool.getEntry("_1269427460"); - DirectoryNode dirB = (DirectoryNode) objPool.getEntry("_1269427461"); + @Test + public void testWithEmbeded() throws Exception { + POIFSFileSystem fs = null; + + HSSFWorkbook wbA = null, wbB = null; + ExcelExtractor exA = null, exB = null; - HSSFWorkbook wbA = new HSSFWorkbook(dirA, fs, true); - HSSFWorkbook wbB = new HSSFWorkbook(dirB, fs, true); - - ExcelExtractor exA = new ExcelExtractor(wbA); try { - ExcelExtractor exB = new ExcelExtractor(wbB); - try { - assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", - exA.getText()); - assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); - - assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", - exB.getText()); - assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); - } finally { - exB.close(); - } + fs = new POIFSFileSystem(POIDataSamples.getDocumentInstance().getFile("word_with_embeded.doc")); + + DirectoryNode objPool = (DirectoryNode) fs.getRoot().getEntry("ObjectPool"); + DirectoryNode dirA = (DirectoryNode) objPool.getEntry("_1269427460"); + DirectoryNode dirB = (DirectoryNode) objPool.getEntry("_1269427461"); + + wbA = new HSSFWorkbook(dirA, fs, true); + exA = new ExcelExtractor(wbA); + wbB = new HSSFWorkbook(dirB, fs, true); + exB = new ExcelExtractor(wbB); + + assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText()); + assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); + assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText()); + assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); } finally { - exA.close(); + if (exB != null) exB.close(); + if (wbB != null) wbB.close(); + if (exA != null) exA.close(); + if (wbA != null) wbA.close(); + if (fs != null) fs.close(); } } /** * Excel embeded in excel */ - public void testWithEmbededInOwn() throws Exception { + @Test + public void testWithEmbededInOwn() throws Exception { POIDataSamples ssSamples = POIDataSamples.getSpreadSheetInstance(); - POIFSFileSystem fs = new POIFSFileSystem( - ssSamples.openResourceAsStream("excel_with_embeded.xls") - ); + POIFSFileSystem fs = null; + HSSFWorkbook wbA = null, wbB = null; + ExcelExtractor exA = null, exB = null, ex = null; - DirectoryNode dirA = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B5"); - DirectoryNode dirB = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B4"); + try { + fs = new POIFSFileSystem(ssSamples.getFile("excel_with_embeded.xls")); - HSSFWorkbook wbA = new HSSFWorkbook(dirA, fs, true); - HSSFWorkbook wbB = new HSSFWorkbook(dirB, fs, true); + DirectoryNode dirA = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B5"); + DirectoryNode dirB = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B4"); - ExcelExtractor exA = new ExcelExtractor(wbA); - try { - ExcelExtractor exB = new ExcelExtractor(wbB); - try { - assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", - exA.getText()); - assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); - - assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", - exB.getText()); - assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); + wbA = new HSSFWorkbook(dirA, fs, true); + wbB = new HSSFWorkbook(dirB, fs, true); + + exA = new ExcelExtractor(wbA); + exB = new ExcelExtractor(wbB); + assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText()); + assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); + + assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText()); + assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); - // And the base file too - ExcelExtractor ex = new ExcelExtractor(fs); - try { - assertEquals("Sheet1\nI have lots of embeded files in me\nSheet2\nSheet3\n", - ex.getText()); - assertEquals("Excel With Embeded", ex.getSummaryInformation().getTitle()); - } finally { - ex.close(); - } - } finally { - exB.close(); - } - } finally { - exA.close(); + // And the base file too + ex = new ExcelExtractor(fs); + assertEquals("Sheet1\nI have lots of embeded files in me\nSheet2\nSheet3\n", ex.getText()); + assertEquals("Excel With Embeded", ex.getSummaryInformation().getTitle()); + } finally { + if (ex != null) ex.close(); + if (exB != null) exB.close(); + if (exA != null) exA.close(); + if (wbB != null) wbB.close(); + if (wbA != null) wbA.close(); + if (fs != null) fs.close(); } } /** * Test that we get text from headers and footers */ - public void test45538() { + @Test + public void test45538() throws IOException { String[] files = { "45538_classic_Footer.xls", "45538_form_Footer.xls", "45538_classic_Header.xls", "45538_form_Header.xls" @@ -352,21 +385,26 @@ public final class TestExcelExtractor extends TestCase { String text = extractor.getText(); assertTrue("Unable to find expected word in text\n" + text, text.indexOf("testdoc") >=0); assertTrue("Unable to find expected word in text\n" + text, text.indexOf("test phrase") >= 0); + extractor.close(); } } - public void testPassword() { + @Test + public void testPassword() throws IOException { Biff8EncryptionKey.setCurrentUserPassword("password"); ExcelExtractor extractor = createExtractor("password.xls"); String text = extractor.getText(); Biff8EncryptionKey.setCurrentUserPassword(null); assertTrue(text.contains("ZIP")); + extractor.close(); } - public void testNullPointerException() { + @Test + public void testNullPointerException() throws IOException { ExcelExtractor extractor = createExtractor("ar.org.apsme.www_Form%20Inscripcion%20Curso%20NO%20Socios.xls"); assertNotNull(extractor); assertNotNull(extractor.getText()); + extractor.close(); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java index e15453da99..f472e3d1d4 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java @@ -36,9 +36,9 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; -import java.util.Date; import java.util.Iterator; import java.util.List; +import java.util.Locale; import java.util.TimeZone; import org.apache.poi.EncryptedDocumentException; @@ -69,13 +69,13 @@ import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Name; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.TempFile; import org.junit.Ignore; import org.junit.Test; @@ -2193,10 +2193,9 @@ public final class TestBugs extends BaseTestBugzillaIssues { @Test public void bug48968() throws Exception { - TimeZone tz = DateUtil.getUserTimeZone(); - try { - DateUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - + TimeZone userTimeZone = LocaleUtil.getUserTimeZone(); + LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); + try { HSSFWorkbook wb = openSample("48968.xls"); assertEquals(1, wb.getNumberOfSheets()); @@ -2241,9 +2240,9 @@ public final class TestBugs extends BaseTestBugzillaIssues { assertEquals(39.0+14.0+1, s.getRow(6).getCell(0).getNumericCellValue(), 0); assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula()); assertEquals(54.0+24.0-60, s.getRow(7).getCell(0).getNumericCellValue(), 0); - } finally { - DateUtil.setUserTimeZone(tz); - } + } finally { + LocaleUtil.setUserTimeZone(userTimeZone); + } } @@ -2474,12 +2473,13 @@ public final class TestBugs extends BaseTestBugzillaIssues { Sheet sheet = wb.getSheet("test-sheet"); int rowCount = sheet.getLastRowNum() + 1; int newRows = 5; + Calendar cal = LocaleUtil.getLocaleCalendar(); for (int r = rowCount; r < rowCount + newRows; r++) { Row row = sheet.createRow((short) r); row.createCell(0).setCellValue(1.03 * (r + 7)); - row.createCell(1).setCellValue(new Date()); - row.createCell(2).setCellValue(Calendar.getInstance()); - row.createCell(3).setCellValue(String.format("row:%d/col:%d", r, 3)); + row.createCell(1).setCellValue(cal.getTime()); + row.createCell(2).setCellValue(cal); + row.createCell(3).setCellValue(String.format(Locale.ROOT, "row:%d/col:%d", r, 3)); row.createCell(4).setCellValue(true); row.createCell(5).setCellType(Cell.CELL_TYPE_ERROR); row.createCell(6).setCellValue("added cells."); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java index 759363a29d..0028034864 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java @@ -32,12 +32,11 @@ import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.TempFile; /** * Class to test cell styling functionality - * - * @author Andrew C. Oliver */ public final class TestCellStyle extends TestCase { @@ -115,8 +114,7 @@ public final class TestCellStyle extends TestCase { cell = row.createCell(2); cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); cell.setCellStyle(cs); - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date()); + Calendar cal = LocaleUtil.getLocaleCalendar(); cell.setCellValue(cal); wb.write(out); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java index b18cfe9ce3..eb59e8a751 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java @@ -17,15 +17,14 @@ package org.apache.poi.hssf.usermodel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import java.io.File; import java.io.FileOutputStream; import java.util.Calendar; -import java.util.GregorianCalendar; import java.util.Iterator; -import junit.framework.AssertionFailedError; -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; @@ -43,15 +42,19 @@ import org.apache.poi.ss.formula.ptg.RefPtg; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.CellReference; +import org.apache.poi.util.LocaleUtil; +import org.junit.BeforeClass; +import org.junit.Test; /** * */ -public final class TestFormulaEvaluatorBugs extends TestCase { +public final class TestFormulaEvaluatorBugs { private static boolean OUTPUT_TEST_FILES = false; - private String tmpDirName; + private static String tmpDirName; - protected void setUp() { + @BeforeClass + public static void setUp() { tmpDirName = System.getProperty("java.io.tmpdir"); OUTPUT_TEST_FILES = Boolean.parseBoolean( System.getProperty("org.apache.poi.test.output_test_files", "False")); @@ -66,6 +69,7 @@ public final class TestFormulaEvaluatorBugs extends TestCase { * WARNING - tedious bug where you actually have to * open up excel */ + @Test public void test44636() throws Exception { // Open the existing file, tweak one value and // re-calculate @@ -80,15 +84,16 @@ public final class TestFormulaEvaluatorBugs extends TestCase { HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); assertEquals(4.2 * 25, row.getCell(3).getNumericCellValue(), 0.0001); - FileOutputStream out; if (OUTPUT_TEST_FILES) { // Save File existing = new File(tmpDirName, "44636-existing.xls"); - out = new FileOutputStream(existing); + FileOutputStream out = new FileOutputStream(existing); wb.write(out); out.close(); System.err.println("Existing file for bug #44636 written to " + existing.toString()); } + wb.close(); + // Now, do a new file from scratch wb = new HSSFWorkbook(); sheet = wb.createSheet(); @@ -106,21 +111,21 @@ public final class TestFormulaEvaluatorBugs extends TestCase { if (OUTPUT_TEST_FILES) { // Save File scratch = new File(tmpDirName, "44636-scratch.xls"); - out = new FileOutputStream(scratch); + FileOutputStream out = new FileOutputStream(scratch); wb.write(out); out.close(); System.err.println("New file for bug #44636 written to " + scratch.toString()); } + wb.close(); } /** * Bug 44297: 32767+32768 is evaluated to -1 * Fix: IntPtg must operate with unsigned short. Reading signed short results in incorrect formula calculation * if a formula has values in the interval [Short.MAX_VALUE, (Short.MAX_VALUE+1)*2] - * - * @author Yegor Kozlov */ - public void test44297() { + @Test + public void test44297() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44297.xls"); @@ -175,13 +180,16 @@ public final class TestFormulaEvaluatorBugs extends TestCase { cell = row.getCell(0); assertEquals("-1000000-3000000", cell.getCellFormula()); assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); + + wb.close(); } /** * Bug 44410: SUM(C:C) is valid in excel, and means a sum * of all the rows in Column C */ - public void test44410() { + @Test + public void test44410() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SingleLetterRanges.xls"); HSSFSheet sheet = wb.getSheetAt(0); @@ -233,12 +241,15 @@ public final class TestFormulaEvaluatorBugs extends TestCase { HSSFCell cellSUM2D = rowSUM2D.getCell(0); assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); + + wb.close(); } /** * Tests that we can evaluate boolean cells properly */ - public void testEvaluateBooleanInCell_bug44508() { + @Test + public void testEvaluateBooleanInCell_bug44508() throws Exception { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); wb.setSheetName(0, "Sheet1"); @@ -254,9 +265,12 @@ public final class TestFormulaEvaluatorBugs extends TestCase { fail("Identified bug 44508"); } assertEquals(true, cell.getBooleanCellValue()); + + wb.close(); } - public void testClassCast_bug44861() { + @Test + public void testClassCast_bug44861() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44861.xls"); // Check direct @@ -276,9 +290,12 @@ public final class TestFormulaEvaluatorBugs extends TestCase { } } } + + wb.close(); } - public void testEvaluateInCellWithErrorCode_bug44950() { + @Test + public void testEvaluateInCellWithErrorCode_bug44950() throws Exception { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Sheet1"); HSSFRow row = sheet.createRow(1); @@ -289,13 +306,16 @@ public final class TestFormulaEvaluatorBugs extends TestCase { fe.evaluateInCell(cell); } catch (NumberFormatException e) { if (e.getMessage().equals("You cannot get an error value from a non-error cell")) { - throw new AssertionFailedError("Identified bug 44950 b"); + fail("Identified bug 44950 b"); } throw e; + } finally { + wb.close(); } } - public void testDateWithNegativeParts_bug48528() { + @Test + public void testDateWithNegativeParts_bug48528() throws Exception { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Sheet1"); HSSFRow row = sheet.createRow(1); @@ -310,31 +330,33 @@ public final class TestFormulaEvaluatorBugs extends TestCase { cell.setCellFormula("DATE(2012,2,1)"); fe.notifyUpdateCell(cell); - assertEquals(40940.0, fe.evaluate(cell).getNumberValue()); + assertEquals(40940.0, fe.evaluate(cell).getNumberValue(), 0); cell.setCellFormula("DATE(2012,2,1+4)"); fe.notifyUpdateCell(cell); - assertEquals(40944.0, fe.evaluate(cell).getNumberValue()); + assertEquals(40944.0, fe.evaluate(cell).getNumberValue(), 0); cell.setCellFormula("DATE(2012,2-1,1+4)"); fe.notifyUpdateCell(cell); - assertEquals(40913.0, fe.evaluate(cell).getNumberValue()); + assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0); cell.setCellFormula("DATE(2012,2,1-27)"); fe.notifyUpdateCell(cell); - assertEquals(40913.0, fe.evaluate(cell).getNumberValue()); + assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0); cell.setCellFormula("DATE(2012,2-2,1+4)"); fe.notifyUpdateCell(cell); - assertEquals(40882.0, fe.evaluate(cell).getNumberValue()); + assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0); cell.setCellFormula("DATE(2012,2,1-58)"); fe.notifyUpdateCell(cell); - assertEquals(40882.0, fe.evaluate(cell).getNumberValue()); + assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0); cell.setCellFormula("DATE(2012,2-12,1+4)"); fe.notifyUpdateCell(cell); - assertEquals(40579.0, fe.evaluate(cell).getNumberValue()); + assertEquals(40579.0, fe.evaluate(cell).getNumberValue(), 0); + + wb.close(); } private static final class EvalListener extends EvaluationListener { @@ -363,7 +385,8 @@ public final class TestFormulaEvaluatorBugs extends TestCase { /** * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values */ - public void testSlowEvaluate45376() { + @Test + public void testSlowEvaluate45376() throws Exception { /* * Note - to observe behaviour without caching, disable the call to * updateValue() from FormulaCellCacheEntry.updateFormulaResult(). @@ -384,7 +407,7 @@ public final class TestFormulaEvaluatorBugs extends TestCase { "DATE(YEAR(" + prevCell + "),MONTH(" + prevCell + ")+1,1),NA())"; cell.setCellFormula(formula); } - Calendar cal = new GregorianCalendar(2000, 0, 1, 0, 0, 0); + Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0); row.createCell(0).setCellValue(cal); // Choose cell A9 instead of A10, so that the failing test case doesn't take too long to execute. @@ -397,8 +420,8 @@ public final class TestFormulaEvaluatorBugs extends TestCase { // Without caching, evaluating cell 'A9' takes 21845 evaluations which consumes // much time (~3 sec on Core 2 Duo 2.2GHz) // short-circuit-if optimisation cuts this down to 255 evaluations which is still too high - System.err.println("Cell A9 took " + evalCount + " intermediate evaluations"); - throw new AssertionFailedError("Identifed bug 45376 - Formula evaluator should cache values"); + // System.err.println("Cell A9 took " + evalCount + " intermediate evaluations"); + fail("Identifed bug 45376 - Formula evaluator should cache values"); } // With caching, the evaluationCount is 8 which is exactly the // number of formula cells that needed to be evaluated. @@ -413,9 +436,12 @@ public final class TestFormulaEvaluatorBugs extends TestCase { // confirm the evaluation result too assertEquals(ErrorEval.NA, ve); + + wb.close(); } @SuppressWarnings("resource") + @Test public void test55747_55324() throws Exception { HSSFWorkbook wb = new HSSFWorkbook(); HSSFFormulaEvaluator ev = wb.getCreationHelper().createFormulaEvaluator(); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java index 015edf41d8..a512f52f16 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java @@ -17,12 +17,15 @@ package org.apache.poi.hssf.usermodel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + import java.io.IOException; import java.util.Calendar; import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.TimeZone; import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFTestDataSamples; @@ -38,15 +41,14 @@ import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; import junit.framework.AssertionFailedError; /** * Tests various functionality having to do with {@link HSSFCell}. For instance support for * particular datatypes, etc. - * @author Andrew C. Oliver (andy at superlinksoftware dot com) - * @author Dan Sherman (dsherman at isisph.com) - * @author Alex Jacoby (ajacoby at gmail.com) */ public final class TestHSSFCell extends BaseTestCell { @@ -59,27 +61,28 @@ public final class TestHSSFCell extends BaseTestCell { * is working properly. Conversion of the date is also an issue, * but there's a separate unit test for that. */ - public void testDateWindowingRead() { - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT); - cal.set(2000, 0, 1, 0, 0, 0); // Jan. 1, 2000 - cal.clear(Calendar.MILLISECOND); + @Test + public void testDateWindowingRead() throws Exception { + Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0);// Jan. 1, 2000 Date date = cal.getTime(); // first check a file with 1900 Date Windowing - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls"); + HSSFSheet sheet = wb.getSheetAt(0); assertEquals("Date from file using 1900 Date Windowing", date.getTime(), sheet.getRow(0).getCell(0).getDateCellValue().getTime()); + wb.close(); // now check a file with 1904 Date Windowing - workbook = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls"); - sheet = workbook.getSheetAt(0); + wb = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls"); + sheet = wb.getSheetAt(0); assertEquals("Date from file using 1904 Date Windowing", date.getTime(), sheet.getRow(0).getCell(0).getDateCellValue().getTime()); + wb.close(); } @@ -90,28 +93,32 @@ public final class TestHSSFCell extends BaseTestCell { * previous test ({@link #testDateWindowingRead}) fails, the * results of this test are meaningless. */ - public void testDateWindowingWrite() { - GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 + @Test + public void testDateWindowingWrite() throws Exception { + Calendar cal = LocaleUtil.getLocaleCalendar(2000,0,1,0,0,0); // Jan. 1, 2000 Date date = cal.getTime(); // first check a file with 1900 Date Windowing - HSSFWorkbook wb; - wb = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls"); + HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls"); - setCell(wb, 0, 1, date); - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); + setCell(wb1, 0, 1, date); + HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); assertEquals("Date from file using 1900 Date Windowing", date.getTime(), - readCell(wb, 0, 1).getTime()); + readCell(wb2, 0, 1).getTime()); + wb1.close(); + wb2.close(); // now check a file with 1904 Date Windowing - wb = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls"); - setCell(wb, 0, 1, date); - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); + wb1 = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls"); + setCell(wb1, 0, 1, date); + wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); assertEquals("Date from file using 1900 Date Windowing", date.getTime(), - readCell(wb, 0, 1).getTime()); + readCell(wb2, 0, 1).getTime()); + wb1.close(); + wb2.close(); } private static void setCell(HSSFWorkbook workbook, int rowIdx, int colIdx, Date date) { @@ -135,12 +142,13 @@ public final class TestHSSFCell extends BaseTestCell { /** * Tests that the active cell can be correctly read and set */ - public void testActiveCell() { + @Test + public void testActiveCell() throws Exception { //read in sample - HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); + HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); //check initial position - HSSFSheet umSheet = book.getSheetAt(0); + HSSFSheet umSheet = wb1.getSheetAt(0); InternalSheet s = umSheet.getSheet(); assertEquals("Initial active cell should be in col 0", (short) 0, s.getActiveCellCol()); @@ -156,18 +164,22 @@ public final class TestHSSFCell extends BaseTestCell { 3, s.getActiveCellRow()); //write book to temp file; read and verify that position is serialized - book = HSSFTestDataSamples.writeOutAndReadBack(book); + HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); + wb1.close(); - umSheet = book.getSheetAt(0); + umSheet = wb2.getSheetAt(0); s = umSheet.getSheet(); assertEquals("After serialize, active cell should be in col 2", (short) 2, s.getActiveCellCol()); assertEquals("After serialize, active cell should be on row 3", 3, s.getActiveCellRow()); + + wb2.close(); } + @Test public void testActiveCellBug56114() throws IOException { Workbook wb = new HSSFWorkbook(); Sheet sh = wb.createSheet(); @@ -222,7 +234,8 @@ public final class TestHSSFCell extends BaseTestCell { /** * Test reading hyperlinks */ - public void testWithHyperlink() { + @Test + public void testWithHyperlink() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithHyperlink.xls"); @@ -235,12 +248,15 @@ public final class TestHSSFCell extends BaseTestCell { assertEquals("http://poi.apache.org/", link.getAddress()); assertEquals(4, link.getFirstRow()); assertEquals(0, link.getFirstColumn()); + + wb.close(); } /** * Test reading hyperlinks */ - public void testWithTwoHyperlinks() { + @Test + public void testWithTwoHyperlinks() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithTwoHyperLinks.xls"); @@ -261,13 +277,16 @@ public final class TestHSSFCell extends BaseTestCell { assertEquals("http://poi.apache.org/hssf/", link2.getAddress()); assertEquals(8, link2.getFirstRow()); assertEquals(1, link2.getFirstColumn()); + + wb.close(); } /** * Test to ensure we can only assign cell styles that belong * to our workbook, and not those from other workbooks. */ - public void testCellStyleWorkbookMatch() { + @Test + public void testCellStyleWorkbookMatch() throws Exception { HSSFWorkbook wbA = new HSSFWorkbook(); HSSFWorkbook wbB = new HSSFWorkbook(); @@ -306,6 +325,9 @@ public final class TestHSSFCell extends BaseTestCell { } catch (IllegalArgumentException e) { // expected during successful test } + + wbB.close(); + wbA.close(); } /** @@ -315,6 +337,7 @@ public final class TestHSSFCell extends BaseTestCell { * versions (prior to bug 46213 / r717883) crash instead. * @throws IOException */ + @Test public void testCachedTypeChange() throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Sheet1"); @@ -362,22 +385,27 @@ public final class TestHSSFCell extends BaseTestCell { /** * HSSF prior to version 3.7 had a bug: it could write a NaN but could not read such a file back. */ - public void testReadNaN() { + @Test + public void testReadNaN() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49761.xls"); assertNotNull(wb); + wb.close(); } - public void testHSSFCell() { + @Test + public void testHSSFCell() throws Exception { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); HSSFRow row = sheet.createRow(0); row.createCell(0); HSSFCell cell = new HSSFCell(wb, sheet, 0, (short)0); - assertNotNull(cell); + assertNotNull(cell); + wb.close(); } @SuppressWarnings("deprecation") - public void testDeprecatedMethods() { + @Test + public void testDeprecatedMethods() throws Exception { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); HSSFRow row = sheet.createRow(0); @@ -402,8 +430,11 @@ public final class TestHSSFCell extends BaseTestCell { cell.removeCellComment(); cell.removeCellComment(); + + wb.close(); } + @Test public void testCellType() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java index f1aad88c1f..4abffc5ce3 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java @@ -17,18 +17,25 @@ package org.apache.poi.hssf.usermodel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.Format; import java.text.SimpleDateFormat; -import java.util.GregorianCalendar; +import java.util.Calendar; import java.util.Iterator; +import java.util.Locale; +import java.util.TimeZone; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; - -import junit.framework.TestCase; +import org.apache.poi.util.LocaleUtil; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; /** * Unit tests for HSSFDataFormatter.java @@ -36,9 +43,25 @@ import junit.framework.TestCase; * @author James May (james dot may at fmr dot com) * */ -public final class TestHSSFDataFormatter extends TestCase { - - private final HSSFDataFormatter formatter; +public final class TestHSSFDataFormatter { + + private static TimeZone userTimeZone; + + @BeforeClass + public static void setTimeZone() { + userTimeZone = LocaleUtil.getUserTimeZone(); + LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); + LocaleUtil.setUserLocale(Locale.US); + } + + @AfterClass + public static void resetTimeZone() { + LocaleUtil.setUserTimeZone(userTimeZone); + LocaleUtil.setUserLocale(Locale.ROOT); + } + + + private final HSSFDataFormatter formatter; private final HSSFWorkbook wb; public TestHSSFDataFormatter() { @@ -197,6 +220,7 @@ public final class TestHSSFDataFormatter extends TestCase { /** * Test getting formatted values from numeric and date cells. */ + @Test public void testGetFormattedCellValueHSSFCell() { // Valid date formats -- cell values should be date formatted & not "555.555" HSSFRow row = wb.getSheetAt(0).getRow(0); @@ -216,7 +240,9 @@ public final class TestHSSFDataFormatter extends TestCase { //assert the correct month form, as in the original Excel format String monthPtrn = fmt.indexOf("mmmm") != -1 ? "MMMM" : "MMM"; // this line is intended to compute how "July" would look like in the current locale - String jul = new SimpleDateFormat(monthPtrn).format(new GregorianCalendar(2010,6,15).getTime()); + SimpleDateFormat sdf = new SimpleDateFormat(monthPtrn, LocaleUtil.getUserLocale()); + Calendar calDef = LocaleUtil.getLocaleCalendar(2010, 6, 15, 0, 0, 0); + String jul = sdf.format(calDef.getTime()); // special case for MMMMM = 1st letter of month name if(fmt.indexOf("mmmmm") > -1) { jul = jul.substring(0,1); @@ -228,7 +254,6 @@ public final class TestHSSFDataFormatter extends TestCase { row = wb.getSheetAt(0).getRow(1); it = row.cellIterator(); log("==== VALID TIME FORMATS ===="); - while (it.hasNext()) { Cell cell = it.next(); String fmt = cell.getCellStyle().getDataFormatString(); @@ -265,7 +290,7 @@ public final class TestHSSFDataFormatter extends TestCase { log(formatter.formatCellValue(cell)); // should be equal to "1234567890.12345" // in some locales the the decimal delimiter is a comma, not a dot - char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator(); + char decimalSeparator = new DecimalFormatSymbols(LocaleUtil.getUserLocale()).getDecimalSeparator(); assertEquals("1234567890" + decimalSeparator + "12345", formatter.formatCellValue(cell)); } @@ -297,6 +322,7 @@ public final class TestHSSFDataFormatter extends TestCase { assertEquals(formatter.formatCellValue(null), ""); } + @Test public void testGetFormattedCellValueHSSFCellHSSFFormulaEvaluator() { // test formula format HSSFRow row = wb.getSheetAt(0).getRow(7); @@ -310,7 +336,7 @@ public final class TestHSSFDataFormatter extends TestCase { // now with a formula evaluator HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); log(formatter.formatCellValue(cell, evaluator) + "\t\t\t (with evaluator)"); - char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator(); + char decimalSeparator = new DecimalFormatSymbols(LocaleUtil.getUserLocale()).getDecimalSeparator(); assertEquals("24" + decimalSeparator + "50%", formatter.formatCellValue(cell,evaluator)); } @@ -319,10 +345,12 @@ public final class TestHSSFDataFormatter extends TestCase { * Test using a default number format. The format should be used when a * format pattern cannot be parsed by DecimalFormat. */ + @Test public void testSetDefaultNumberFormat() { HSSFRow row = wb.getSheetAt(0).getRow(3); Iterator<Cell> it = row.cellIterator(); - Format defaultFormat = new DecimalFormat("Balance $#,#00.00 USD;Balance -$#,#00.00 USD"); + DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()); + Format defaultFormat = new DecimalFormat("Balance $#,#00.00 USD;Balance -$#,#00.00 USD", dfs); formatter.setDefaultNumberFormat(defaultFormat); log("\n==== DEFAULT NUMBER FORMAT ===="); @@ -338,6 +366,7 @@ public final class TestHSSFDataFormatter extends TestCase { /** * A format of "@" means use the general format */ + @Test public void testGeneralAtFormat() { HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("47154.xls"); HSSFSheet sheet = workbook.getSheetAt(0); @@ -356,6 +385,7 @@ public final class TestHSSFDataFormatter extends TestCase { /** * Tests various formattings of dates and numbers */ + @Test public void testFromFile() { HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("Formatting.xls"); HSSFSheet sheet = workbook.getSheetAt(0); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java index 7abd515743..224c2bd7dc 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java @@ -17,41 +17,38 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.*; +import static java.util.Calendar.AUGUST; +import static java.util.Calendar.FEBRUARY; +import static java.util.Calendar.JANUARY; +import static java.util.Calendar.JULY; +import static java.util.Calendar.MARCH; +import static java.util.Calendar.MAY; +import static java.util.Calendar.OCTOBER; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; -import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.InternalWorkbook; import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.util.LocaleUtil; import org.junit.Test; /** * Class TestHSSFDateUtil - * - * - * @author Dan Sherman (dsherman at isisph.com) - * @author Hack Kampbjorn (hak at 2mba.dk) - * @author Pavel Krupets (pkrupets at palmtreebusiness dot com) - * @author Alex Jacoby (ajacoby at gmail.com) - * @version %I%, %G% */ public final class TestHSSFDateUtil { - 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; - /** * Checks the date conversion functions in the HSSFDateUtil class. */ @@ -59,25 +56,24 @@ public final class TestHSSFDateUtil { public void dateConversion() { // Iteratating over the hours exposes any rounding issues. - for (int hour = 0; hour < 23; hour++) - { - GregorianCalendar date = new GregorianCalendar(2002, 0, 1, - hour, 1, 1); - double excelDate = - HSSFDateUtil.getExcelDate(date.getTime(), false); - - assertEquals("Checking hour = " + hour, date.getTime().getTime(), + Calendar cal = LocaleUtil.getLocaleCalendar(2002,JANUARY,1,0,1,1); + for (int hour = 0; hour < 23; hour++) { + double excelDate = HSSFDateUtil.getExcelDate(cal.getTime(), false); + + assertEquals("Checking hour = " + hour, cal.getTime().getTime(), HSSFDateUtil.getJavaDate(excelDate, false).getTime()); + + cal.add(Calendar.HOUR_OF_DAY, 1); } // check 1900 and 1904 date windowing conversions double excelDate = 36526.0; // with 1900 windowing, excelDate is Jan. 1, 2000 // with 1904 windowing, excelDate is Jan. 2, 2004 - GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 + cal.set(2000,JANUARY,1,0,0,0); // Jan. 1, 2000 Date dateIf1900 = cal.getTime(); - cal.add(GregorianCalendar.YEAR,4); // now Jan. 1, 2004 - cal.add(GregorianCalendar.DATE,1); // now Jan. 2, 2004 + cal.add(Calendar.YEAR,4); // now Jan. 1, 2004 + cal.add(Calendar.DATE,1); // now Jan. 2, 2004 Date dateIf1904 = cal.getTime(); // 1900 windowing assertEquals("Checking 1900 Date Windowing", @@ -95,11 +91,9 @@ public final class TestHSSFDateUtil { */ @Test public void excelConversionOnDSTStart() { - TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); - TimeZone.setDefault(cet); - Calendar cal = new GregorianCalendar(2004, CALENDAR_MARCH, 28); + Calendar cal = LocaleUtil.getLocaleCalendar(2004,MARCH,28,0,0,0); for (int hour = 0; hour < 24; hour++) { - + // Skip 02:00 CET as that is the Daylight change time // and Java converts it automatically to 03:00 CEST if (hour == 2) { @@ -108,6 +102,8 @@ public final class TestHSSFDateUtil { cal.set(Calendar.HOUR_OF_DAY, hour); Date javaDate = cal.getTime(); + + double excelDate = HSSFDateUtil.getExcelDate(javaDate, false); double difference = excelDate - Math.floor(excelDate); int differenceInHours = (int) (difference * 24 * 60 + 0.5) / 60; @@ -126,9 +122,7 @@ public final class TestHSSFDateUtil { */ @Test public void javaConversionOnDSTStart() { - TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); - TimeZone.setDefault(cet); - Calendar cal = new GregorianCalendar(2004, CALENDAR_MARCH, 28); + Calendar cal = LocaleUtil.getLocaleCalendar(2004,MARCH,28,0,0,0); double excelDate = HSSFDateUtil.getExcelDate(cal.getTime(), false); double oneHour = 1.0 / 24; double oneMinute = oneHour / 60; @@ -154,9 +148,7 @@ public final class TestHSSFDateUtil { */ @Test public void excelConversionOnDSTEnd() { - TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); - TimeZone.setDefault(cet); - Calendar cal = new GregorianCalendar(2004, CALENDAR_OCTOBER, 31); + Calendar cal = LocaleUtil.getLocaleCalendar(2004,OCTOBER,31,0,0,0); for (int hour = 0; hour < 24; hour++) { cal.set(Calendar.HOUR_OF_DAY, hour); Date javaDate = cal.getTime(); @@ -178,9 +170,7 @@ public final class TestHSSFDateUtil { */ @Test public void javaConversionOnDSTEnd() { - TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); - TimeZone.setDefault(cet); - Calendar cal = new GregorianCalendar(2004, CALENDAR_OCTOBER, 31); + Calendar cal = LocaleUtil.getLocaleCalendar(2004,OCTOBER,31,0,0,0); double excelDate = HSSFDateUtil.getExcelDate(cal.getTime(), false); double oneHour = 1.0 / 24; double oneMinute = oneHour / 60; @@ -198,40 +188,45 @@ public final class TestHSSFDateUtil { */ @Test public void calendarConversion() { - GregorianCalendar date = new GregorianCalendar(2002, 0, 1, 12, 1, 1); - Date expected = date.getTime(); - - // Iterating over the hours exposes any rounding issues. - for (int hour = -12; hour <= 12; hour++) - { - String id = "GMT" + (hour < 0 ? "" : "+") + hour + ":00"; - date.setTimeZone(TimeZone.getTimeZone(id)); - date.set(Calendar.HOUR_OF_DAY, 12); - double excelDate = HSSFDateUtil.getExcelDate(date, false); - Date javaDate = HSSFDateUtil.getJavaDate(excelDate); - - // Should match despite time-zone - assertEquals("Checking timezone " + id, expected.getTime(), javaDate.getTime()); + TimeZone userTZ = LocaleUtil.getUserTimeZone(); + LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); + try { + Calendar cal = LocaleUtil.getLocaleCalendar(2002,JANUARY,1,12,1,1); + Date expected = cal.getTime(); + + // Iterating over the hours exposes any rounding issues. + for (int hour = -12; hour <= 12; hour++) + { + String id = "GMT" + (hour < 0 ? "" : "+") + hour + ":00"; + cal.setTimeZone(TimeZone.getTimeZone(id)); + cal.set(Calendar.HOUR_OF_DAY, 12); + double excelDate = HSSFDateUtil.getExcelDate(cal, false); + Date javaDate = HSSFDateUtil.getJavaDate(excelDate); + + // Should match despite time-zone + assertEquals("Checking timezone " + id, expected.getTime(), javaDate.getTime()); + } + + // Check that the timezone aware getter works correctly + TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); + TimeZone ldn = TimeZone.getTimeZone("Europe/London"); + + // 12:45 on 27th April 2012 + double excelDate = 41026.53125; + + // Same, no change + assertEquals( + HSSFDateUtil.getJavaDate(excelDate, false).getTime(), + HSSFDateUtil.getJavaDate(excelDate, false, cet).getTime() + ); + + // London vs Copenhagen, should differ by an hour + Date cetDate = HSSFDateUtil.getJavaDate(excelDate, false); + Date ldnDate = HSSFDateUtil.getJavaDate(excelDate, false, ldn); + assertEquals(ldnDate.getTime() - cetDate.getTime(), 60*60*1000); + } finally { + LocaleUtil.setUserTimeZone(userTZ); } - - // Check that the timezone aware getter works correctly - TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); - TimeZone ldn = TimeZone.getTimeZone("Europe/London"); - TimeZone.setDefault(cet); - - // 12:45 on 27th April 2012 - double excelDate = 41026.53125; - - // Same, no change - assertEquals( - HSSFDateUtil.getJavaDate(excelDate, false).getTime(), - HSSFDateUtil.getJavaDate(excelDate, false, cet).getTime() - ); - - // London vs Copenhagen, should differ by an hour - Date cetDate = HSSFDateUtil.getJavaDate(excelDate, false); - Date ldnDate = HSSFDateUtil.getJavaDate(excelDate, false, ldn); - assertEquals(ldnDate.getTime() - cetDate.getTime(), 60*60*1000); } /** @@ -405,7 +400,8 @@ public final class TestHSSFDateUtil { @Test public void excelDateBorderCases() throws ParseException { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT); + df.setTimeZone(LocaleUtil.getUserTimeZone()); assertEquals(1.0, DateUtil.getExcelDate(df.parse("1900-01-01")), 0.00001); assertEquals(31.0, DateUtil.getExcelDate(df.parse("1900-01-31")), 0.00001); @@ -415,38 +411,38 @@ public final class TestHSSFDateUtil { @Test public void dateBug_2Excel() { - assertEquals(59.0, HSSFDateUtil.getExcelDate(createDate(1900, CALENDAR_FEBRUARY, 28), false), 0.00001); - assertEquals(61.0, HSSFDateUtil.getExcelDate(createDate(1900, CALENDAR_MARCH, 1), false), 0.00001); + assertEquals(59.0, HSSFDateUtil.getExcelDate(createDate(1900, FEBRUARY, 28), false), 0.00001); + assertEquals(61.0, HSSFDateUtil.getExcelDate(createDate(1900, MARCH, 1), false), 0.00001); - assertEquals(37315.00, HSSFDateUtil.getExcelDate(createDate(2002, CALENDAR_FEBRUARY, 28), false), 0.00001); - assertEquals(37316.00, HSSFDateUtil.getExcelDate(createDate(2002, CALENDAR_MARCH, 1), false), 0.00001); - assertEquals(37257.00, HSSFDateUtil.getExcelDate(createDate(2002, CALENDAR_JANUARY, 1), false), 0.00001); - assertEquals(38074.00, HSSFDateUtil.getExcelDate(createDate(2004, CALENDAR_MARCH, 28), false), 0.00001); + assertEquals(37315.00, HSSFDateUtil.getExcelDate(createDate(2002, FEBRUARY, 28), false), 0.00001); + assertEquals(37316.00, HSSFDateUtil.getExcelDate(createDate(2002, MARCH, 1), false), 0.00001); + assertEquals(37257.00, HSSFDateUtil.getExcelDate(createDate(2002, JANUARY, 1), false), 0.00001); + assertEquals(38074.00, HSSFDateUtil.getExcelDate(createDate(2004, MARCH, 28), false), 0.00001); } @Test public void dateBug_2Java() { - assertEquals(createDate(1900, CALENDAR_FEBRUARY, 28), HSSFDateUtil.getJavaDate(59.0, false)); - assertEquals(createDate(1900, CALENDAR_MARCH, 1), HSSFDateUtil.getJavaDate(61.0, false)); + assertEquals(createDate(1900, FEBRUARY, 28), HSSFDateUtil.getJavaDate(59.0, false)); + assertEquals(createDate(1900, MARCH, 1), HSSFDateUtil.getJavaDate(61.0, false)); - assertEquals(createDate(2002, CALENDAR_FEBRUARY, 28), HSSFDateUtil.getJavaDate(37315.00, false)); - assertEquals(createDate(2002, CALENDAR_MARCH, 1), HSSFDateUtil.getJavaDate(37316.00, false)); - assertEquals(createDate(2002, CALENDAR_JANUARY, 1), HSSFDateUtil.getJavaDate(37257.00, false)); - assertEquals(createDate(2004, CALENDAR_MARCH, 28), HSSFDateUtil.getJavaDate(38074.00, false)); + assertEquals(createDate(2002, FEBRUARY, 28), HSSFDateUtil.getJavaDate(37315.00, false)); + assertEquals(createDate(2002, MARCH, 1), HSSFDateUtil.getJavaDate(37316.00, false)); + assertEquals(createDate(2002, JANUARY, 1), HSSFDateUtil.getJavaDate(37257.00, false)); + assertEquals(createDate(2004, MARCH, 28), HSSFDateUtil.getJavaDate(38074.00, false)); } @Test public void date1904() { - assertEquals(createDate(1904, CALENDAR_JANUARY, 2), HSSFDateUtil.getJavaDate(1.0, true)); - assertEquals(createDate(1904, CALENDAR_JANUARY, 1), HSSFDateUtil.getJavaDate(0.0, true)); - assertEquals(0.0, HSSFDateUtil.getExcelDate(createDate(1904, CALENDAR_JANUARY, 1), true), 0.00001); - assertEquals(1.0, HSSFDateUtil.getExcelDate(createDate(1904, CALENDAR_JANUARY, 2), true), 0.00001); + assertEquals(createDate(1904, JANUARY, 2), HSSFDateUtil.getJavaDate(1.0, true)); + assertEquals(createDate(1904, JANUARY, 1), HSSFDateUtil.getJavaDate(0.0, true)); + assertEquals(0.0, HSSFDateUtil.getExcelDate(createDate(1904, JANUARY, 1), true), 0.00001); + assertEquals(1.0, HSSFDateUtil.getExcelDate(createDate(1904, JANUARY, 2), true), 0.00001); - assertEquals(createDate(1998, CALENDAR_JULY, 5), HSSFDateUtil.getJavaDate(35981, false)); - assertEquals(createDate(1998, CALENDAR_JULY, 5), HSSFDateUtil.getJavaDate(34519, true)); + assertEquals(createDate(1998, JULY, 5), HSSFDateUtil.getJavaDate(35981, false)); + assertEquals(createDate(1998, JULY, 5), HSSFDateUtil.getJavaDate(34519, true)); - assertEquals(35981.0, HSSFDateUtil.getExcelDate(createDate(1998, CALENDAR_JULY, 5), false), 0.00001); - assertEquals(34519.0, HSSFDateUtil.getExcelDate(createDate(1998, CALENDAR_JULY, 5), true), 0.00001); + assertEquals(35981.0, HSSFDateUtil.getExcelDate(createDate(1998, JULY, 5), false), 0.00001); + assertEquals(34519.0, HSSFDateUtil.getExcelDate(createDate(1998, JULY, 5), true), 0.00001); } /** @@ -462,9 +458,7 @@ public final class TestHSSFDateUtil { * @param day one based */ private static Date createDate(int year, int month, int day, int hour, int minute, int second) { - Calendar c = new GregorianCalendar(Locale.ROOT); - c.set(year, month, day, hour, minute, second); - c.set(Calendar.MILLISECOND, 0); + Calendar c = LocaleUtil.getLocaleCalendar(year, month, day, hour, minute, second); return c.getTime(); } @@ -474,26 +468,26 @@ public final class TestHSSFDateUtil { @Test public void absoluteDay() { // 1 Jan 1900 is 1 day after 31 Dec 1899 - GregorianCalendar calendar = new GregorianCalendar(1900, 0, 1); - assertEquals("Checking absolute day (1 Jan 1900)", 1, HSSFDateUtil.absoluteDay(calendar, false)); + Calendar cal = LocaleUtil.getLocaleCalendar(1900,JANUARY,1,0,0,0); + assertEquals("Checking absolute day (1 Jan 1900)", 1, HSSFDateUtil.absoluteDay(cal, false)); // 1 Jan 1901 is 366 days after 31 Dec 1899 - calendar = new GregorianCalendar(1901, 0, 1); - assertEquals("Checking absolute day (1 Jan 1901)", 366, HSSFDateUtil.absoluteDay(calendar, false)); + cal.set(1901,JANUARY,1,0,0,0); + assertEquals("Checking absolute day (1 Jan 1901)", 366, HSSFDateUtil.absoluteDay(cal, false)); } @Test public void absoluteDayYearTooLow() { - GregorianCalendar calendar = new GregorianCalendar(1899, 0, 1); + Calendar cal = LocaleUtil.getLocaleCalendar(1899,JANUARY,1,0,0,0); try { - HSSFDateUtil.absoluteDay(calendar, false); + HSSFDateUtil.absoluteDay(cal, false); fail("Should fail here"); } catch (IllegalArgumentException e) { // expected here } try { - calendar = new GregorianCalendar(1903, 0, 1); - HSSFDateUtil.absoluteDay(calendar, true); + cal.set(1903,JANUARY,1,0,0,0); + HSSFDateUtil.absoluteDay(cal, true); fail("Should fail here"); } catch (IllegalArgumentException e) { // expected here @@ -512,8 +506,8 @@ public final class TestHSSFDateUtil { @Test public void parseDate() { - assertEquals(createDate(2008, Calendar.AUGUST, 3), HSSFDateUtil.parseYYYYMMDDDate("2008/08/03")); - assertEquals(createDate(1994, Calendar.MAY, 1), HSSFDateUtil.parseYYYYMMDDDate("1994/05/01")); + assertEquals(createDate(2008, AUGUST, 3), HSSFDateUtil.parseYYYYMMDDDate("2008/08/03")); + assertEquals(createDate(1994, MAY, 1), HSSFDateUtil.parseYYYYMMDDDate("1994/05/01")); } /** @@ -540,10 +534,8 @@ public final class TestHSSFDateUtil { HSSFSheet sheet = workbook.createSheet(); HSSFCell cell = sheet.createRow(0).createCell(0); - Calendar cal = Calendar.getInstance(); - // A pseudo special Excel dates - cal.set(1900, 0, 1); + Calendar cal = LocaleUtil.getLocaleCalendar(1900, JANUARY, 1); Date valueToTest = cal.getTime(); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java index 1b7cf18d4b..57be4a6d6d 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java @@ -17,42 +17,50 @@ package org.apache.poi.hssf.usermodel; -import java.util.GregorianCalendar; -import java.util.List; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import junit.framework.TestCase; +import java.util.Calendar; +import java.util.Date; +import java.util.List; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.InternalSheet; import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.EOFRecord; +import org.apache.poi.hssf.record.RecordBase; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; /** * @author Glen Stampoultzis (glens at apache.org) */ -public final class TestReadWriteChart extends TestCase { +public final class TestReadWriteChart { /** * In the presence of a chart we need to make sure BOF/EOF records still exist. */ - public void testBOFandEOFRecords() { + @Test + public void testBOFandEOFRecords() throws Exception { HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls"); HSSFSheet sheet = workbook.getSheetAt(0); HSSFRow firstRow = sheet.getRow(0); HSSFCell firstCell = firstRow.getCell(0); //System.out.println("first assertion for date"); - assertEquals(new GregorianCalendar(2000, 0, 1, 10, 51, 2).getTime(), - HSSFDateUtil - .getJavaDate(firstCell.getNumericCellValue(), false)); + Calendar calExp = LocaleUtil.getLocaleCalendar(2000, 0, 1, 10, 51, 2); + Date dateAct = HSSFDateUtil.getJavaDate(firstCell.getNumericCellValue(), false); + assertEquals(calExp.getTime(), dateAct); HSSFRow row = sheet.createRow(15); HSSFCell cell = row.createCell(1); cell.setCellValue(22); InternalSheet newSheet = workbook.getSheetAt(0).getSheet(); - List records = newSheet.getRecords(); + List<RecordBase> records = newSheet.getRecords(); assertTrue(records.get(0) instanceof BOFRecord); assertTrue(records.get(records.size() - 1) instanceof EOFRecord); + + workbook.close(); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java b/src/testcases/org/apache/poi/hssf/usermodel/TestText.java index 7231330ee0..42a30ec8e7 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestText.java @@ -18,21 +18,23 @@ package org.apache.poi.hssf.usermodel;
import static org.junit.Assert.assertArrayEquals;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.HSSFTestModelHelper;
import org.apache.poi.hssf.model.TextboxShape;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.TextObjectRecord;
+import org.junit.Test;
/**
* @author Evgeniy Berlog
* @date 25.06.12
*/
-public class TestText extends TestCase {
+public class TestText {
- public void testResultEqualsToAbstractShape() {
+ @Test
+ public void testResultEqualsToAbstractShape() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sh = wb.createSheet();
HSSFPatriarch patriarch = sh.createDrawingPatriarch();
@@ -81,11 +83,14 @@ public class TestText extends TestCase { assertEquals(expected.length, actual.length);
assertArrayEquals(expected, actual);
+
+ wb.close();
}
- public void testAddTextToExistingFile() {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
+ @Test
+ public void testAddTextToExistingFile() throws Exception {
+ HSSFWorkbook wb1 = new HSSFWorkbook();
+ HSSFSheet sh = wb1.createSheet();
HSSFPatriarch patriarch = sh.createDrawingPatriarch();
HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor());
textbox.setString(new HSSFRichTextString("just for test"));
@@ -94,8 +99,9 @@ public class TestText extends TestCase { assertEquals(patriarch.getChildren().size(), 2);
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wb.getSheetAt(0);
+ HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
+ wb1.close();
+ sh = wb2.getSheetAt(0);
patriarch = sh.getDrawingPatriarch();
assertEquals(patriarch.getChildren().size(), 2);
@@ -103,19 +109,23 @@ public class TestText extends TestCase { text3.setString(new HSSFRichTextString("text3"));
assertEquals(patriarch.getChildren().size(), 3);
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wb.getSheetAt(0);
+ HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
+ wb2.close();
+ sh = wb3.getSheetAt(0);
patriarch = sh.getDrawingPatriarch();
assertEquals(patriarch.getChildren().size(), 3);
assertEquals(((HSSFTextbox) patriarch.getChildren().get(0)).getString().getString(), "just for test");
assertEquals(((HSSFTextbox) patriarch.getChildren().get(1)).getString().getString(), "just for test2");
assertEquals(((HSSFTextbox) patriarch.getChildren().get(2)).getString().getString(), "text3");
+
+ wb3.close();
}
- public void testSetGetProperties() {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
+ @Test
+ public void testSetGetProperties() throws Exception {
+ HSSFWorkbook wb1 = new HSSFWorkbook();
+ HSSFSheet sh = wb1.createSheet();
HSSFPatriarch patriarch = sh.createDrawingPatriarch();
HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor());
textbox.setString(new HSSFRichTextString("test"));
@@ -139,8 +149,9 @@ public class TestText extends TestCase { textbox.setMarginTop(10);
assertEquals(textbox.getMarginTop(), 10);
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wb.getSheetAt(0);
+ HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
+ wb1.close();
+ sh = wb2.getSheetAt(0);
patriarch = sh.getDrawingPatriarch();
textbox = (HSSFTextbox) patriarch.getChildren().get(0);
assertEquals(textbox.getString().getString(), "test");
@@ -167,8 +178,9 @@ public class TestText extends TestCase { assertEquals(textbox.getMarginRight(), 91);
assertEquals(textbox.getMarginTop(), 101);
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wb.getSheetAt(0);
+ HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
+ wb2.close();
+ sh = wb3.getSheetAt(0);
patriarch = sh.getDrawingPatriarch();
textbox = (HSSFTextbox) patriarch.getChildren().get(0);
@@ -179,9 +191,12 @@ public class TestText extends TestCase { assertEquals(textbox.getMarginLeft(), 81);
assertEquals(textbox.getMarginRight(), 91);
assertEquals(textbox.getMarginTop(), 101);
+
+ wb3.close();
}
- public void testExistingFileWithText(){
+ @Test
+ public void testExistingFileWithText() throws Exception {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
HSSFSheet sheet = wb.getSheet("text");
HSSFPatriarch drawing = sheet.getDrawingPatriarch();
@@ -194,5 +209,6 @@ public class TestText extends TestCase { assertEquals(textbox.getMarginLeft(), 3600000);
assertEquals(textbox.getMarginRight(), 0);
assertEquals(textbox.getString().getString(), "teeeeesssstttt");
+ wb.close();
}
}
diff --git a/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java b/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java index 28e9cfe46b..537dafbb3e 100644 --- a/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java +++ b/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java @@ -25,10 +25,12 @@ import static java.awt.Color.ORANGE; import static java.awt.Color.RED; import static java.awt.Color.WHITE; import static java.awt.Color.YELLOW; +import static org.junit.Assert.assertEquals; import java.awt.Color; import java.io.IOException; import java.util.Arrays; +import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; @@ -36,15 +38,14 @@ import java.util.TreeSet; import javax.swing.JLabel; -import junit.framework.TestCase; - import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.POILogger; +import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.POILogFactory; +import org.apache.poi.util.POILogger; /** * This class is a base class for spreadsheet-based tests, such as are used for @@ -57,9 +58,7 @@ import org.apache.poi.util.POILogFactory; * flag "Categories" is not empty, only tests that have at least one category * listed in "Categories" are run. */ -@SuppressWarnings( - {"JUnitTestCaseWithNoTests", "JUnitTestClassNamingConvention"}) -public class CellFormatTestBase extends TestCase { +public class CellFormatTestBase { private static final POILogger logger = POILogFactory.getLogger(CellFormatTestBase.class); private final ITestDataProvider _testDataProvider; @@ -86,7 +85,6 @@ public class CellFormatTestBase extends TestCase { abstract static class CellValue { abstract Object getValue(Cell cell); - @SuppressWarnings({"UnusedDeclaration"}) Color getColor(Cell cell) { return TEST_COLOR; } @@ -114,20 +112,19 @@ public class CellFormatTestBase extends TestCase { } Sheet sheet = workbook.getSheet("Tests"); - int end = sheet.getLastRowNum(); - // Skip the header row, therefore "+ 1" - for (int r = sheet.getFirstRowNum() + 1; r <= end; r++) { - Row row = sheet.getRow(r); - if (row == null) - continue; - int cellnum = 0; - String expectedText = row.getCell(cellnum).getStringCellValue(); - String format = row.getCell(1).getStringCellValue(); + Iterator<Row> rowIter = sheet.rowIterator(); + // Skip the header row + rowIter.next(); + while (rowIter.hasNext()) { + Row row = rowIter.next(); + if (row == null) continue; + String expectedText = row.getCell(0).getStringCellValue(); + String format = row.getCell(1).getStringCellValue(); + Cell value = row.getCell(2); String testCategoryList = row.getCell(3).getStringCellValue(); boolean byCategory = runByCategory(runCategories, testCategoryList); if ((expectedText.length() > 0 || format.length() > 0) && byCategory) { - Cell cell = row.getCell(2); - tryFormat(r, expectedText, format, valueGetter, cell); + tryFormat(row.getRowNum(), expectedText, format, valueGetter, value); } } } @@ -216,16 +213,17 @@ public class CellFormatTestBase extends TestCase { label.setForeground(testColor); label.setText("xyzzy"); - logger.log(POILogger.INFO, String.format("Row %d: \"%s\" -> \"%s\": expected \"%s\"", row + 1, - String.valueOf(value), desc, expectedText)); + logger.log(POILogger.INFO, String.format(LocaleUtil.getUserLocale(), + "Row %d: \"%s\" -> \"%s\": expected \"%s\"", + row + 1, String.valueOf(value), desc, expectedText)); String actualText = tryColor(desc, null, getter, value, expectedText, testColor); - logger.log(POILogger.INFO, String.format(", actual \"%s\")%n", actualText)); + logger.log(POILogger.INFO, String.format(LocaleUtil.getUserLocale(), + ", actual \"%s\")%n", actualText)); if (tryAllColors && testColor != TEST_COLOR) { for (int i = 0; i < COLOR_NAMES.length; i++) { - String cname = COLOR_NAMES[i]; - tryColor(desc, cname, getter, value, expectedText, COLORS[i]); + tryColor(desc, COLOR_NAMES[i], getter, value, expectedText, COLORS[i]); } } } diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java b/src/testcases/org/apache/poi/ss/format/TestCellFormat.java index 9d2d7580c3..b7983a3c80 100644 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java +++ b/src/testcases/org/apache/poi/ss/format/TestCellFormat.java @@ -16,23 +16,45 @@ ==================================================================== */ package org.apache.poi.ss.format; +import static org.junit.Assert.assertEquals; + import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; import javax.swing.JLabel; -import junit.framework.TestCase; - import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.util.LocaleUtil; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; -public class TestCellFormat extends TestCase { +public class TestCellFormat { + + private static TimeZone userTimeZone; + + @BeforeClass + public static void setTimeZone() { + userTimeZone = LocaleUtil.getUserTimeZone(); + LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); + LocaleUtil.setUserLocale(Locale.US); + } + + @AfterClass + public static void resetTimeZone() { + LocaleUtil.setUserTimeZone(userTimeZone); + LocaleUtil.setUserLocale(Locale.ROOT); + } + private static final String _255_POUND_SIGNS; static { @@ -43,6 +65,7 @@ public class TestCellFormat extends TestCase { _255_POUND_SIGNS = sb.toString(); } + @Test public void testSome() { JLabel l = new JLabel(); CellFormat fmt = CellFormat.getInstance( @@ -50,48 +73,56 @@ public class TestCellFormat extends TestCase { fmt.apply(l, 1.1); } + @Test public void testPositiveFormatHasOnePart() { CellFormat fmt = CellFormat.getInstance("0.00"); CellFormatResult result = fmt.apply(12.345); assertEquals("12.35", result.text); } + @Test public void testNegativeFormatHasOnePart() { CellFormat fmt = CellFormat.getInstance("0.00"); CellFormatResult result = fmt.apply(-12.345); assertEquals("-12.35", result.text); } + @Test public void testZeroFormatHasOnePart() { CellFormat fmt = CellFormat.getInstance("0.00"); CellFormatResult result = fmt.apply(0.0); assertEquals("0.00", result.text); } + @Test public void testPositiveFormatHasPosAndNegParts() { CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); CellFormatResult result = fmt.apply(12.345); assertEquals("12.35", result.text); } + @Test public void testNegativeFormatHasPosAndNegParts() { CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); CellFormatResult result = fmt.apply(-12.345); assertEquals("-12.35", result.text); } + @Test public void testNegativeFormatHasPosAndNegParts2() { CellFormat fmt = CellFormat.getInstance("0.00;(0.00)"); CellFormatResult result = fmt.apply(-12.345); assertEquals("(12.35)", result.text); } + @Test public void testZeroFormatHasPosAndNegParts() { CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); CellFormatResult result = fmt.apply(0.0); assertEquals("0.00", result.text); } + @Test public void testFormatWithThreeSections() { CellFormat fmt = CellFormat.getInstance("0.00;-0.00;-"); @@ -101,6 +132,7 @@ public class TestCellFormat extends TestCase { assertEquals("abc", fmt.apply("abc").text); } + @Test public void testFormatWithFourSections() { CellFormat fmt = CellFormat.getInstance("0.00;-0.00;-; @ "); @@ -110,7 +142,8 @@ public class TestCellFormat extends TestCase { assertEquals(" abc ", fmt.apply("abc").text); } - public void testApplyCellForGeneralFormat() { + @Test + public void testApplyCellForGeneralFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -147,9 +180,11 @@ public class TestCellFormat extends TestCase { CellFormatResult result4 = cf.apply(cell4); assertEquals("abc", result4.text); + wb.close(); } - public void testApplyCellForAtFormat() { + @Test + public void testApplyCellForAtFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -186,9 +221,11 @@ public class TestCellFormat extends TestCase { CellFormatResult result4 = cf.apply(cell4); assertEquals("abc", result4.text); + wb.close(); } - public void testApplyCellForDateFormat() { + @Test + public void testApplyCellForDateFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -207,9 +244,11 @@ public class TestCellFormat extends TestCase { CellFormatResult result1 = cf.apply(cell1); assertEquals(_255_POUND_SIGNS, result1.text); + wb.close(); } - public void testApplyCellForTimeFormat() { + @Test + public void testApplyCellForTimeFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -223,9 +262,11 @@ public class TestCellFormat extends TestCase { CellFormatResult result = cf.apply(cell); assertEquals("03:04", result.text); + wb.close(); } - public void testApplyCellForDateFormatAndNegativeFormat() { + @Test + public void testApplyCellForDateFormatAndNegativeFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -244,9 +285,11 @@ public class TestCellFormat extends TestCase { CellFormatResult result1 = cf.apply(cell1); assertEquals("(1)", result1.text); + wb.close(); } - public void testApplyJLabelCellForGeneralFormat() { + @Test + public void testApplyJLabelCellForGeneralFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -294,9 +337,11 @@ public class TestCellFormat extends TestCase { assertEquals("abc", result4.text); assertEquals("abc", label4.getText()); + wb.close(); } - public void testApplyJLabelCellForAtFormat() { + @Test + public void testApplyJLabelCellForAtFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -344,9 +389,11 @@ public class TestCellFormat extends TestCase { assertEquals("abc", result4.text); assertEquals("abc", label4.getText()); + wb.close(); } - public void testApplyJLabelCellForDateFormat() { + @Test + public void testApplyJLabelCellForDateFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -370,9 +417,11 @@ public class TestCellFormat extends TestCase { assertEquals(_255_POUND_SIGNS, result1.text); assertEquals(_255_POUND_SIGNS, label1.getText()); + wb.close(); } - public void testApplyJLabelCellForTimeFormat() { + @Test + public void testApplyJLabelCellForTimeFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -389,9 +438,11 @@ public class TestCellFormat extends TestCase { assertEquals("03:04", result.text); assertEquals("03:04", label.getText()); + wb.close(); } - public void testApplyJLabelCellForDateFormatAndNegativeFormat() { + @Test + public void testApplyJLabelCellForDateFormatAndNegativeFormat() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -415,9 +466,11 @@ public class TestCellFormat extends TestCase { assertEquals("(1)", result1.text); assertEquals("(1)", label1.getText()); + wb.close(); } - public void testApplyFormatHasOnePartAndPartHasCondition() { + @Test + public void testApplyFormatHasOnePartAndPartHasCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -442,9 +495,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("abc", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasTwoPartsFirstHasCondition() { + @Test + public void testApplyFormatHasTwoPartsFirstHasCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -475,9 +530,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("TRUE"); assertEquals("TRUE", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasTwoPartsBothHaveCondition() { + @Test + public void testApplyFormatHasTwoPartsBothHaveCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -505,9 +562,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("abc", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasThreePartsFirstHasCondition() { + @Test + public void testApplyFormatHasThreePartsFirstHasCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -537,9 +596,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("abc", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasThreePartsFirstTwoHaveCondition() { + @Test + public void testApplyFormatHasThreePartsFirstTwoHaveCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -564,9 +625,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("abc", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasThreePartsFirstIsDateFirstTwoHaveCondition() { + @Test + public void testApplyFormatHasThreePartsFirstIsDateFirstTwoHaveCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -591,9 +654,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("abc", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasTwoPartsFirstHasConditionSecondIsGeneral() { + @Test + public void testApplyFormatHasTwoPartsFirstHasConditionSecondIsGeneral() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -618,9 +683,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("abc", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasThreePartsFirstTwoHaveConditionThirdIsGeneral() { + @Test + public void testApplyFormatHasThreePartsFirstTwoHaveConditionThirdIsGeneral() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -645,9 +712,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("abc", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasFourPartsFirstHasCondition() { + @Test + public void testApplyFormatHasFourPartsFirstHasCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -677,9 +746,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue("abc"); assertEquals("~~abc~~", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasFourPartsSecondHasCondition() { + @Test + public void testApplyFormatHasFourPartsSecondHasCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -710,9 +781,11 @@ public class TestCellFormat extends TestCase { cell.setCellValue(true); assertEquals("~~TRUE~~", cf.apply(cell).text); + wb.close(); } - public void testApplyFormatHasFourPartsFirstTwoHaveCondition() { + @Test + public void testApplyFormatHasFourPartsFirstTwoHaveCondition() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -739,11 +812,14 @@ public class TestCellFormat extends TestCase { cell.setCellValue(true); assertEquals("~~TRUE~~", cf.apply(cell).text); + + wb.close(); } /* * Test apply(Object value) with a number as parameter */ + @Test public void testApplyObjectNumber() { CellFormat cf1 = CellFormat.getInstance("0.000"); @@ -771,15 +847,17 @@ public class TestCellFormat extends TestCase { /* * Test apply(Object value) with a Date as parameter */ + @Test public void testApplyObjectDate() throws ParseException { CellFormat cf1 = CellFormat.getInstance("m/d/yyyy"); - Date date1 = new SimpleDateFormat("M/d/y").parse("01/11/2012"); + Date date1 = new SimpleDateFormat("M/d/y", Locale.ROOT).parse("01/11/2012"); assertEquals("1/11/2012", cf1.apply(date1).text); } - public void testApplyCellForDateFormatWithConditions() { + @Test + public void testApplyCellForDateFormatWithConditions() throws Exception { // Create a workbook, row and cell to test with Workbook wb = new HSSFWorkbook(); @@ -798,11 +876,13 @@ public class TestCellFormat extends TestCase { cell.setCellValue(-1); assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); + wb.close(); } /* * Test apply(Object value) with a String as parameter */ + @Test public void testApplyObjectString() { CellFormat cf = CellFormat.getInstance("0.00"); @@ -814,6 +894,7 @@ public class TestCellFormat extends TestCase { /* * Test apply(Object value) with a Boolean as parameter */ + @Test public void testApplyObjectBoolean() { CellFormat cf1 = CellFormat.getInstance("0"); @@ -826,6 +907,7 @@ public class TestCellFormat extends TestCase { } + @Test public void testSimpleFractionFormat() throws IOException { CellFormat cf1 = CellFormat.getInstance("# ?/?"); // Create a workbook, row and cell to test with diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java b/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java index 9dcbf16ac3..5117787d6f 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java @@ -17,21 +17,18 @@ package org.apache.poi.ss.formula.atp; -import static java.util.Calendar.OCTOBER; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import java.util.Calendar; -import java.util.Date; - -import junit.framework.TestCase; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.EvaluationException; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; -/** - * @author jfaenomoto@gmail.com - */ -public class TestDateParser extends TestCase { - +public class TestDateParser { + @Test public void testFailWhenNoDate() { try { DateParser.parseDate("potato"); @@ -41,6 +38,7 @@ public class TestDateParser extends TestCase { } } + @Test public void testFailWhenLooksLikeDateButItIsnt() { try { DateParser.parseDate("potato/cucumber/banana"); @@ -50,6 +48,7 @@ public class TestDateParser extends TestCase { } } + @Test public void testFailWhenIsInvalidDate() { try { DateParser.parseDate("13/13/13"); @@ -59,18 +58,18 @@ public class TestDateParser extends TestCase { } } - @SuppressWarnings("deprecation") + @Test public void testShouldParseValidDate() throws EvaluationException { - Calendar aDate = Calendar.getInstance(); - aDate.setTime(new Date(84, OCTOBER, 20)); - assertEquals(aDate, DateParser.parseDate("1984/10/20")); + Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); + Calendar actDate = DateParser.parseDate("1984/10/20"); + assertEquals(expDate, actDate); } - @SuppressWarnings("deprecation") + @Test public void testShouldIgnoreTimestamp() throws EvaluationException { - Calendar aDate = Calendar.getInstance(); - aDate.setTime(new Date(84, OCTOBER, 20)); - assertEquals(aDate, DateParser.parseDate("1984/10/20 12:34:56")); + Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); + Calendar actDate = DateParser.parseDate("1984/10/20 12:34:56"); + assertEquals(expDate, actDate); } } diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java b/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java index 15309d5c19..9df80a9d7a 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java @@ -17,21 +17,12 @@ package org.apache.poi.ss.formula.atp; -import static java.util.Calendar.DECEMBER; -import static java.util.Calendar.JANUARY; -import static java.util.Calendar.MARCH; -import static java.util.Calendar.NOVEMBER; -import static java.util.Calendar.OCTOBER; import static org.apache.poi.ss.formula.eval.ErrorEval.NAME_INVALID; import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; -import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Date; import java.util.List; -import junit.framework.TestCase; - import org.apache.poi.ss.formula.OperationEvaluationContext; import org.apache.poi.ss.formula.TwoDEval; import org.apache.poi.ss.formula.eval.AreaEval; @@ -40,23 +31,15 @@ import org.apache.poi.ss.formula.eval.NumericValueEval; import org.apache.poi.ss.formula.eval.StringEval; import org.apache.poi.ss.formula.eval.ValueEval; -/** - * @author jfaenomoto@gmail.com - */ -@SuppressWarnings("deprecation") // YK: uses deprecated {@link java.util.Date(int year, int month, int date)} -public class TestNetworkdaysFunction extends TestCase { - - private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); - - private static final String STARTING_DATE = formatter.format(new Date(108, OCTOBER, 1)); - - private static final String END_DATE = formatter.format(new Date(109, MARCH, 1)); - - private static final String FIRST_HOLIDAY = formatter.format(new Date(108, NOVEMBER, 26)); +import junit.framework.TestCase; - private static final String SECOND_HOLIDAY = formatter.format(new Date(108, DECEMBER, 4)); +public class TestNetworkdaysFunction extends TestCase { - private static final String THIRD_HOLIDAY = formatter.format(new Date(109, JANUARY, 21)); + private static final String STARTING_DATE = "2008/10/01"; + private static final String END_DATE = "2009/03/01"; + private static final String FIRST_HOLIDAY = "2008/11/26"; + private static final String SECOND_HOLIDAY = "2008/12/04"; + private static final String THIRD_HOLIDAY = "2009/01/21"; private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 1, 1, 1, null); diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java index 3ab1255a02..055149c6c6 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java @@ -17,87 +17,100 @@ package org.apache.poi.ss.formula.atp; -import static java.util.Calendar.DECEMBER; import static java.util.Calendar.SATURDAY; +import static org.junit.Assert.assertEquals; +import java.util.Calendar; import java.util.Date; -import junit.framework.TestCase; - import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; -/** - * @author jfaenomoto@gmail.com - */ -@SuppressWarnings("deprecation") // YK: heavily uses deprecated {@link java.util.Date(int year, int month, int date)} -public class TestWorkdayCalculator extends TestCase { +public class TestWorkdayCalculator { + @Test public void testCalculateWorkdaysShouldReturnJustWeekdaysWhenNoWeekend() { - final double A_MONDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 12)); - final double A_FRIDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 16)); + final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 12)); + final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); assertEquals(5, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_FRIDAY, new double[0])); } + @Test public void testCalculateWorkdaysShouldReturnAllDaysButNoSaturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 14)); - final double A_SATURDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 18)); + final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 14)); + final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 18)); assertEquals(3, WorkdayCalculator.instance.calculateWorkdays(A_WEDNESDAY, A_SATURDAY, new double[0])); } + @Test public void testCalculateWorkdaysShouldReturnAllDaysButNoSundays() { - final double A_SUNDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 11)); - final double A_THURSDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 15)); + final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); + final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 15)); assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_SUNDAY, A_THURSDAY, new double[0])); } + @Test public void testCalculateWorkdaysShouldReturnAllDaysButNoHolidays() { - final double A_MONDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 12)); - final double A_FRIDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 16)); - final double A_WEDNESDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 14)); + final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 12)); + final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); + final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 14)); assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_FRIDAY, new double[]{ A_WEDNESDAY })); } + @Test public void testCalculateWorkdaysShouldIgnoreWeekendHolidays() { - final double A_FRIDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 16)); - final double A_SATURDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 17)); - final double A_SUNDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 18)); - final double A_WEDNESDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 21)); + final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); + final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 17)); + final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 18)); + final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 21)); assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_FRIDAY, A_WEDNESDAY, new double[]{ A_SATURDAY, A_SUNDAY })); } + @Test public void testCalculateWorkdaysNumberOfDays() { double start = 41553.0; int days = 1; - assertEquals(new Date(113, 9, 7), WorkdayCalculator.instance.calculateWorkdays(start, days, new double[0])); + assertEquals(d(2013, 10, 7), WorkdayCalculator.instance.calculateWorkdays(start, days, new double[0])); } + @Test public void testPastDaysOfWeekShouldReturn0Past0Saturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 7)); - final double A_FRIDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 9)); + final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 7)); + final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 9)); assertEquals(0, WorkdayCalculator.instance.pastDaysOfWeek(A_WEDNESDAY, A_FRIDAY, SATURDAY)); } + @Test public void testPastDaysOfWeekShouldReturn1Past1Saturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 7)); - final double A_SUNDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 11)); + final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 7)); + final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_WEDNESDAY, A_SUNDAY, SATURDAY)); } + @Test public void testPastDaysOfWeekShouldReturn2Past2Saturdays() { - final double A_THURSDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 8)); - final double A_MONDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 19)); + final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 8)); + final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 19)); assertEquals(2, WorkdayCalculator.instance.pastDaysOfWeek(A_THURSDAY, A_MONDAY, SATURDAY)); } + @Test public void testPastDaysOfWeekShouldReturn1BeginningFromASaturday() { - final double A_SATURDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 10)); - final double A_SUNDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 11)); + final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 10)); + final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_SATURDAY, A_SUNDAY, SATURDAY)); } + @Test public void testPastDaysOfWeekShouldReturn1EndingAtASaturday() { - final double A_THURSDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 8)); - final double A_SATURDAY = DateUtil.getExcelDate(new Date(111, DECEMBER, 10)); + final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 8)); + final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 10)); assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_THURSDAY, A_SATURDAY, SATURDAY)); } + + private static Date d(int year, int month, int day) { + Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day, 0, 0, 0); + return cal.getTime(); + } } diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java index 94deb2db0a..02af969a2b 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java @@ -18,17 +18,12 @@ package org.apache.poi.ss.formula.atp; -import static java.util.Calendar.APRIL; -import static java.util.Calendar.DECEMBER; -import static java.util.Calendar.JANUARY; -import static java.util.Calendar.MAY; -import static java.util.Calendar.NOVEMBER; -import static java.util.Calendar.OCTOBER; -import static java.util.Calendar.SEPTEMBER; + import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; +import static org.junit.Assert.assertEquals; -import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Calendar; import java.util.Date; import java.util.List; @@ -40,114 +35,140 @@ import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.formula.eval.StringEval; import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; -import junit.framework.TestCase; - -/** - * @author jfaenomoto@gmail.com - */ -@SuppressWarnings("deprecation") // YK: heavily uses deprecated {@link java.util.Date(int year, int month, int date)} -public class TestWorkdayFunction extends TestCase { - - private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); - - private static final String STARTING_DATE = formatter.format(new Date(108, OCTOBER, 1)); +public class TestWorkdayFunction { - private static final String FIRST_HOLIDAY = formatter.format(new Date(108, NOVEMBER, 26)); - - private static final String SECOND_HOLIDAY = formatter.format(new Date(108, DECEMBER, 4)); - - private static final String THIRD_HOLIDAY = formatter.format(new Date(109, JANUARY, 21)); - - private static final String RETROATIVE_HOLIDAY = formatter.format(new Date(108, SEPTEMBER, 29)); + private static final String STARTING_DATE = "2008/10/01"; + private static final String FIRST_HOLIDAY = "2008/11/26"; + private static final String SECOND_HOLIDAY = "2008/12/04"; + private static final String THIRD_HOLIDAY = "2009/01/21"; + private static final String RETROATIVE_HOLIDAY = "2008/09/29"; private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 1, 1, 1, null); + @Test public void testFailWhenNoArguments() { - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(new ValueEval[0], null)); + ValueEval ve[] = new ValueEval[0]; + assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); } + @Test public void testFailWhenLessThan2Arguments() { - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(new ValueEval[1], null)); + ValueEval ve[] = new ValueEval[1]; + assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); } + @Test public void testFailWhenMoreThan3Arguments() { - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(new ValueEval[4], null)); + ValueEval ve[] = new ValueEval[4]; + assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); } + @Test public void testFailWhenArgumentsAreNotDatesNorNumbers() { - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate( - new ValueEval[]{ new StringEval("Potato"), new StringEval("Cucumber") }, EC)); + ValueEval ve[] = { new StringEval("Potato"), new StringEval("Cucumber") }; + assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, EC)); } + @Test public void testReturnWorkdays() { - assertEquals(new Date(109, APRIL, 30), DateUtil.getJavaDate(((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new NumberEval(151) }, EC)).getNumberValue())); + Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 3, 30); + Date expDate = expCal.getTime(); + ValueEval ve[] = { new StringEval(STARTING_DATE), new NumberEval(151) }; + Date actDate = DateUtil.getJavaDate(((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue()); + assertEquals(expDate, actDate); } + @Test public void testReturnWorkdaysSpanningAWeekendSubtractingDays() { - String startDate = "2013/09/30"; - int days = -1; - StringEval stringEval = new StringEval(startDate); - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - stringEval, new NumberEval(days) }, EC)).getNumberValue(); - assertEquals(41544.0, numberValue); + Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 8, 27); + Date expDate = expCal.getTime(); + + ValueEval ve[] = { new StringEval("2013/09/30"), new NumberEval(-1) }; + double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); + assertEquals(41544.0, numberValue, 0); - Date date = DateUtil.getJavaDate(numberValue); - assertEquals("Should be 2013/09/27", new Date(113, 8, 27), date); + Date actDate = DateUtil.getJavaDate(numberValue); + assertEquals(expDate, actDate); } + @Test public void testReturnWorkdaysSpanningAWeekendAddingDays() { - String startDate = "2013/09/27"; - int days = 1; - StringEval stringEval = new StringEval(startDate); - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - stringEval, new NumberEval(days) }, EC)).getNumberValue(); - assertEquals(41547.0, numberValue); - - Date date = DateUtil.getJavaDate(numberValue); - assertEquals("Should be 2013/09/30", new Date(113, 8, 30), date); + Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 8, 30); + Date expDate = expCal.getTime(); + + ValueEval ve[] = { new StringEval("2013/09/27"), new NumberEval(1) }; + double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); + assertEquals(41547.0, numberValue, 0); + + Date actDate = DateUtil.getJavaDate(numberValue); + assertEquals(expDate, actDate); } + @Test public void testReturnWorkdaysWhenStartIsWeekendAddingDays() { - String startDate = "2013/10/06"; - int days = 1; - StringEval stringEval = new StringEval(startDate); - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - stringEval, new NumberEval(days) }, EC)).getNumberValue(); - assertEquals(41554.0, numberValue); - - Date date = DateUtil.getJavaDate(numberValue); - assertEquals("Should be 2013/10/07", new Date(113, 9, 7), date); + Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 9, 7); + Date expDate = expCal.getTime(); + + ValueEval ve[] = { new StringEval("2013/10/06"), new NumberEval(1) }; + double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); + assertEquals(41554.0, numberValue, 0); + + Date actDate = DateUtil.getJavaDate(numberValue); + assertEquals(expDate, actDate); } + @Test public void testReturnWorkdaysWhenStartIsWeekendSubtractingDays() { - String startDate = "2013/10/06"; - int days = -1; - StringEval stringEval = new StringEval(startDate); - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - stringEval, new NumberEval(days) }, EC)).getNumberValue(); - assertEquals(41551.0, numberValue); - - Date date = DateUtil.getJavaDate(numberValue); - assertEquals("Should be 2013/10/04", new Date(113, 9, 4), date); + Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 9, 4); + Date expDate = expCal.getTime(); + + ValueEval ve[] = { new StringEval("2013/10/06"), new NumberEval(-1) }; + double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); + assertEquals(41551.0, numberValue, 0); + + Date actDate = DateUtil.getJavaDate(numberValue); + assertEquals(expDate, actDate); } + @Test public void testReturnWorkdaysWithDaysTruncated() { - assertEquals(new Date(109, APRIL, 30), DateUtil.getJavaDate(((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new NumberEval(151.99999) }, EC)).getNumberValue())); + Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 3, 30); + Date expDate = expCal.getTime(); + + ValueEval ve[] = { new StringEval(STARTING_DATE), new NumberEval(151.99999) }; + double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); + + Date actDate = DateUtil.getJavaDate(numberValue); + assertEquals(expDate, actDate); } + @Test public void testReturnRetroativeWorkday() { - assertEquals(new Date(108, SEPTEMBER, 23), DateUtil.getJavaDate(((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new NumberEval(-5), new StringEval(RETROATIVE_HOLIDAY) }, EC)) - .getNumberValue())); + Calendar expCal = LocaleUtil.getLocaleCalendar(2008, 8, 23); + Date expDate = expCal.getTime(); + + ValueEval ve[] = { new StringEval(STARTING_DATE), new NumberEval(-5), new StringEval(RETROATIVE_HOLIDAY) }; + double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); + + Date actDate = DateUtil.getJavaDate(numberValue); + assertEquals(expDate, actDate); } + @Test public void testReturnNetworkdaysWithManyHolidays() { - assertEquals(new Date(109, MAY, 5), DateUtil.getJavaDate(((NumberEval) WorkdayFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new NumberEval(151), - new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY) }, EC)).getNumberValue())); + Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 4, 5); + Date expDate = expCal.getTime(); + + ValueEval ve[] = { + new StringEval(STARTING_DATE), new NumberEval(151), + new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY) }; + double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); + + Date actDate = DateUtil.getJavaDate(numberValue); + assertEquals(expDate, actDate); } private class MockAreaEval extends AreaEvalBase { diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java index abd8ba2ccd..6094d1860b 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java @@ -17,20 +17,21 @@ package org.apache.poi.ss.formula.atp; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.Locale; +import static org.junit.Assert.assertEquals; -import junit.framework.TestCase; +import java.util.Calendar; import org.apache.poi.ss.formula.eval.EvaluationException; import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; /** * Specific test cases for YearFracCalculator */ -public final class TestYearFracCalculator extends TestCase { +public final class TestYearFracCalculator { + @Test public void testBasis1() { confirm(md(1999, 1, 1), md(1999, 4, 5), 1, 0.257534247); confirm(md(1999, 4, 1), md(1999, 4, 5), 1, 0.010958904); @@ -59,10 +60,7 @@ public final class TestYearFracCalculator extends TestCase { } private static double md(int year, int month, int day) { - Calendar c = new GregorianCalendar(Locale.ROOT); - - c.set(year, month-1, day, 0, 0, 0); - c.set(Calendar.MILLISECOND, 0); + Calendar c = LocaleUtil.getLocaleCalendar(year, month-1, day); return DateUtil.getExcelDate(c.getTime()); } } diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java index d735fe8c2c..4860d6b05e 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java @@ -17,31 +17,29 @@ package org.apache.poi.ss.formula.atp; -import java.io.PrintStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.util.Calendar; -import java.util.GregorianCalendar; import java.util.Iterator; -import junit.framework.Assert; -import junit.framework.AssertionFailedError; -import junit.framework.ComparisonFailure; -import junit.framework.TestCase; - import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.eval.EvaluationException; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.formula.eval.EvaluationException; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; /** * Tests YearFracCalculator using test-cases listed in a sample spreadsheet - * - * @author Josh Micich */ -public final class TestYearFracCalculatorFromSpreadsheet extends TestCase { +public final class TestYearFracCalculatorFromSpreadsheet { private static final class SS { @@ -52,15 +50,14 @@ public final class TestYearFracCalculatorFromSpreadsheet extends TestCase { public static final int EXPECTED_RESULT_COLUMN = 13; // "N" } - public void testAll() { + @Test + public void testAll() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("yearfracExamples.xls"); HSSFSheet sheet = wb.getSheetAt(0); HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(wb); int nSuccess = 0; - int nFailures = 0; - int nUnexpectedErrors = 0; - Iterator rowIterator = sheet.rowIterator(); + Iterator<Row> rowIterator = sheet.rowIterator(); while(rowIterator.hasNext()) { HSSFRow row = (HSSFRow) rowIterator.next(); @@ -68,28 +65,16 @@ public final class TestYearFracCalculatorFromSpreadsheet extends TestCase { if (cell == null || cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA) { continue; } - try { - processRow(row, cell, formulaEvaluator); - nSuccess++; - } catch (RuntimeException e) { - nUnexpectedErrors ++; - printShortStackTrace(System.err, e); - } catch (AssertionFailedError e) { - nFailures ++; - printShortStackTrace(System.err, e); - } - } - if (nUnexpectedErrors + nFailures > 0) { - String msg = nFailures + " failures(s) and " + nUnexpectedErrors - + " unexpected errors(s) occurred. See stderr for details"; - throw new AssertionFailedError(msg); - } - if (nSuccess < 1) { - throw new RuntimeException("No test sample cases found"); + processRow(row, cell, formulaEvaluator); + nSuccess++; } + + assertTrue("No test sample cases found", nSuccess > 0); + wb.close(); } - private static void processRow(HSSFRow row, HSSFCell cell, HSSFFormulaEvaluator formulaEvaluator) { + private void processRow(HSSFRow row, HSSFCell cell, HSSFFormulaEvaluator formulaEvaluator) + throws EvaluationException { double startDate = makeDate(row, SS.START_YEAR_COLUMN); double endDate = makeDate(row, SS.END_YEAR_COLUMN); @@ -98,81 +83,33 @@ public final class TestYearFracCalculatorFromSpreadsheet extends TestCase { double expectedValue = getDoubleCell(row, SS.EXPECTED_RESULT_COLUMN); - double actualValue; - try { - actualValue = YearFracCalculator.calculate(startDate, endDate, basis); - } catch (EvaluationException e) { - throw new RuntimeException(e); - } - if (expectedValue != actualValue) { - throw new ComparisonFailure("Direct calculate failed - row " + (row.getRowNum()+1), - String.valueOf(expectedValue), String.valueOf(actualValue)); - } + double actualValue = YearFracCalculator.calculate(startDate, endDate, basis); + + String loc = " - row " + (row.getRowNum()+1); + assertEquals("Direct calculate failed"+loc, expectedValue, actualValue, 0); actualValue = formulaEvaluator.evaluate(cell).getNumberValue(); - if (expectedValue != actualValue) { - throw new ComparisonFailure("Formula evaluate failed - row " + (row.getRowNum()+1), - String.valueOf(expectedValue), String.valueOf(actualValue)); - } + assertEquals("Formula evaluate failed"+loc, expectedValue, actualValue, 0); } private static double makeDate(HSSFRow row, int yearColumn) { int year = getIntCell(row, yearColumn + 0); int month = getIntCell(row, yearColumn + 1); int day = getIntCell(row, yearColumn + 2); - Calendar c = new GregorianCalendar(year, month-1, day, 0, 0, 0); - c.set(Calendar.MILLISECOND, 0); + Calendar c = LocaleUtil.getLocaleCalendar(year, month-1, day); return HSSFDateUtil.getExcelDate(c.getTime()); } private static int getIntCell(HSSFRow row, int colIx) { double dVal = getDoubleCell(row, colIx); - if (Math.floor(dVal) != dVal) { - throw new RuntimeException("Non integer value (" + dVal - + ") cell found at column " + (char)('A' + colIx)); - } + String msg = "Non integer value (" + dVal + ") cell found at column " + (char)('A' + colIx); + assertEquals(msg, Math.floor(dVal), dVal, 0); return (int)dVal; } private static double getDoubleCell(HSSFRow row, int colIx) { HSSFCell cell = row.getCell(colIx); - if (cell == null) { - throw new RuntimeException("No cell found at column " + colIx); - } + assertNotNull("No cell found at column " + colIx, cell); double dVal = cell.getNumericCellValue(); return dVal; } - - /** - * Useful to keep output concise when expecting many failures to be reported by this test case - * TODO - refactor duplicates in other Test~FromSpreadsheet classes - */ - private static void printShortStackTrace(PrintStream ps, Throwable e) { - StackTraceElement[] stes = e.getStackTrace(); - - int startIx = 0; - // skip any top frames inside junit.framework.Assert - while(startIx<stes.length) { - if(!stes[startIx].getClassName().equals(Assert.class.getName())) { - break; - } - startIx++; - } - // skip bottom frames (part of junit framework) - int endIx = startIx+1; - while(endIx < stes.length) { - if(stes[endIx].getClassName().equals(TestCase.class.getName())) { - break; - } - endIx++; - } - if(startIx >= endIx) { - // something went wrong. just print the whole stack trace - e.printStackTrace(ps); - } - endIx -= 4; // skip 4 frames of reflection invocation - ps.println(e.toString()); - for(int i=startIx; i<endIx; i++) { - ps.println("\tat " + stes[i].toString()); - } - } } diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java index d7b17a4c5c..85ddfe01c3 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java @@ -21,8 +21,9 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; -import java.io.PrintStream; +import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.Locale; import org.apache.poi.hssf.HSSFTestDataSamples; @@ -33,14 +34,15 @@ import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.junit.Assert; -import org.junit.Before; +import org.apache.poi.util.LocaleUtil; +import org.junit.AfterClass; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; import junit.framework.AssertionFailedError; -import junit.framework.TestCase; /** * Tests formulas and operators as loaded from a test data spreadsheet.<p/> @@ -49,248 +51,166 @@ import junit.framework.TestCase; * exercised as well. Tests for bug fixes and specific/tricky behaviour can be found in the * corresponding test class (<tt>TestXxxx</tt>) of the target (<tt>Xxxx</tt>) implementor, * where execution can be observed more easily. - * - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > */ +@RunWith(Parameterized.class) public final class TestFormulasFromSpreadsheet { - private static final POILogger logger = POILogFactory.getLogger(TestFormulasFromSpreadsheet.class); - private static final class Result { - public static final int SOME_EVALUATIONS_FAILED = -1; - public static final int ALL_EVALUATIONS_SUCCEEDED = +1; - public static final int NO_EVALUATIONS_FOUND = 0; - } - - /** + private static HSSFWorkbook workbook; + private static Sheet sheet; + private static HSSFFormulaEvaluator evaluator; + private static Locale userLocale; + + /** * This class defines constants for navigating around the test data spreadsheet used for these tests. */ - private static final class SS { + private static interface SS { /** * Name of the test spreadsheet (found in the standard test data folder) */ - public final static String FILENAME = "FormulaEvalTestData.xls"; + String FILENAME = "FormulaEvalTestData.xls"; /** * Row (zero-based) in the test spreadsheet where the operator examples start. */ - public static final int START_OPERATORS_ROW_INDEX = 22; // Row '23' + int START_OPERATORS_ROW_INDEX = 22; // Row '23' /** * Row (zero-based) in the test spreadsheet where the function examples start. */ - public static final int START_FUNCTIONS_ROW_INDEX = 95; // Row '96' + int START_FUNCTIONS_ROW_INDEX = 95; // Row '96' /** * Index of the column that contains the function names */ - public static final int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B' + int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B' /** * Used to indicate when there are no more functions left */ - public static final String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>"; + String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>"; /** * Index of the column where the test values start (for each function) */ - public static final short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D' + short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D' /** * Each function takes 4 rows in the test spreadsheet */ - public static final int NUMBER_OF_ROWS_PER_FUNCTION = 4; - } - - private HSSFWorkbook workbook; - private Sheet sheet; - // Note - multiple failures are aggregated before ending. - // If one or more functions fail, a single AssertionFailedError is thrown at the end - private int _functionFailureCount; - private int _functionSuccessCount; - private int _evaluationFailureCount; - private int _evaluationSuccessCount; - - private static final Cell getExpectedValueCell(Row row, int columnIndex) { - if (row == null) { - return null; - } - return row.getCell(columnIndex); - } - - - private static void confirmExpectedResult(String msg, Cell expected, CellValue actual) { - assertNotNull(msg + " - Bad setup data expected value is null", expected); - assertNotNull(msg + " - actual value was null", actual); - - switch (expected.getCellType()) { - case Cell.CELL_TYPE_BLANK: - assertEquals(msg, Cell.CELL_TYPE_BLANK, actual.getCellType()); - break; - case Cell.CELL_TYPE_BOOLEAN: - assertEquals(msg, Cell.CELL_TYPE_BOOLEAN, actual.getCellType()); - assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue()); - break; - case Cell.CELL_TYPE_ERROR: - assertEquals(msg, Cell.CELL_TYPE_ERROR, actual.getCellType()); - assertEquals(msg, ErrorEval.getText(expected.getErrorCellValue()), ErrorEval.getText(actual.getErrorValue())); - break; - case Cell.CELL_TYPE_FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case Cell.CELL_TYPE_NUMERIC: - assertEquals(msg, Cell.CELL_TYPE_NUMERIC, actual.getCellType()); - TestMathX.assertEquals(msg, expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); - break; - case Cell.CELL_TYPE_STRING: - assertEquals(msg, Cell.CELL_TYPE_STRING, actual.getCellType()); - assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getStringValue()); - break; - } - } - - @Before - protected void setUp() { - if (workbook == null) { - workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); - sheet = workbook.getSheetAt( 0 ); - } - _functionFailureCount = 0; - _functionSuccessCount = 0; - _evaluationFailureCount = 0; - _evaluationSuccessCount = 0; + int NUMBER_OF_ROWS_PER_FUNCTION = 4; } - @Test - public void testFunctionsFromTestSpreadsheet() { - - processFunctionGroup(SS.START_OPERATORS_ROW_INDEX, null); - processFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null); - // example for debugging individual functions/operators: -// processFunctionGroup(SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); -// processFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, "AVERAGE"); - - // confirm results - String successMsg = "There were " - + _evaluationSuccessCount + " successful evaluation(s) and " - + _functionSuccessCount + " function(s) without error"; - String msg = _functionFailureCount + " function(s) failed in " - + _evaluationFailureCount + " evaluation(s). " + successMsg; - assertEquals(msg, _functionFailureCount, 0); - logger.log(POILogger.INFO, getClass().getName() + ": " + successMsg); - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass <code>null</code> to test all functions - */ - private void processFunctionGroup(int startRowIndex, String testFocusFunctionName) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook); - Collection<String> funcs = FunctionEval.getSupportedFunctionNames(); - - int rowIndex = startRowIndex; - while (true) { - Row r = sheet.getRow(rowIndex); - String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Test spreadsheet cell empty on row (" + @Parameter(value = 0) + public String targetFunctionName; + @Parameter(value = 1) + public int formulasRowIdx; + @Parameter(value = 2) + public int expectedValuesRowIdx; + + @AfterClass + public static void closeResource() throws Exception { + LocaleUtil.setUserLocale(userLocale); + workbook.close(); + } + + @Parameters(name="{0}") + public static Collection<Object[]> data() throws Exception { + // Function "Text" uses custom-formats which are locale specific + // can't set the locale on a per-testrun execution, as some settings have been + // already set, when we would try to change the locale by then + userLocale = LocaleUtil.getUserLocale(); + LocaleUtil.setUserLocale(Locale.ROOT); + + workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); + sheet = workbook.getSheetAt( 0 ); + evaluator = new HSSFFormulaEvaluator(workbook); + + List<Object[]> data = new ArrayList<Object[]>(); + + processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, null); + processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); + // example for debugging individual functions/operators: + // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); + // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); + + return data; + } + + /** + * @param startRowIndex row index in the spreadsheet where the first function/operator is found + * @param testFocusFunctionName name of a single function/operator to test alone. + * Typically pass <code>null</code> to test all functions + */ + private static void processFunctionGroup(List<Object[]> data, int startRowIndex, String testFocusFunctionName) { + for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) { + Row r = sheet.getRow(rowIndex); + String targetFunctionName = getTargetFunctionName(r); + assertNotNull("Test spreadsheet cell empty on row (" + (rowIndex+1) + "). Expected function name or '" + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Row expectedValuesRow = sheet.getRow(rowIndex + 1); + if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { + // found end of functions list + break; + } + if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { + + // expected results are on the row below + Row expectedValuesRow = sheet.getRow(rowIndex + 1); int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row assertNotNull("Missing expected values row for function '" + targetFunctionName + " (row " + missingRowNum + ")", expectedValuesRow); - switch(processFunctionRow(evaluator, targetFunctionName, r, expectedValuesRow)) { - case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break; - case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break; - default: - throw new RuntimeException("unexpected result"); - case Result.NO_EVALUATIONS_FOUND: // do nothing - String uname = targetFunctionName.toUpperCase(Locale.ROOT); - if(startRowIndex >= SS.START_FUNCTIONS_ROW_INDEX && - funcs.contains(uname)) { - logger.log(POILogger.WARN, uname + ": function is supported but missing test data"); - } - break; - } - } - rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION; - } - } - - /** - * - * @return a constant from the local Result class denoting whether there were any evaluation - * cases, and whether they all succeeded. - */ - private int processFunctionRow(HSSFFormulaEvaluator evaluator, String targetFunctionName, - Row formulasRow, Row expectedValuesRow) { - - int result = Result.NO_EVALUATIONS_FOUND; // so far - short endcolnum = formulasRow.getLastCellNum(); - - // iterate across the row for all the evaluation cases - for (int colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { - Cell c = formulasRow.getCell(colnum); - if (c == null || c.getCellType() != Cell.CELL_TYPE_FORMULA) { - continue; - } - - CellValue actualValue = evaluator.evaluate(c); - - Cell expectedValueCell = getExpectedValueCell(expectedValuesRow, colnum); - try { - confirmExpectedResult("Function '" + targetFunctionName + "': Formula: " + c.getCellFormula() + " @ " + formulasRow.getRowNum() + ":" + colnum, - expectedValueCell, actualValue); - _evaluationSuccessCount ++; - if(result != Result.SOME_EVALUATIONS_FAILED) { - result = Result.ALL_EVALUATIONS_SUCCEEDED; - } - } catch (AssertionFailedError e) { - _evaluationFailureCount ++; - printShortStackTrace(System.err, e); - result = Result.SOME_EVALUATIONS_FAILED; - } - } - return result; - } - - /** - * Useful to keep output concise when expecting many failures to be reported by this test case - */ - private static void printShortStackTrace(PrintStream ps, AssertionFailedError e) { - StackTraceElement[] stes = e.getStackTrace(); - - int startIx = 0; - // skip any top frames inside junit.framework.Assert - while(startIx<stes.length) { - if(!stes[startIx].getClassName().equals(Assert.class.getName())) { - break; - } - startIx++; - } - // skip bottom frames (part of junit framework) - int endIx = startIx+1; - while(endIx < stes.length) { - if(stes[endIx].getClassName().equals(TestCase.class.getName())) { - break; - } - endIx++; - } - if(startIx >= endIx) { - // something went wrong. just print the whole stack trace - e.printStackTrace(ps); - } - endIx -= 4; // skip 4 frames of reflection invocation - ps.println(e.toString()); - for(int i=startIx; i<endIx; i++) { - ps.println("\tat " + stes[i].toString()); - } - } + data.add(new Object[]{targetFunctionName, rowIndex, rowIndex + 1}); + } + } + } + + @Test + public void processFunctionRow() { + Row formulasRow = sheet.getRow(formulasRowIdx); + Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); + + short endcolnum = formulasRow.getLastCellNum(); + + // iterate across the row for all the evaluation cases + for (int colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { + Cell c = formulasRow.getCell(colnum); + if (c == null || c.getCellType() != Cell.CELL_TYPE_FORMULA) { + continue; + } + + CellValue actValue = evaluator.evaluate(c); + Cell expValue = (expectedValuesRow == null) ? null : expectedValuesRow.getCell(colnum); + + String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" + , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); + + assertNotNull(msg + " - Bad setup data expected value is null", expValue); + assertNotNull(msg + " - actual value was null", actValue); + + switch (expValue.getCellType()) { + case Cell.CELL_TYPE_BLANK: + assertEquals(msg, Cell.CELL_TYPE_BLANK, actValue.getCellType()); + break; + case Cell.CELL_TYPE_BOOLEAN: + assertEquals(msg, Cell.CELL_TYPE_BOOLEAN, actValue.getCellType()); + assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); + break; + case Cell.CELL_TYPE_ERROR: + assertEquals(msg, Cell.CELL_TYPE_ERROR, actValue.getCellType()); + assertEquals(msg, ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue())); + break; + case Cell.CELL_TYPE_FORMULA: // will never be used, since we will call method after formula evaluation + fail("Cannot expect formula as result of formula evaluation: " + msg); + case Cell.CELL_TYPE_NUMERIC: + assertEquals(msg, Cell.CELL_TYPE_NUMERIC, actValue.getCellType()); + TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); + break; + case Cell.CELL_TYPE_STRING: + assertEquals(msg, Cell.CELL_TYPE_STRING, actValue.getCellType()); + assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); + break; + } + } + } /** * @return <code>null</code> if cell is missing, empty or blank */ diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java index 29fabef20f..dbe41a883c 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java @@ -28,6 +28,7 @@ import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.ss.formula.eval.BoolEval; import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.formula.eval.ValueEval; +import org.apache.poi.util.LocaleUtil; import org.junit.Test; public final class TestDays360 { @@ -36,14 +37,13 @@ public final class TestDays360 { * @param month 1-based */ private static Date makeDate(int year, int month, int day) { - Calendar cal = Calendar.getInstance(Locale.ROOT); - cal.set(year, month-1, day, 0, 0, 0); - cal.set(Calendar.MILLISECOND, 0); + Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day); return cal.getTime(); } private static Date decrementDay(Date d) { - Calendar c = (Calendar)d.clone(); + Calendar c = LocaleUtil.getLocaleCalendar(); + c.setTime(d); c.add(Calendar.DAY_OF_MONTH, -1); return c.getTime(); } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java b/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java index 3917f44cb9..e8eaf4c5fb 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java @@ -17,22 +17,24 @@ package org.apache.poi.ss.formula.functions; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.util.Calendar; import java.util.Date; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.AreaEval; import org.apache.poi.ss.formula.eval.BlankEval; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.RefEval; import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.ErrorConstants; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; -public class TestEDate extends TestCase { +public class TestEDate { + @Test public void testEDateProperValues() { // verify some border-case combinations of startDate and month-increase checkValue(1000, 0, 1000d); @@ -49,71 +51,79 @@ public class TestEDate extends TestCase { private void checkValue(int startDate, int monthInc, double expectedResult) { EDate eDate = new EDate(); NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(startDate), new NumberEval(monthInc)}, null); - assertEquals(expectedResult, result.getNumberValue()); + assertEquals(expectedResult, result.getNumberValue(), 0); } + @Test public void testEDateInvalidValues() { EDate eDate = new EDate(); ErrorEval result = (ErrorEval) eDate.evaluate(new ValueEval[]{new NumberEval(1000)}, null); - assertEquals(ErrorConstants.ERROR_VALUE, result.getErrorCode()); + assertEquals(ErrorConstants.ERROR_VALUE, result.getErrorCode(), 0); } + @Test public void testEDateIncrease() { EDate eDate = new EDate(); Date startDate = new Date(); int offset = 2; NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(DateUtil.getExcelDate(startDate)), new NumberEval(offset)}, null); Date resultDate = DateUtil.getJavaDate(result.getNumberValue()); - Calendar instance = Calendar.getInstance(); + Calendar instance = LocaleUtil.getLocaleCalendar(); instance.setTime(startDate); instance.add(Calendar.MONTH, offset); assertEquals(resultDate, instance.getTime()); } + @Test public void testEDateDecrease() { EDate eDate = new EDate(); Date startDate = new Date(); int offset = -2; NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(DateUtil.getExcelDate(startDate)), new NumberEval(offset)}, null); Date resultDate = DateUtil.getJavaDate(result.getNumberValue()); - Calendar instance = Calendar.getInstance(); + Calendar instance = LocaleUtil.getLocaleCalendar(); instance.setTime(startDate); instance.add(Calendar.MONTH, offset); assertEquals(resultDate, instance.getTime()); } + @Test public void testBug56688() { EDate eDate = new EDate(); NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(1000), new RefEvalImplementation(new NumberEval(0))}, null); - assertEquals(1000d, result.getNumberValue()); + assertEquals(1000d, result.getNumberValue(), 0); } + @Test public void testRefEvalStartDate() { EDate eDate = new EDate(); NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new RefEvalImplementation(new NumberEval(1000)), new NumberEval(0)}, null); - assertEquals(1000d, result.getNumberValue()); + assertEquals(1000d, result.getNumberValue(), 0); } + @Test public void testEDateInvalidValueEval() { ValueEval evaluate = new EDate().evaluate(new ValueEval[]{new ValueEval() {}, new NumberEval(0)}, null); assertTrue(evaluate instanceof ErrorEval); assertEquals(ErrorEval.VALUE_INVALID, evaluate); } + @Test public void testEDateBlankValueEval() { NumberEval evaluate = (NumberEval) new EDate().evaluate(new ValueEval[]{BlankEval.instance, new NumberEval(0)}, null); - assertEquals(-1.0d, evaluate.getNumberValue()); + assertEquals(-1.0d, evaluate.getNumberValue(), 0); } + @Test public void testEDateBlankRefValueEval() { EDate eDate = new EDate(); NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new RefEvalImplementation(BlankEval.instance), new NumberEval(0)}, null); assertEquals("0 startDate triggers BAD_DATE currently, thus -1.0!", - -1.0d, result.getNumberValue()); + -1.0d, result.getNumberValue(), 0); result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(1), new RefEvalImplementation(BlankEval.instance)}, null); assertEquals("Blank is handled as 0 otherwise", - 1.0d, result.getNumberValue()); + 1.0d, result.getNumberValue(), 0); } } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java b/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java index 55372b03a5..1a15760a76 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java @@ -17,12 +17,13 @@ package org.apache.poi.ss.formula.functions;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
import java.util.Calendar;
import java.util.Date;
-import junit.framework.TestCase;
import org.apache.poi.ss.formula.OperationEvaluationContext;
-
import org.apache.poi.ss.formula.eval.BlankEval;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.NumberEval;
@@ -30,8 +31,10 @@ import org.apache.poi.ss.formula.eval.StringEval; import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.ErrorConstants;
+import org.apache.poi.util.LocaleUtil;
+import org.junit.Test;
-public class TestEOMonth extends TestCase{
+public class TestEOMonth {
private static final double BAD_DATE = -1.0;
@@ -47,6 +50,7 @@ public class TestEOMonth extends TestCase{ private final FreeRefFunction eOMonth = EOMonth.instance;
private final OperationEvaluationContext ec = new OperationEvaluationContext(null, null, 0, 0, 0, null);
+ @Test
public void testEOMonthProperValues() {
// verify some border-case combinations of startDate and month-increase
checkValue(DATE_1900_01_01, 0, DATE_1900_01_31);
@@ -56,6 +60,7 @@ public class TestEOMonth extends TestCase{ checkValue(DATE_2034_06_09, 1, DATE_2034_07_31);
}
+ @Test
public void testEOMonthBadDateValues() {
checkValue(0.0, -2, BAD_DATE);
checkValue(0.0, -3, BAD_DATE);
@@ -63,74 +68,85 @@ public class TestEOMonth extends TestCase{ }
private void checkValue(double startDate, int monthInc, double expectedResult) {
- NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(startDate), new NumberEval(monthInc)}, ec);
- assertEquals(expectedResult, result.getNumberValue());
+ ValueEval ve[] = {new NumberEval(startDate), new NumberEval(monthInc)};
+ NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec);
+ assertEquals(expectedResult, result.getNumberValue(), 0);
}
+ @Test
public void testEOMonthZeroDate() {
NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(0), new NumberEval(0)}, ec);
- assertEquals("0 startDate is 1900-01-00", DATE_1900_01_31, result.getNumberValue());
+ assertEquals("0 startDate is 1900-01-00", DATE_1900_01_31, result.getNumberValue(), 0);
result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(0), new NumberEval(1)}, ec);
- assertEquals("0 startDate is 1900-01-00", DATE_1900_02_28, result.getNumberValue());
+ assertEquals("0 startDate is 1900-01-00", DATE_1900_02_28, result.getNumberValue(), 0);
}
+ @Test
public void testEOMonthInvalidArguments() {
ValueEval result = eOMonth.evaluate(new ValueEval[] {new NumberEval(DATE_1902_09_26)}, ec);
assertTrue(result instanceof ErrorEval);
- assertEquals(ErrorConstants.ERROR_VALUE, ((ErrorEval) result).getErrorCode());
+ assertEquals(ErrorConstants.ERROR_VALUE, ((ErrorEval) result).getErrorCode(), 0);
result = eOMonth.evaluate(new ValueEval[] {new StringEval("a"), new StringEval("b")}, ec);
assertTrue(result instanceof ErrorEval);
- assertEquals(ErrorConstants.ERROR_VALUE, ((ErrorEval) result).getErrorCode());
- }
-
- public void testEOMonthIncrease() {
- checkOffset(new Date(), 2);
- }
-
- public void testEOMonthDecrease() {
- checkOffset(new Date(), -2);
+ assertEquals(ErrorConstants.ERROR_VALUE, ((ErrorEval) result).getErrorCode(), 0);
}
- private void checkOffset(Date startDate, int offset) {
- NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(DateUtil.getExcelDate(startDate)), new NumberEval(offset)}, ec);
- Date resultDate = DateUtil.getJavaDate(result.getNumberValue());
- Calendar instance = Calendar.getInstance();
- instance.setTime(startDate);
- instance.add(Calendar.MONTH, offset);
- instance.add(Calendar.MONTH, 1);
- instance.set(Calendar.DAY_OF_MONTH, 1);
- instance.add(Calendar.DAY_OF_MONTH, -1);
- instance.set(Calendar.HOUR_OF_DAY, 0);
- instance.set(Calendar.MINUTE, 0);
- instance.set(Calendar.SECOND, 0);
- instance.set(Calendar.MILLISECOND, 0);
- assertEquals(instance.getTime(), resultDate);
+ @Test
+ public void checkOffset() {
+ for (int offset=-12; offset<=12; offset++) {
+ Calendar cal = LocaleUtil.getLocaleCalendar();
+ Date startDate = cal.getTime();
+
+ cal.add(Calendar.MONTH, offset);
+ cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
+ cal.clear(Calendar.HOUR);
+ cal.set(Calendar.HOUR_OF_DAY, 0);
+ cal.clear(Calendar.MINUTE);
+ cal.clear(Calendar.SECOND);
+ cal.clear(Calendar.MILLISECOND);
+ Date expDate = cal.getTime();
+
+ ValueEval ve[] = {
+ new NumberEval(DateUtil.getExcelDate(startDate)),
+ new NumberEval(offset)
+ };
+ NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec);
+ Date actDate = DateUtil.getJavaDate(result.getNumberValue());
+
+ assertEquals(expDate, actDate);
+ }
}
+ @Test
public void testBug56688() {
- NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(DATE_1902_09_26), new RefEvalImplementation(new NumberEval(0))}, ec);
- assertEquals(DATE_1902_09_30, result.getNumberValue());
+ ValueEval ve[] = {new NumberEval(DATE_1902_09_26), new RefEvalImplementation(new NumberEval(0))};
+ NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec);
+ assertEquals(DATE_1902_09_30, result.getNumberValue(), 0);
}
+ @Test
public void testRefEvalStartDate() {
- NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new RefEvalImplementation(new NumberEval(DATE_1902_09_26)), new NumberEval(0)}, ec);
- assertEquals(DATE_1902_09_30, result.getNumberValue());
+ ValueEval ve[] = {new RefEvalImplementation(new NumberEval(DATE_1902_09_26)), new NumberEval(0)};
+ NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec);
+ assertEquals(DATE_1902_09_30, result.getNumberValue(), 0);
}
+ @Test
public void testEOMonthBlankValueEval() {
NumberEval evaluate = (NumberEval) eOMonth.evaluate(new ValueEval[] {BlankEval.instance, new NumberEval(0)}, ec);
- assertEquals("Blank is handled as 0", DATE_1900_01_31, evaluate.getNumberValue());
+ assertEquals("Blank is handled as 0", DATE_1900_01_31, evaluate.getNumberValue(), 0);
}
+ @Test
public void testEOMonthBlankRefValueEval() {
- NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new RefEvalImplementation(BlankEval.instance), new NumberEval(1)}, ec);
- assertEquals("Blank is handled as 0",
- DATE_1900_02_28, result.getNumberValue());
+ ValueEval[] ve1 = {new RefEvalImplementation(BlankEval.instance), new NumberEval(1)};
+ NumberEval result = (NumberEval) eOMonth.evaluate(ve1, ec);
+ assertEquals("Blank is handled as 0", DATE_1900_02_28, result.getNumberValue(), 0);
- result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(1), new RefEvalImplementation(BlankEval.instance)}, ec);
- assertEquals("Blank is handled as 0",
- DATE_1900_01_31, result.getNumberValue());
+ ValueEval[] ve2 = {new NumberEval(1), new RefEvalImplementation(BlankEval.instance)};
+ result = (NumberEval) eOMonth.evaluate(ve2, ec);
+ assertEquals("Blank is handled as 0", DATE_1900_01_31, result.getNumberValue(), 0);
}
}
diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java b/src/testcases/org/apache/poi/ss/formula/functions/TestText.java index 9b330ca422..4249de677b 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestText.java @@ -17,21 +17,25 @@ package org.apache.poi.ss.formula.functions; +import static org.junit.Assert.assertEquals; + +import java.text.DateFormatSymbols; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; -import java.util.GregorianCalendar; -import java.util.Locale; +import java.util.TimeZone; -import junit.framework.TestCase; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.formula.eval.StringEval; +import org.apache.poi.ss.formula.eval.ValueEval; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; /** * Test case for TEXT() */ -public final class TestText extends TestCase { +public final class TestText { + @Test public void testTextWithStringFirstArg() { ValueEval strArg = new StringEval("abc"); ValueEval formatArg = new StringEval("abc"); @@ -40,13 +44,14 @@ public final class TestText extends TestCase { assertEquals(ErrorEval.VALUE_INVALID, result); } + @Test public void testTextWithDeciamlFormatSecondArg() { ValueEval numArg = new NumberEval(321321.321); ValueEval formatArg = new StringEval("#,###.00000"); ValueEval[] args = { numArg, formatArg }; ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - char groupSeparator = new DecimalFormatSymbols(Locale.getDefault()).getGroupingSeparator(); - char decimalSeparator = new DecimalFormatSymbols(Locale.getDefault()).getDecimalSeparator(); + char groupSeparator = new DecimalFormatSymbols(LocaleUtil.getUserLocale()).getGroupingSeparator(); + char decimalSeparator = new DecimalFormatSymbols(LocaleUtil.getUserLocale()).getDecimalSeparator(); ValueEval testResult = new StringEval("321" + groupSeparator + "321" + decimalSeparator + "32100"); assertEquals(testResult.toString(), result.toString()); numArg = new NumberEval(321.321); @@ -64,6 +69,7 @@ public final class TestText extends TestCase { assertEquals(testResult.toString(), result.toString()); } + @Test public void testTextWithFractionFormatSecondArg() { ValueEval numArg = new NumberEval(321.321); ValueEval formatArg = new StringEval("# #/#"); @@ -85,37 +91,47 @@ public final class TestText extends TestCase { assertEquals(testResult.toString(), result.toString()); } + @Test public void testTextWithDateFormatSecondArg() { - // Test with Java style M=Month - ValueEval numArg = new NumberEval(321.321); - ValueEval formatArg = new StringEval("dd:MM:yyyy hh:mm:ss"); - ValueEval[] args = { numArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - ValueEval testResult = new StringEval("16:11:1900 07:42:14"); - assertEquals(testResult.toString(), result.toString()); - - // Excel also supports "m before h is month" - formatArg = new StringEval("dd:mm:yyyy hh:mm:ss"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("16:11:1900 07:42:14"); - assertEquals(testResult.toString(), result.toString()); - - // this line is intended to compute how "November" would look like in the current locale - String november = new SimpleDateFormat("MMMM").format(new GregorianCalendar(2010,10,15).getTime()); - - // Again with Java style - formatArg = new StringEval("MMMM dd, yyyy"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval(november + " 16, 1900"); - assertEquals(testResult.toString(), result.toString()); - - // And Excel style - formatArg = new StringEval("mmmm dd, yyyy"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval(november + " 16, 1900"); - assertEquals(testResult.toString(), result.toString()); + TimeZone userTZ = LocaleUtil.getUserTimeZone(); + LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); + try { + // Test with Java style M=Month + ValueEval numArg = new NumberEval(321.321); + ValueEval formatArg = new StringEval("dd:MM:yyyy hh:mm:ss"); + ValueEval[] args = { numArg, formatArg }; + ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); + ValueEval testResult = new StringEval("16:11:1900 07:42:14"); + assertEquals(testResult.toString(), result.toString()); + + // Excel also supports "m before h is month" + formatArg = new StringEval("dd:mm:yyyy hh:mm:ss"); + args[1] = formatArg; + result = TextFunction.TEXT.evaluate(args, -1, (short)-1); + testResult = new StringEval("16:11:1900 07:42:14"); + assertEquals(testResult.toString(), result.toString()); + + // this line is intended to compute how "November" would look like in the current locale + // update: now the locale will be (if not set otherwise) always Locale.getDefault() (see LocaleUtil) + DateFormatSymbols dfs = DateFormatSymbols.getInstance(LocaleUtil.getUserLocale()); + SimpleDateFormat sdf = new SimpleDateFormat("MMMM", dfs); + String november = sdf.format(LocaleUtil.getLocaleCalendar(2015,10,1).getTime()); + + // Again with Java style + formatArg = new StringEval("MMMM dd, yyyy"); + args[1] = formatArg; + result = TextFunction.TEXT.evaluate(args, -1, (short)-1); + testResult = new StringEval(november + " 16, 1900"); + assertEquals(testResult.toString(), result.toString()); + + // And Excel style + formatArg = new StringEval("mmmm dd, yyyy"); + args[1] = formatArg; + result = TextFunction.TEXT.evaluate(args, -1, (short)-1); + testResult = new StringEval(november + " 16, 1900"); + assertEquals(testResult.toString(), result.toString()); + } finally { + LocaleUtil.setUserTimeZone(userTZ); + } } } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java index a1f89ff79b..7f12c136aa 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.functions; -import java.util.regex.Pattern; +import static org.junit.Assert.assertEquals; -import junit.framework.TestCase; +import java.util.regex.Pattern; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; @@ -28,13 +28,13 @@ import org.apache.poi.hssf.usermodel.HSSFDataFormatter; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.junit.Before; +import org.junit.Test; /** * Tests for {@link TimeFunc} - * - * @author @author Steven Butler (sebutler @ gmail dot com) */ -public final class TestTime extends TestCase { +public final class TestTime { private static final int SECONDS_PER_MINUTE = 60; private static final int SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE; @@ -44,7 +44,8 @@ public final class TestTime extends TestCase { private HSSFWorkbook wb; private HSSFDataFormatter form; private HSSFCellStyle style; - + + @Before public void setUp() { wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("new sheet"); @@ -58,11 +59,13 @@ public final class TestTime extends TestCase { evaluator = new HSSFFormulaEvaluator(wb); } + @Test public void testSomeArgumentsMissing() { confirm("00:00:00", "TIME(, 0, 0)"); confirm("12:00:00", "TIME(12, , )"); } + @Test public void testValid() { confirm("00:00:01", 0, 0, 1); confirm("00:01:00", 0, 1, 0); @@ -101,7 +104,6 @@ public final class TestTime extends TestCase { } private void confirm(String expectedTimeStr, String formulaText) { -// System.out.println("=" + formulaText); String[] parts = Pattern.compile(":").split(expectedTimeStr); int expH = Integer.parseInt(parts[0]); int expM = Integer.parseInt(parts[1]); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java index e54eef87cc..4d6b314973 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java @@ -17,23 +17,31 @@ package org.apache.poi.ss.usermodel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.IOException; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.SpreadsheetVersion; +import org.apache.poi.util.LocaleUtil; +import org.junit.Test; + +import junit.framework.AssertionFailedError; /** * Common superclass for testing implementations of * {@link org.apache.poi.ss.usermodel.Cell} */ -public abstract class BaseTestCell extends TestCase { +public abstract class BaseTestCell { protected final ITestDataProvider _testDataProvider; @@ -44,6 +52,7 @@ public abstract class BaseTestCell extends TestCase { _testDataProvider = testDataProvider; } + @Test public void testSetValues() { Workbook book = _testDataProvider.createWorkbook(); Sheet sheet = book.createSheet("test"); @@ -80,7 +89,7 @@ public abstract class BaseTestCell extends TestCase { assertProhibitedValueAccess(cell, Cell.CELL_TYPE_NUMERIC, Cell.CELL_TYPE_BOOLEAN, Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_ERROR); - Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT); + Calendar c = LocaleUtil.getLocaleCalendar(); c.setTimeInMillis(123456789); cell.setCellValue(c.getTime()); assertEquals(c.getTime().getTime(), cell.getDateCellValue().getTime()); @@ -132,6 +141,7 @@ public abstract class BaseTestCell extends TestCase { /** * test that Boolean and Error types (BoolErrRecord) are supported properly. */ + @Test public void testBoolErr() { Workbook wb = _testDataProvider.createWorkbook(); @@ -173,6 +183,7 @@ public abstract class BaseTestCell extends TestCase { /** * test that Cell Styles being applied to formulas remain intact */ + @Test public void testFormulaStyle() { Workbook wb = _testDataProvider.createWorkbook(); @@ -214,6 +225,7 @@ public abstract class BaseTestCell extends TestCase { } /**tests the toString() method of HSSFCell*/ + @Test public void testToString() { Workbook wb = _testDataProvider.createWorkbook(); Row r = wb.createSheet("Sheet1").createRow(0); @@ -245,6 +257,7 @@ public abstract class BaseTestCell extends TestCase { /** * Test that setting cached formula result keeps the cell type */ + @Test public void testSetFormulaValue() { Workbook wb = _testDataProvider.createWorkbook(); Sheet s = wb.createSheet(); @@ -278,7 +291,7 @@ public abstract class BaseTestCell extends TestCase { return _testDataProvider.createWorkbook().createSheet("Sheet1").createRow(0).createCell(0); } - + @Test public void testChangeTypeStringToBool() { Cell cell = createACell(); @@ -305,6 +318,7 @@ public abstract class BaseTestCell extends TestCase { assertEquals("FALSE", cell.getRichStringCellValue().getString()); } + @Test public void testChangeTypeBoolToString() { Cell cell = createACell(); @@ -321,6 +335,7 @@ public abstract class BaseTestCell extends TestCase { assertEquals("TRUE", cell.getRichStringCellValue().getString()); } + @Test public void testChangeTypeErrorToNumber() { Cell cell = createACell(); cell.setCellErrorValue((byte)ErrorConstants.ERROR_NAME); @@ -332,6 +347,7 @@ public abstract class BaseTestCell extends TestCase { assertEquals(2.5, cell.getNumericCellValue(), 0.0); } + @Test public void testChangeTypeErrorToBoolean() { Cell cell = createACell(); cell.setCellErrorValue((byte)ErrorConstants.ERROR_NAME); @@ -353,6 +369,7 @@ public abstract class BaseTestCell extends TestCase { * {@link FormulaEvaluator#evaluateInCell(Cell)} with a * string result type. */ + @Test public void testConvertStringFormulaCell() { Cell cellA1 = createACell(); cellA1.setCellFormula("\"abc\""); @@ -371,10 +388,12 @@ public abstract class BaseTestCell extends TestCase { } assertEquals("abc", cellA1.getStringCellValue()); } + /** * similar to {@link #testConvertStringFormulaCell()} but checks at a * lower level that {#link {@link Cell#setCellType(int)} works properly */ + @Test public void testSetTypeStringOnFormulaCell() { Cell cellA1 = createACell(); FormulaEvaluator fe = cellA1.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); @@ -418,6 +437,7 @@ public abstract class BaseTestCell extends TestCase { /** * Test for bug in convertCellValueToBoolean to make sure that formula results get converted */ + @Test public void testChangeTypeFormulaToBoolean() { Cell cell = createACell(); cell.setCellFormula("1=1"); @@ -433,6 +453,7 @@ public abstract class BaseTestCell extends TestCase { * Bug 40296: HSSFCell.setCellFormula throws * ClassCastException if cell is created using HSSFRow.createCell(short column, int type) */ + @Test public void test40296() { Workbook wb = _testDataProvider.createWorkbook(); Sheet workSheet = wb.createSheet("Sheet1"); @@ -470,6 +491,7 @@ public abstract class BaseTestCell extends TestCase { assertEquals("SUM(A1:B1)", cell.getCellFormula()); } + @Test public void testSetStringInFormulaCell_bug44606() { Workbook wb = _testDataProvider.createWorkbook(); Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); @@ -484,7 +506,8 @@ public abstract class BaseTestCell extends TestCase { /** * Make sure that cell.setCellType(Cell.CELL_TYPE_BLANK) preserves the cell style */ - public void testSetBlank_bug47028() { + @Test + public void testSetBlank_bug47028() { Workbook wb = _testDataProvider.createWorkbook(); CellStyle style = wb.createCellStyle(); Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); @@ -514,7 +537,8 @@ public abstract class BaseTestCell extends TestCase { * </li> * </ul> */ - public void testNanAndInfinity() { + @Test + public void testNanAndInfinity() { Workbook wb = _testDataProvider.createWorkbook(); Sheet workSheet = wb.createSheet("Sheet1"); Row row = workSheet.createRow(0); @@ -550,7 +574,8 @@ public abstract class BaseTestCell extends TestCase { assertEquals(ErrorConstants.ERROR_DIV_0, cell2.getErrorCellValue()); } - public void testDefaultStyleProperties() { + @Test + public void testDefaultStyleProperties() { Workbook wb = _testDataProvider.createWorkbook(); Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); @@ -584,7 +609,8 @@ public abstract class BaseTestCell extends TestCase { assertFalse(style2.getHidden()); } - public void testBug55658SetNumericValue(){ + @Test + public void testBug55658SetNumericValue(){ Workbook wb = _testDataProvider.createWorkbook(); Sheet sh = wb.createSheet(); Row row = sh.createRow(0); @@ -604,7 +630,8 @@ public abstract class BaseTestCell extends TestCase { assertEquals("24", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue()); } - public void testRemoveHyperlink(){ + @Test + public void testRemoveHyperlink(){ Workbook wb = _testDataProvider.createWorkbook(); Sheet sh = wb.createSheet("test"); Row row = sh.createRow(0); @@ -646,7 +673,8 @@ public abstract class BaseTestCell extends TestCase { * an problem that cell could not return error value form formula cell). * @throws IOException */ - public void testGetErrorCellValueFromFormulaCell() throws IOException { + @Test + public void testGetErrorCellValueFromFormulaCell() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); try { Sheet sheet = wb.createSheet(); @@ -660,7 +688,8 @@ public abstract class BaseTestCell extends TestCase { } } - public void testSetRemoveStyle() throws Exception { + @Test + public void testSetRemoveStyle() throws Exception { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); Row row = sheet.createRow(0); @@ -699,6 +728,7 @@ public abstract class BaseTestCell extends TestCase { wb.close(); } + @Test public void test57008() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); @@ -740,6 +770,7 @@ public abstract class BaseTestCell extends TestCase { * The maximum length of cell contents (text) is 32,767 characters. * @throws IOException */ + @Test public void testMaxTextLength() throws IOException{ Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java index b1aeb637c3..997d825edf 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java @@ -17,15 +17,20 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Calendar; +import java.util.Locale; import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.JvmBugs; +import org.apache.poi.util.LocaleUtil; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; -import java.util.Calendar; - /** * Common superclass for testing automatic sizing of sheet columns * @@ -35,12 +40,25 @@ public abstract class BaseTestSheetAutosizeColumn { private final ITestDataProvider _testDataProvider; + private static Locale userLocale; + + @BeforeClass + public static void initLocale() { + userLocale = LocaleUtil.getUserLocale(); + LocaleUtil.setUserLocale(Locale.ROOT); + } + + @AfterClass + public static void resetLocale() { + LocaleUtil.setUserLocale(userLocale); + } + protected BaseTestSheetAutosizeColumn(ITestDataProvider testDataProvider) { _testDataProvider = testDataProvider; } @Test - public void numericCells(){ + public void numericCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); DataFormat df = workbook.getCreationHelper().createDataFormat(); @@ -77,10 +95,12 @@ public abstract class BaseTestSheetAutosizeColumn { assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // columns 1, 2 and 3 should have the same width assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(3)); // columns 1, 2 and 3 should have the same width assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(5)); // 10.0000 and '10.0000' + + workbook.close(); } @Test - public void booleanCells(){ + public void booleanCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); @@ -106,10 +126,12 @@ public abstract class BaseTestSheetAutosizeColumn { assertTrue(sheet.getColumnWidth(1) > sheet.getColumnWidth(0)); // 'true' is wider than '0' assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // columns 1, 2 and 3 should have the same width assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(3)); // columns 1, 2 and 3 should have the same width + + workbook.close(); } @Test - public void dateCells(){ + public void dateCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); @@ -124,8 +146,7 @@ public abstract class BaseTestSheetAutosizeColumn { CellStyle style5 = workbook.createCellStyle(); //rotated text style5.setDataFormat(df.getFormat("mmm/dd/yyyy")); - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 0, 1); // Jan 1 2010 + Calendar calendar = LocaleUtil.getLocaleCalendar(2010, 0, 1); // Jan 1 2010 Row row = sheet.createRow(0); row.createCell(0).setCellValue(DateUtil.getJavaDate(0)); //default date @@ -172,10 +193,12 @@ public abstract class BaseTestSheetAutosizeColumn { assertTrue(sheet.getColumnWidth(5) > sheet.getColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm' assertEquals(sheet.getColumnWidth(6), sheet.getColumnWidth(5)); // date formatted as 'mmm/dd/yyyy' assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(7)); // date formula formatted as 'mmm' + + workbook.close(); } @Test - public void stringCells(){ + public void stringCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); @@ -205,10 +228,12 @@ public abstract class BaseTestSheetAutosizeColumn { assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); boolean ignoreFontSizeX2 = JvmBugs.hasLineBreakMeasurerBug(); assertTrue(ignoreFontSizeX2 || sheet.getColumnWidth(5) > sheet.getColumnWidth(4)); //larger font results in a wider column width + + workbook.close(); } @Test - public void rotatedText(){ + public void rotatedText() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); @@ -230,10 +255,12 @@ public abstract class BaseTestSheetAutosizeColumn { int w1 = sheet.getColumnWidth(1); assertTrue(w0*5 < w1); // rotated text occupies at least five times less horizontal space than normal text + + workbook.close(); } @Test - public void mergedCells(){ + public void mergedCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); @@ -251,6 +278,8 @@ public abstract class BaseTestSheetAutosizeColumn { sheet.autoSizeColumn(0, true); assertTrue(sheet.getColumnWidth(0) > defaulWidth); + + workbook.close(); } @@ -293,6 +322,8 @@ public abstract class BaseTestSheetAutosizeColumn { Row r60708 = sheet.createRow(60708); r60708.createCell(0).setCellValue("Near the end"); sheet.autoSizeColumn(0); + + workbook.close(); } // TODO should we have this stuff in the FormulaEvaluator? diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java b/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java index 08f21a5900..1251f1e8b3 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java +++ b/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java @@ -21,16 +21,22 @@ package org.apache.poi.ss.usermodel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.IOException; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; -import junit.framework.TestCase; - import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.TestHSSFDataFormatter; +import org.apache.poi.util.LocaleUtil; +import org.junit.Ignore; +import org.junit.Test; /** * Tests of {@link DataFormatter} @@ -38,13 +44,14 @@ import org.apache.poi.hssf.usermodel.TestHSSFDataFormatter; * See {@link TestHSSFDataFormatter} too for * more tests. */ -public class TestDataFormatter extends TestCase { +public class TestDataFormatter { private static final double _15_MINUTES = 0.041666667; /** * Test that we use the specified locale when deciding * how to format normal numbers */ + @Test public void testLocale() { DataFormatter dfUS = new DataFormatter(Locale.US); DataFormatter dfFR = new DataFormatter(Locale.FRENCH); @@ -61,6 +68,7 @@ public class TestDataFormatter extends TestCase { * a specific locale, but we should format things as if * the locale (eg '[$-1010409]') isn't there */ + @Test public void testLocaleBasedFormats() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -78,6 +86,7 @@ public class TestDataFormatter extends TestCase { * Ensure that colours get correctly * zapped from within the format strings */ + @Test public void testColours() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -105,6 +114,7 @@ public class TestDataFormatter extends TestCase { assertEquals("[ab]12.34[x]", dfUS.formatRawCellContents(12.343, -1, "[ab]##.##[x]")); } + @Test public void testColoursAndBrackets() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -149,6 +159,7 @@ public class TestDataFormatter extends TestCase { * and Excel differ, and workarounds are not * yet in place for all of these */ + @Test public void testNegativeZero() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -193,6 +204,7 @@ public class TestDataFormatter extends TestCase { * Test that we correctly handle fractions in the * format string, eg # #/# */ + @Test public void testFractions() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -262,6 +274,7 @@ public class TestDataFormatter extends TestCase { * and *x (fill to the column width with "x"s) are * correctly ignored by us. */ + @Test public void testPaddingSpaces() { DataFormatter dfUS = new DataFormatter(Locale.US); assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##_ ")); @@ -278,6 +291,7 @@ public class TestDataFormatter extends TestCase { /** * DataFormatter is the CSV mode preserves spaces */ + @Test public void testPaddingSpacesCSV() { DataFormatter dfUS = new DataFormatter(Locale.US, true); assertEquals("12.34 ", dfUS.formatRawCellContents(12.343, -1, "##.##_ ")); @@ -311,12 +325,11 @@ public class TestDataFormatter extends TestCase { * Test that the special Excel month format MMMMM * gets turned into the first letter of the month */ + @Test public void testMMMMM() { DataFormatter dfUS = new DataFormatter(Locale.US); - Calendar c = Calendar.getInstance(); - c.set(Calendar.MILLISECOND, 0); - c.set(2010, 5, 1, 2, 0, 0); + Calendar c = LocaleUtil.getLocaleCalendar(2010, 5, 1, 2, 0, 0); assertEquals("2010-J-1 2:00:00", dfUS.formatRawCellContents( DateUtil.getExcelDate(c, false), -1, "YYYY-MMMMM-D h:mm:ss" @@ -326,6 +339,7 @@ public class TestDataFormatter extends TestCase { /** * Tests that we do AM/PM handling properly */ + @Test public void testAMPM() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -343,6 +357,7 @@ public class TestDataFormatter extends TestCase { * Test that we can handle elapsed time, * eg formatting 1 day 4 hours as 28 hours */ + @Test public void testElapsedTime() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -447,6 +462,7 @@ public class TestDataFormatter extends TestCase { } } + @Test public void testDateWindowing() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -455,6 +471,7 @@ public class TestDataFormatter extends TestCase { assertEquals("1904-01-01 00:00:00", dfUS.formatRawCellContents(0.0, -1, "yyyy-mm-dd hh:mm:ss", true)); } + @Test public void testScientificNotation() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -463,6 +480,7 @@ public class TestDataFormatter extends TestCase { assertEquals("0.00E+00", dfUS.formatRawCellContents(0.0, -1, "0.00E+00")); } + @Test public void testInvalidDate() { DataFormatter df1 = new DataFormatter(Locale.US); assertEquals("-1.0", df1.formatRawCellContents(-1, -1, "mm/dd/yyyy")); @@ -472,6 +490,7 @@ public class TestDataFormatter extends TestCase { df2.formatRawCellContents(-1, -1, "mm/dd/yyyy")); } + @Test public void testEscapes() { DataFormatter dfUS = new DataFormatter(Locale.US); @@ -485,6 +504,7 @@ public class TestDataFormatter extends TestCase { assertEquals("1901/01/01", dfUS.formatRawCellContents(367.0, -1, "yyyy\\/mm\\/dd")); } + @Test public void testOther() { DataFormatter dfUS = new DataFormatter(Locale.US, true); @@ -494,6 +514,7 @@ public class TestDataFormatter extends TestCase { assertEquals(" $- ", dfUS.formatRawCellContents(0.0, -1, "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-")); } + @Test public void testErrors() throws IOException { DataFormatter dfUS = new DataFormatter(Locale.US, true); @@ -519,6 +540,7 @@ public class TestDataFormatter extends TestCase { * the start of a format string to format it differently, we * should at least handle it as it if wasn't there */ + @Test public void testDatesWithLocales() { DataFormatter dfUS = new DataFormatter(Locale.US, true); @@ -543,7 +565,9 @@ public class TestDataFormatter extends TestCase { /** * TODO Fix these so that they work */ - public void DISABLEDtestCustomFormats() { + @Test + @Ignore + public void testCustomFormats() { DataFormatter dfUS = new DataFormatter(Locale.US, true); String fmt; @@ -560,6 +584,7 @@ public class TestDataFormatter extends TestCase { /** * ExcelStyleDateFormatter should work for Milliseconds too */ + @Test public void testExcelStyleDateFormatterStringOnMillis() { // Test directly with the .000 style DateFormat formatter1 = new ExcelStyleDateFormatter("ss.000"); @@ -589,7 +614,8 @@ public class TestDataFormatter extends TestCase { assertEquals("01.010", dfUS.formatRawCellContents(0.0000116898, -1, "ss.000")); } - public void testBug54786() { + @Test + public void testBug54786() { DataFormatter formatter = new DataFormatter(); String format = "[h]\"\"h\"\" m\"\"m\"\""; assertTrue(DateUtil.isADateFormat(-1,format)); @@ -613,7 +639,8 @@ public class TestDataFormatter extends TestCase { } } - public void testIsADateFormat() { + @Test + public void testIsADateFormat() { // first check some cases that should not be a date, also call multiple times to ensure the cache is used assertFalse(DateUtil.isADateFormat(-1, null)); assertFalse(DateUtil.isADateFormat(-1, null)); diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java b/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java index 870cd9cb35..3f0ef4b7c1 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java +++ b/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java @@ -23,6 +23,7 @@ import java.util.Calendar; import java.util.Date; import java.util.TimeZone; +import org.apache.poi.util.LocaleUtil; import org.junit.Test; public class TestDateUtil { @@ -30,7 +31,7 @@ public class TestDateUtil { @Test public void getJavaDate_InvalidValue() { double dateValue = -1; - TimeZone tz = TimeZone.getDefault(); + TimeZone tz = LocaleUtil.getUserTimeZone(); boolean use1904windowing = false; boolean roundSeconds = false; @@ -44,13 +45,11 @@ public class TestDateUtil { @Test public void getJavaDate_ValidValue() { double dateValue = 0; - TimeZone tz = TimeZone.getDefault(); + TimeZone tz = LocaleUtil.getUserTimeZone(); boolean use1904windowing = false; boolean roundSeconds = false; - Calendar calendar = Calendar.getInstance(tz); - calendar.set(1900, 0, 0, 0, 0, 0); - calendar.set(Calendar.MILLISECOND, 0); + Calendar calendar = LocaleUtil.getLocaleCalendar(1900, 0, 0); Date date = calendar.getTime(); assertEquals(date, DateUtil.getJavaDate(dateValue)); @@ -63,7 +62,7 @@ public class TestDateUtil { @Test public void getJavaCalendar_InvalidValue() { double dateValue = -1; - TimeZone tz = TimeZone.getDefault(); + TimeZone tz = LocaleUtil.getUserTimeZone(); boolean use1904windowing = false; boolean roundSeconds = false; @@ -76,17 +75,21 @@ public class TestDateUtil { @Test public void getJavaCalendar_ValidValue() { double dateValue = 0; - TimeZone tz = TimeZone.getDefault(); + TimeZone tz = LocaleUtil.getUserTimeZone(); boolean use1904windowing = false; boolean roundSeconds = false; - Calendar calendar = Calendar.getInstance(tz); - calendar.set(1900, 0, 0, 0, 0, 0); - calendar.set(Calendar.MILLISECOND, 0); - - assertEquals(calendar, DateUtil.getJavaCalendar(dateValue)); - assertEquals(calendar, DateUtil.getJavaCalendar(dateValue, use1904windowing)); - assertEquals(calendar, DateUtil.getJavaCalendar(dateValue, use1904windowing, tz)); - assertEquals(calendar, DateUtil.getJavaCalendar(dateValue, use1904windowing, tz, roundSeconds)); + Calendar expCal = LocaleUtil.getLocaleCalendar(1900, 0, 0); + + Calendar actCal[] = { + DateUtil.getJavaCalendar(dateValue), + DateUtil.getJavaCalendar(dateValue, use1904windowing), + DateUtil.getJavaCalendar(dateValue, use1904windowing, tz), + DateUtil.getJavaCalendar(dateValue, use1904windowing, tz, roundSeconds) + }; + assertEquals(expCal, actCal[0]); + assertEquals(expCal, actCal[1]); + assertEquals(expCal, actCal[2]); + assertEquals(expCal, actCal[3]); } } diff --git a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java b/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java index 418070f16a..2b6e6e3127 100644 --- a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java +++ b/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java @@ -69,7 +69,7 @@ public final class TestDateFormatConverter extends TestCase { Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(locale.toString()); - row.createCell(1).setCellValue(locale.getDisplayName()); + row.createCell(1).setCellValue(locale.getDisplayName(Locale.ROOT)); DateFormat dateFormat; if( dates ) { diff --git a/src/testcases/org/apache/poi/util/TestHexDump.java b/src/testcases/org/apache/poi/util/TestHexDump.java index 11cd4cb9a7..f6e149e75e 100644 --- a/src/testcases/org/apache/poi/util/TestHexDump.java +++ b/src/testcases/org/apache/poi/util/TestHexDump.java @@ -134,7 +134,7 @@ public final class TestHexDump { obj[17] = chrs.toString(); format.append("%18$s"+HexDump.EOL); - String str = String.format(format.toString(), obj); + String str = String.format(LocaleUtil.getUserLocale(), format.toString(), obj); strExp.append(str); } byte bytesExp[] = strExp.toString().getBytes(HexDump.UTF8); diff --git a/src/testcases/org/apache/poi/util/TestStringUtil.java b/src/testcases/org/apache/poi/util/TestStringUtil.java index 04c03d93e8..fcef5bd17a 100644 --- a/src/testcases/org/apache/poi/util/TestStringUtil.java +++ b/src/testcases/org/apache/poi/util/TestStringUtil.java @@ -144,7 +144,7 @@ public final class TestStringUtil extends TestCase { } private static String fmt(double num, int minIntDigits, int maxFracDigitis) { - NumberFormat nf = NumberFormat.getInstance(); + NumberFormat nf = NumberFormat.getInstance(LocaleUtil.getUserLocale()); if (minIntDigits != -1) { nf.setMinimumIntegerDigits(minIntDigits); |