test_class_signature
stringlengths
21
105
function
stringlengths
268
12.2k
prompt_complete_with_comment
stringlengths
1.66k
9.91k
location
stringlengths
46
115
be_test_import_context
stringlengths
44
2.77k
be_test_class_function_signature_context
stringlengths
60
22.9k
end
int64
44
7.03k
function_name
stringlengths
8
51
prompt_chat_with_comment
stringlengths
1.56k
9.41k
start
int64
28
7.02k
prompt_complete
stringlengths
1.75k
10.3k
comment
stringlengths
128
2.81k
bug_id
int64
1
112
be_test_class_long_name
stringlengths
24
92
source_dir
stringclasses
4 values
prompt_chat
stringlengths
1.66k
9.83k
be_test_class_signature
stringlengths
17
234
test_import_context
stringlengths
39
2.03k
test_class_function_signature_context
stringlengths
169
69.8k
task_id
stringlengths
64
64
testmethods
sequence
be_test_class_field_context
stringlengths
0
8.55k
function_signature
stringlengths
23
151
test_class_field_context
stringlengths
0
4.05k
project
stringclasses
12 values
source
stringlengths
3.4k
445k
indent
stringclasses
2 values
classmethods
list
public class LoopingIteratorTest extends TestCase
public void testReset() throws Exception { final List<String> list = Arrays.asList("a", "b", "c"); final LoopingIterator<String> loop = new LoopingIterator<String>(list); assertEquals("a", loop.next()); assertEquals("b", loop.next()); loop.reset(); assertEquals("a", loop.next()); loop.reset(); assertEquals("a", loop.next()); assertEquals("b", loop.next()); assertEquals("c", loop.next()); loop.reset(); assertEquals("a", loop.next()); assertEquals("b", loop.next()); assertEquals("c", loop.next()); }
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Collection; // import java.util.Iterator; // import java.util.NoSuchElementException; // import org.apache.commons.collections4.ResettableIterator; // // // // public class LoopingIterator<E> implements ResettableIterator<E> { // private final Collection<? extends E> collection; // private Iterator<? extends E> iterator; // // public LoopingIterator(final Collection<? extends E> coll); // @Override // public boolean hasNext(); // @Override // public E next(); // @Override // public void remove(); // @Override // public void reset(); // public int size(); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.iterators; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.List; // import java.util.NoSuchElementException; // import junit.framework.TestCase; // // // // public class LoopingIteratorTest extends TestCase { // // // public void testConstructorEx() throws Exception; // public void testLooping0() throws Exception; // public void testLooping1() throws Exception; // public void testLooping2() throws Exception; // public void testLooping3() throws Exception; // public void testRemoving1() throws Exception; // public void testReset() throws Exception; // public void testSize() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testReset` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */
src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.java
package org.apache.commons.collections4.iterators; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableIterator;
public LoopingIterator(final Collection<? extends E> coll); @Override public boolean hasNext(); @Override public E next(); @Override public void remove(); @Override public void reset(); public int size();
171
testReset
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableIterator; public class LoopingIterator<E> implements ResettableIterator<E> { private final Collection<? extends E> collection; private Iterator<? extends E> iterator; public LoopingIterator(final Collection<? extends E> coll); @Override public boolean hasNext(); @Override public E next(); @Override public void remove(); @Override public void reset(); public int size(); } // Abstract Java Test Class package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; public class LoopingIteratorTest extends TestCase { public void testConstructorEx() throws Exception; public void testLooping0() throws Exception; public void testLooping1() throws Exception; public void testLooping2() throws Exception; public void testLooping3() throws Exception; public void testRemoving1() throws Exception; public void testReset() throws Exception; public void testSize() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testReset` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */
155
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Collection; // import java.util.Iterator; // import java.util.NoSuchElementException; // import org.apache.commons.collections4.ResettableIterator; // // // // public class LoopingIterator<E> implements ResettableIterator<E> { // private final Collection<? extends E> collection; // private Iterator<? extends E> iterator; // // public LoopingIterator(final Collection<? extends E> coll); // @Override // public boolean hasNext(); // @Override // public E next(); // @Override // public void remove(); // @Override // public void reset(); // public int size(); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.iterators; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.List; // import java.util.NoSuchElementException; // import junit.framework.TestCase; // // // // public class LoopingIteratorTest extends TestCase { // // // public void testConstructorEx() throws Exception; // public void testLooping0() throws Exception; // public void testLooping1() throws Exception; // public void testLooping2() throws Exception; // public void testLooping3() throws Exception; // public void testRemoving1() throws Exception; // public void testReset() throws Exception; // public void testSize() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testReset` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testReset() throws Exception {
/** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */
28
org.apache.commons.collections4.iterators.LoopingIterator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableIterator; public class LoopingIterator<E> implements ResettableIterator<E> { private final Collection<? extends E> collection; private Iterator<? extends E> iterator; public LoopingIterator(final Collection<? extends E> coll); @Override public boolean hasNext(); @Override public E next(); @Override public void remove(); @Override public void reset(); public int size(); } // Abstract Java Test Class package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; public class LoopingIteratorTest extends TestCase { public void testConstructorEx() throws Exception; public void testLooping0() throws Exception; public void testLooping1() throws Exception; public void testLooping2() throws Exception; public void testLooping3() throws Exception; public void testRemoving1() throws Exception; public void testReset() throws Exception; public void testSize() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testReset` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testReset() throws Exception { ```
public class LoopingIterator<E> implements ResettableIterator<E>
package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase;
public void testConstructorEx() throws Exception; public void testLooping0() throws Exception; public void testLooping1() throws Exception; public void testLooping2() throws Exception; public void testLooping3() throws Exception; public void testRemoving1() throws Exception; public void testReset() throws Exception; public void testSize() throws Exception;
bd971158a3c3a231b5a2750230b6c34685cd069736717ffde95194dd28c67040
[ "org.apache.commons.collections4.iterators.LoopingIteratorTest::testReset" ]
private final Collection<? extends E> collection; private Iterator<? extends E> iterator;
public void testReset() throws Exception
Collections
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; /** * Tests the LoopingIterator class. * * @version $Id$ */ public class LoopingIteratorTest extends TestCase { /** * Tests constructor exception. */ public void testConstructorEx() throws Exception { try { new LoopingIterator<Object>(null); fail(); } catch (final NullPointerException ex) { } } /** * Tests whether an empty looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping0() throws Exception { final List<Object> list = new ArrayList<Object>(); final LoopingIterator<Object> loop = new LoopingIterator<Object>(list); assertTrue("hasNext should return false", !loop.hasNext()); try { loop.next(); fail("NoSuchElementException was not thrown during next() call."); } catch (final NoSuchElementException ex) { } } /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping1() throws Exception { final List<String> list = Arrays.asList("a"); final LoopingIterator<String> loop = new LoopingIterator<String>(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); } /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping2() throws Exception { final List<String> list = Arrays.asList("a", "b"); final LoopingIterator<String> loop = new LoopingIterator<String>(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("b", loop.next()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); } /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping3() throws Exception { final List<String> list = Arrays.asList("a", "b", "c"); final LoopingIterator<String> loop = new LoopingIterator<String>(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("b", loop.next()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("c", loop.next()); assertTrue("4th hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); } /** * Tests the remove() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testRemoving1() throws Exception { final List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c")); final LoopingIterator<String> loop = new LoopingIterator<String>(list); assertEquals("list should have 3 elements.", 3, list.size()); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); loop.remove(); // removes a assertEquals("list should have 2 elements.", 2, list.size()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("b", loop.next()); loop.remove(); // removes b assertEquals("list should have 1 elements.", 1, list.size()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("c", loop.next()); loop.remove(); // removes c assertEquals("list should have 0 elements.", 0, list.size()); assertFalse("4th hasNext should return false", loop.hasNext()); try { loop.next(); fail("Expected NoSuchElementException to be thrown."); } catch (final NoSuchElementException ex) { } } /** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testReset() throws Exception { final List<String> list = Arrays.asList("a", "b", "c"); final LoopingIterator<String> loop = new LoopingIterator<String>(list); assertEquals("a", loop.next()); assertEquals("b", loop.next()); loop.reset(); assertEquals("a", loop.next()); loop.reset(); assertEquals("a", loop.next()); assertEquals("b", loop.next()); assertEquals("c", loop.next()); loop.reset(); assertEquals("a", loop.next()); assertEquals("b", loop.next()); assertEquals("c", loop.next()); } /** * Tests the size() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testSize() throws Exception { final List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c")); final LoopingIterator<String> loop = new LoopingIterator<String>(list); assertEquals(3, loop.size()); loop.next(); loop.next(); assertEquals(3, loop.size()); loop.reset(); assertEquals(3, loop.size()); loop.next(); loop.remove(); assertEquals(2, loop.size()); } }
[ { "be_test_class_file": "org/apache/commons/collections4/iterators/LoopingIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.LoopingIterator", "be_test_function_name": "next", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "86", "87", "89", "90", "92" ], "method_line_rate": 0.6 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/LoopingIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.LoopingIterator", "be_test_function_name": "reset", "be_test_function_signature": "()V", "line_numbers": [ "117", "118" ], "method_line_rate": 1 } ]
@SuppressWarnings("resource") public class JsonParserTest extends BaseTest
public void testKeywords() throws Exception { final String DOC = "{\n" +"\"key1\" : null,\n" +"\"key2\" : true,\n" +"\"key3\" : false,\n" +"\"key4\" : [ false, null, true ]\n" +"}" ; JsonParser p = createParserUsingStream(JSON_FACTORY, DOC, "UTF-8"); _testKeywords(p, true); p.close(); p = createParserUsingReader(JSON_FACTORY, DOC); _testKeywords(p, true); p.close(); p = createParserForDataInput(JSON_FACTORY, new MockDataInput(DOC)); _testKeywords(p, false); p.close(); }
// public abstract Version version(); // @Override // public abstract void close() throws IOException; // public abstract boolean isClosed(); // public abstract JsonStreamContext getParsingContext(); // public abstract JsonLocation getTokenLocation(); // public abstract JsonLocation getCurrentLocation(); // public int releaseBuffered(OutputStream out) throws IOException; // public int releaseBuffered(Writer w) throws IOException; // public JsonParser enable(Feature f); // public JsonParser disable(Feature f); // public JsonParser configure(Feature f, boolean state); // public boolean isEnabled(Feature f); // public int getFeatureMask(); // @Deprecated // public JsonParser setFeatureMask(int mask); // public JsonParser overrideStdFeatures(int values, int mask); // public int getFormatFeatures(); // public JsonParser overrideFormatFeatures(int values, int mask); // public abstract JsonToken nextToken() throws IOException; // public abstract JsonToken nextValue() throws IOException; // public boolean nextFieldName(SerializableString str) throws IOException; // public String nextFieldName() throws IOException; // public String nextTextValue() throws IOException; // public int nextIntValue(int defaultValue) throws IOException; // public long nextLongValue(long defaultValue) throws IOException; // public Boolean nextBooleanValue() throws IOException; // public abstract JsonParser skipChildren() throws IOException; // public void finishToken() throws IOException; // public JsonToken currentToken(); // public int currentTokenId(); // public abstract JsonToken getCurrentToken(); // public abstract int getCurrentTokenId(); // public abstract boolean hasCurrentToken(); // public abstract boolean hasTokenId(int id); // public abstract boolean hasToken(JsonToken t); // public boolean isExpectedStartArrayToken(); // public boolean isExpectedStartObjectToken(); // public boolean isNaN() throws IOException; // public abstract void clearCurrentToken(); // public abstract JsonToken getLastClearedToken(); // public abstract void overrideCurrentName(String name); // public abstract String getCurrentName() throws IOException; // public String currentName() throws IOException; // public abstract String getText() throws IOException; // public int getText(Writer writer) throws IOException, UnsupportedOperationException; // public abstract char[] getTextCharacters() throws IOException; // public abstract int getTextLength() throws IOException; // public abstract int getTextOffset() throws IOException; // public abstract boolean hasTextCharacters(); // public abstract Number getNumberValue() throws IOException; // public abstract NumberType getNumberType() throws IOException; // public byte getByteValue() throws IOException; // public short getShortValue() throws IOException; // public abstract int getIntValue() throws IOException; // public abstract long getLongValue() throws IOException; // public abstract BigInteger getBigIntegerValue() throws IOException; // public abstract float getFloatValue() throws IOException; // public abstract double getDoubleValue() throws IOException; // public abstract BigDecimal getDecimalValue() throws IOException; // public boolean getBooleanValue() throws IOException; // public Object getEmbeddedObject() throws IOException; // public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException; // public byte[] getBinaryValue() throws IOException; // public int readBinaryValue(OutputStream out) throws IOException; // public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException; // public int getValueAsInt() throws IOException; // public int getValueAsInt(int def) throws IOException; // public long getValueAsLong() throws IOException; // public long getValueAsLong(long def) throws IOException; // public double getValueAsDouble() throws IOException; // public double getValueAsDouble(double def) throws IOException; // public boolean getValueAsBoolean() throws IOException; // public boolean getValueAsBoolean(boolean def) throws IOException; // public String getValueAsString() throws IOException; // public abstract String getValueAsString(String def) throws IOException; // public boolean canReadObjectId(); // public boolean canReadTypeId(); // public Object getObjectId() throws IOException; // public Object getTypeId() throws IOException; // public <T> T readValueAs(Class<T> valueType) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException; // public <T> Iterator<T> readValuesAs(Class<T> valueType) throws IOException; // public <T> Iterator<T> readValuesAs(TypeReference<T> valueTypeRef) throws IOException; // @SuppressWarnings("unchecked") // public <T extends TreeNode> T readValueAsTree() throws IOException; // protected ObjectCodec _codec(); // protected JsonParseException _constructError(String msg); // protected void _reportUnsupportedOperation(); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.core.read; // // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.testsupport.MockDataInput; // import com.fasterxml.jackson.core.util.JsonParserDelegate; // import java.io.*; // import java.net.URL; // import java.util.*; // // // // @SuppressWarnings("resource") // public class JsonParserTest extends BaseTest // { // // // public void testConfig() throws Exception; // public void testInterningWithStreams() throws Exception; // public void testInterningWithReaders() throws Exception; // private void _testIntern(boolean useStream, boolean enableIntern, String expName) throws IOException; // public void testSpecExampleSkipping() throws Exception; // public void testSpecExampleFully() throws Exception; // public void testKeywords() throws Exception; // private void _testKeywords(JsonParser p, boolean checkColumn) throws Exception; // public void testSkipping() throws Exception; // private void _testSkipping(int mode) throws Exception; // public void testNameEscaping() throws IOException; // private void _testNameEscaping(int mode) throws IOException; // public void testLongText() throws Exception; // private void _testLongText(int LEN) throws Exception; // public void testBytesAsSource() throws Exception; // public void testUtf8BOMHandling() throws Exception; // public void testSpacesInURL() throws Exception; // public void testHandlingOfInvalidSpaceByteStream() throws Exception; // public void testHandlingOfInvalidSpaceChars() throws Exception; // public void testHandlingOfInvalidSpaceDataInput() throws Exception; // private void _testHandlingOfInvalidSpace(int mode) throws Exception; // private void _testHandlingOfInvalidSpaceFromResource(boolean useStream) throws Exception; // public void testGetValueAsTextBytes() throws Exception; // public void testGetValueAsTextDataInput() throws Exception; // public void testGetValueAsTextChars() throws Exception; // private void _testGetValueAsText(int mode, boolean delegate) throws Exception; // public void testGetTextViaWriter() throws Exception; // private void _testGetTextViaWriter(int mode) throws Exception; // public void testLongerReadText() throws Exception; // private void _testLongerReadText(int mode) throws Exception; // private void _doTestSpec(boolean verify) throws IOException; // } // You are a professional Java test case writer, please create a test case named `testKeywords` for the `JsonParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Unit test that verifies that 3 basic keywords (null, true, false) * are properly parsed in various contexts. */
src/test/java/com/fasterxml/jackson/core/read/JsonParserTest.java
package com.fasterxml.jackson.core; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Iterator; import com.fasterxml.jackson.core.async.NonBlockingInputFeeder; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.util.RequestPayload;
protected JsonParser(); protected JsonParser(int features); public abstract ObjectCodec getCodec(); public abstract void setCodec(ObjectCodec c); public Object getInputSource(); public Object getCurrentValue(); public void setCurrentValue(Object v); public void setRequestPayloadOnError(RequestPayload payload); public void setRequestPayloadOnError(byte[] payload, String charset); public void setRequestPayloadOnError(String payload); public void setSchema(FormatSchema schema); public FormatSchema getSchema(); public boolean canUseSchema(FormatSchema schema); public boolean requiresCustomCodec(); public boolean canParseAsync(); public NonBlockingInputFeeder getNonBlockingInputFeeder(); @Override public abstract Version version(); @Override public abstract void close() throws IOException; public abstract boolean isClosed(); public abstract JsonStreamContext getParsingContext(); public abstract JsonLocation getTokenLocation(); public abstract JsonLocation getCurrentLocation(); public int releaseBuffered(OutputStream out) throws IOException; public int releaseBuffered(Writer w) throws IOException; public JsonParser enable(Feature f); public JsonParser disable(Feature f); public JsonParser configure(Feature f, boolean state); public boolean isEnabled(Feature f); public int getFeatureMask(); @Deprecated public JsonParser setFeatureMask(int mask); public JsonParser overrideStdFeatures(int values, int mask); public int getFormatFeatures(); public JsonParser overrideFormatFeatures(int values, int mask); public abstract JsonToken nextToken() throws IOException; public abstract JsonToken nextValue() throws IOException; public boolean nextFieldName(SerializableString str) throws IOException; public String nextFieldName() throws IOException; public String nextTextValue() throws IOException; public int nextIntValue(int defaultValue) throws IOException; public long nextLongValue(long defaultValue) throws IOException; public Boolean nextBooleanValue() throws IOException; public abstract JsonParser skipChildren() throws IOException; public void finishToken() throws IOException; public JsonToken currentToken(); public int currentTokenId(); public abstract JsonToken getCurrentToken(); public abstract int getCurrentTokenId(); public abstract boolean hasCurrentToken(); public abstract boolean hasTokenId(int id); public abstract boolean hasToken(JsonToken t); public boolean isExpectedStartArrayToken(); public boolean isExpectedStartObjectToken(); public boolean isNaN() throws IOException; public abstract void clearCurrentToken(); public abstract JsonToken getLastClearedToken(); public abstract void overrideCurrentName(String name); public abstract String getCurrentName() throws IOException; public String currentName() throws IOException; public abstract String getText() throws IOException; public int getText(Writer writer) throws IOException, UnsupportedOperationException; public abstract char[] getTextCharacters() throws IOException; public abstract int getTextLength() throws IOException; public abstract int getTextOffset() throws IOException; public abstract boolean hasTextCharacters(); public abstract Number getNumberValue() throws IOException; public abstract NumberType getNumberType() throws IOException; public byte getByteValue() throws IOException; public short getShortValue() throws IOException; public abstract int getIntValue() throws IOException; public abstract long getLongValue() throws IOException; public abstract BigInteger getBigIntegerValue() throws IOException; public abstract float getFloatValue() throws IOException; public abstract double getDoubleValue() throws IOException; public abstract BigDecimal getDecimalValue() throws IOException; public boolean getBooleanValue() throws IOException; public Object getEmbeddedObject() throws IOException; public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException; public byte[] getBinaryValue() throws IOException; public int readBinaryValue(OutputStream out) throws IOException; public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException; public int getValueAsInt() throws IOException; public int getValueAsInt(int def) throws IOException; public long getValueAsLong() throws IOException; public long getValueAsLong(long def) throws IOException; public double getValueAsDouble() throws IOException; public double getValueAsDouble(double def) throws IOException; public boolean getValueAsBoolean() throws IOException; public boolean getValueAsBoolean(boolean def) throws IOException; public String getValueAsString() throws IOException; public abstract String getValueAsString(String def) throws IOException; public boolean canReadObjectId(); public boolean canReadTypeId(); public Object getObjectId() throws IOException; public Object getTypeId() throws IOException; public <T> T readValueAs(Class<T> valueType) throws IOException; @SuppressWarnings("unchecked") public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException; public <T> Iterator<T> readValuesAs(Class<T> valueType) throws IOException; public <T> Iterator<T> readValuesAs(TypeReference<T> valueTypeRef) throws IOException; @SuppressWarnings("unchecked") public <T extends TreeNode> T readValueAsTree() throws IOException; protected ObjectCodec _codec(); protected JsonParseException _constructError(String msg); protected void _reportUnsupportedOperation();
112
testKeywords
```java public abstract Version version(); @Override public abstract void close() throws IOException; public abstract boolean isClosed(); public abstract JsonStreamContext getParsingContext(); public abstract JsonLocation getTokenLocation(); public abstract JsonLocation getCurrentLocation(); public int releaseBuffered(OutputStream out) throws IOException; public int releaseBuffered(Writer w) throws IOException; public JsonParser enable(Feature f); public JsonParser disable(Feature f); public JsonParser configure(Feature f, boolean state); public boolean isEnabled(Feature f); public int getFeatureMask(); @Deprecated public JsonParser setFeatureMask(int mask); public JsonParser overrideStdFeatures(int values, int mask); public int getFormatFeatures(); public JsonParser overrideFormatFeatures(int values, int mask); public abstract JsonToken nextToken() throws IOException; public abstract JsonToken nextValue() throws IOException; public boolean nextFieldName(SerializableString str) throws IOException; public String nextFieldName() throws IOException; public String nextTextValue() throws IOException; public int nextIntValue(int defaultValue) throws IOException; public long nextLongValue(long defaultValue) throws IOException; public Boolean nextBooleanValue() throws IOException; public abstract JsonParser skipChildren() throws IOException; public void finishToken() throws IOException; public JsonToken currentToken(); public int currentTokenId(); public abstract JsonToken getCurrentToken(); public abstract int getCurrentTokenId(); public abstract boolean hasCurrentToken(); public abstract boolean hasTokenId(int id); public abstract boolean hasToken(JsonToken t); public boolean isExpectedStartArrayToken(); public boolean isExpectedStartObjectToken(); public boolean isNaN() throws IOException; public abstract void clearCurrentToken(); public abstract JsonToken getLastClearedToken(); public abstract void overrideCurrentName(String name); public abstract String getCurrentName() throws IOException; public String currentName() throws IOException; public abstract String getText() throws IOException; public int getText(Writer writer) throws IOException, UnsupportedOperationException; public abstract char[] getTextCharacters() throws IOException; public abstract int getTextLength() throws IOException; public abstract int getTextOffset() throws IOException; public abstract boolean hasTextCharacters(); public abstract Number getNumberValue() throws IOException; public abstract NumberType getNumberType() throws IOException; public byte getByteValue() throws IOException; public short getShortValue() throws IOException; public abstract int getIntValue() throws IOException; public abstract long getLongValue() throws IOException; public abstract BigInteger getBigIntegerValue() throws IOException; public abstract float getFloatValue() throws IOException; public abstract double getDoubleValue() throws IOException; public abstract BigDecimal getDecimalValue() throws IOException; public boolean getBooleanValue() throws IOException; public Object getEmbeddedObject() throws IOException; public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException; public byte[] getBinaryValue() throws IOException; public int readBinaryValue(OutputStream out) throws IOException; public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException; public int getValueAsInt() throws IOException; public int getValueAsInt(int def) throws IOException; public long getValueAsLong() throws IOException; public long getValueAsLong(long def) throws IOException; public double getValueAsDouble() throws IOException; public double getValueAsDouble(double def) throws IOException; public boolean getValueAsBoolean() throws IOException; public boolean getValueAsBoolean(boolean def) throws IOException; public String getValueAsString() throws IOException; public abstract String getValueAsString(String def) throws IOException; public boolean canReadObjectId(); public boolean canReadTypeId(); public Object getObjectId() throws IOException; public Object getTypeId() throws IOException; public <T> T readValueAs(Class<T> valueType) throws IOException; @SuppressWarnings("unchecked") public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException; public <T> Iterator<T> readValuesAs(Class<T> valueType) throws IOException; public <T> Iterator<T> readValuesAs(TypeReference<T> valueTypeRef) throws IOException; @SuppressWarnings("unchecked") public <T extends TreeNode> T readValueAsTree() throws IOException; protected ObjectCodec _codec(); protected JsonParseException _constructError(String msg); protected void _reportUnsupportedOperation(); } // Abstract Java Test Class package com.fasterxml.jackson.core.read; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.testsupport.MockDataInput; import com.fasterxml.jackson.core.util.JsonParserDelegate; import java.io.*; import java.net.URL; import java.util.*; @SuppressWarnings("resource") public class JsonParserTest extends BaseTest { public void testConfig() throws Exception; public void testInterningWithStreams() throws Exception; public void testInterningWithReaders() throws Exception; private void _testIntern(boolean useStream, boolean enableIntern, String expName) throws IOException; public void testSpecExampleSkipping() throws Exception; public void testSpecExampleFully() throws Exception; public void testKeywords() throws Exception; private void _testKeywords(JsonParser p, boolean checkColumn) throws Exception; public void testSkipping() throws Exception; private void _testSkipping(int mode) throws Exception; public void testNameEscaping() throws IOException; private void _testNameEscaping(int mode) throws IOException; public void testLongText() throws Exception; private void _testLongText(int LEN) throws Exception; public void testBytesAsSource() throws Exception; public void testUtf8BOMHandling() throws Exception; public void testSpacesInURL() throws Exception; public void testHandlingOfInvalidSpaceByteStream() throws Exception; public void testHandlingOfInvalidSpaceChars() throws Exception; public void testHandlingOfInvalidSpaceDataInput() throws Exception; private void _testHandlingOfInvalidSpace(int mode) throws Exception; private void _testHandlingOfInvalidSpaceFromResource(boolean useStream) throws Exception; public void testGetValueAsTextBytes() throws Exception; public void testGetValueAsTextDataInput() throws Exception; public void testGetValueAsTextChars() throws Exception; private void _testGetValueAsText(int mode, boolean delegate) throws Exception; public void testGetTextViaWriter() throws Exception; private void _testGetTextViaWriter(int mode) throws Exception; public void testLongerReadText() throws Exception; private void _testLongerReadText(int mode) throws Exception; private void _doTestSpec(boolean verify) throws IOException; } ``` You are a professional Java test case writer, please create a test case named `testKeywords` for the `JsonParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Unit test that verifies that 3 basic keywords (null, true, false) * are properly parsed in various contexts. */
91
// public abstract Version version(); // @Override // public abstract void close() throws IOException; // public abstract boolean isClosed(); // public abstract JsonStreamContext getParsingContext(); // public abstract JsonLocation getTokenLocation(); // public abstract JsonLocation getCurrentLocation(); // public int releaseBuffered(OutputStream out) throws IOException; // public int releaseBuffered(Writer w) throws IOException; // public JsonParser enable(Feature f); // public JsonParser disable(Feature f); // public JsonParser configure(Feature f, boolean state); // public boolean isEnabled(Feature f); // public int getFeatureMask(); // @Deprecated // public JsonParser setFeatureMask(int mask); // public JsonParser overrideStdFeatures(int values, int mask); // public int getFormatFeatures(); // public JsonParser overrideFormatFeatures(int values, int mask); // public abstract JsonToken nextToken() throws IOException; // public abstract JsonToken nextValue() throws IOException; // public boolean nextFieldName(SerializableString str) throws IOException; // public String nextFieldName() throws IOException; // public String nextTextValue() throws IOException; // public int nextIntValue(int defaultValue) throws IOException; // public long nextLongValue(long defaultValue) throws IOException; // public Boolean nextBooleanValue() throws IOException; // public abstract JsonParser skipChildren() throws IOException; // public void finishToken() throws IOException; // public JsonToken currentToken(); // public int currentTokenId(); // public abstract JsonToken getCurrentToken(); // public abstract int getCurrentTokenId(); // public abstract boolean hasCurrentToken(); // public abstract boolean hasTokenId(int id); // public abstract boolean hasToken(JsonToken t); // public boolean isExpectedStartArrayToken(); // public boolean isExpectedStartObjectToken(); // public boolean isNaN() throws IOException; // public abstract void clearCurrentToken(); // public abstract JsonToken getLastClearedToken(); // public abstract void overrideCurrentName(String name); // public abstract String getCurrentName() throws IOException; // public String currentName() throws IOException; // public abstract String getText() throws IOException; // public int getText(Writer writer) throws IOException, UnsupportedOperationException; // public abstract char[] getTextCharacters() throws IOException; // public abstract int getTextLength() throws IOException; // public abstract int getTextOffset() throws IOException; // public abstract boolean hasTextCharacters(); // public abstract Number getNumberValue() throws IOException; // public abstract NumberType getNumberType() throws IOException; // public byte getByteValue() throws IOException; // public short getShortValue() throws IOException; // public abstract int getIntValue() throws IOException; // public abstract long getLongValue() throws IOException; // public abstract BigInteger getBigIntegerValue() throws IOException; // public abstract float getFloatValue() throws IOException; // public abstract double getDoubleValue() throws IOException; // public abstract BigDecimal getDecimalValue() throws IOException; // public boolean getBooleanValue() throws IOException; // public Object getEmbeddedObject() throws IOException; // public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException; // public byte[] getBinaryValue() throws IOException; // public int readBinaryValue(OutputStream out) throws IOException; // public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException; // public int getValueAsInt() throws IOException; // public int getValueAsInt(int def) throws IOException; // public long getValueAsLong() throws IOException; // public long getValueAsLong(long def) throws IOException; // public double getValueAsDouble() throws IOException; // public double getValueAsDouble(double def) throws IOException; // public boolean getValueAsBoolean() throws IOException; // public boolean getValueAsBoolean(boolean def) throws IOException; // public String getValueAsString() throws IOException; // public abstract String getValueAsString(String def) throws IOException; // public boolean canReadObjectId(); // public boolean canReadTypeId(); // public Object getObjectId() throws IOException; // public Object getTypeId() throws IOException; // public <T> T readValueAs(Class<T> valueType) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException; // public <T> Iterator<T> readValuesAs(Class<T> valueType) throws IOException; // public <T> Iterator<T> readValuesAs(TypeReference<T> valueTypeRef) throws IOException; // @SuppressWarnings("unchecked") // public <T extends TreeNode> T readValueAsTree() throws IOException; // protected ObjectCodec _codec(); // protected JsonParseException _constructError(String msg); // protected void _reportUnsupportedOperation(); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.core.read; // // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.testsupport.MockDataInput; // import com.fasterxml.jackson.core.util.JsonParserDelegate; // import java.io.*; // import java.net.URL; // import java.util.*; // // // // @SuppressWarnings("resource") // public class JsonParserTest extends BaseTest // { // // // public void testConfig() throws Exception; // public void testInterningWithStreams() throws Exception; // public void testInterningWithReaders() throws Exception; // private void _testIntern(boolean useStream, boolean enableIntern, String expName) throws IOException; // public void testSpecExampleSkipping() throws Exception; // public void testSpecExampleFully() throws Exception; // public void testKeywords() throws Exception; // private void _testKeywords(JsonParser p, boolean checkColumn) throws Exception; // public void testSkipping() throws Exception; // private void _testSkipping(int mode) throws Exception; // public void testNameEscaping() throws IOException; // private void _testNameEscaping(int mode) throws IOException; // public void testLongText() throws Exception; // private void _testLongText(int LEN) throws Exception; // public void testBytesAsSource() throws Exception; // public void testUtf8BOMHandling() throws Exception; // public void testSpacesInURL() throws Exception; // public void testHandlingOfInvalidSpaceByteStream() throws Exception; // public void testHandlingOfInvalidSpaceChars() throws Exception; // public void testHandlingOfInvalidSpaceDataInput() throws Exception; // private void _testHandlingOfInvalidSpace(int mode) throws Exception; // private void _testHandlingOfInvalidSpaceFromResource(boolean useStream) throws Exception; // public void testGetValueAsTextBytes() throws Exception; // public void testGetValueAsTextDataInput() throws Exception; // public void testGetValueAsTextChars() throws Exception; // private void _testGetValueAsText(int mode, boolean delegate) throws Exception; // public void testGetTextViaWriter() throws Exception; // private void _testGetTextViaWriter(int mode) throws Exception; // public void testLongerReadText() throws Exception; // private void _testLongerReadText(int mode) throws Exception; // private void _doTestSpec(boolean verify) throws IOException; // } // You are a professional Java test case writer, please create a test case named `testKeywords` for the `JsonParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Unit test that verifies that 3 basic keywords (null, true, false) * are properly parsed in various contexts. */ public void testKeywords() throws Exception {
/** * Unit test that verifies that 3 basic keywords (null, true, false) * are properly parsed in various contexts. */
26
com.fasterxml.jackson.core.JsonParser
src/test/java
```java public abstract Version version(); @Override public abstract void close() throws IOException; public abstract boolean isClosed(); public abstract JsonStreamContext getParsingContext(); public abstract JsonLocation getTokenLocation(); public abstract JsonLocation getCurrentLocation(); public int releaseBuffered(OutputStream out) throws IOException; public int releaseBuffered(Writer w) throws IOException; public JsonParser enable(Feature f); public JsonParser disable(Feature f); public JsonParser configure(Feature f, boolean state); public boolean isEnabled(Feature f); public int getFeatureMask(); @Deprecated public JsonParser setFeatureMask(int mask); public JsonParser overrideStdFeatures(int values, int mask); public int getFormatFeatures(); public JsonParser overrideFormatFeatures(int values, int mask); public abstract JsonToken nextToken() throws IOException; public abstract JsonToken nextValue() throws IOException; public boolean nextFieldName(SerializableString str) throws IOException; public String nextFieldName() throws IOException; public String nextTextValue() throws IOException; public int nextIntValue(int defaultValue) throws IOException; public long nextLongValue(long defaultValue) throws IOException; public Boolean nextBooleanValue() throws IOException; public abstract JsonParser skipChildren() throws IOException; public void finishToken() throws IOException; public JsonToken currentToken(); public int currentTokenId(); public abstract JsonToken getCurrentToken(); public abstract int getCurrentTokenId(); public abstract boolean hasCurrentToken(); public abstract boolean hasTokenId(int id); public abstract boolean hasToken(JsonToken t); public boolean isExpectedStartArrayToken(); public boolean isExpectedStartObjectToken(); public boolean isNaN() throws IOException; public abstract void clearCurrentToken(); public abstract JsonToken getLastClearedToken(); public abstract void overrideCurrentName(String name); public abstract String getCurrentName() throws IOException; public String currentName() throws IOException; public abstract String getText() throws IOException; public int getText(Writer writer) throws IOException, UnsupportedOperationException; public abstract char[] getTextCharacters() throws IOException; public abstract int getTextLength() throws IOException; public abstract int getTextOffset() throws IOException; public abstract boolean hasTextCharacters(); public abstract Number getNumberValue() throws IOException; public abstract NumberType getNumberType() throws IOException; public byte getByteValue() throws IOException; public short getShortValue() throws IOException; public abstract int getIntValue() throws IOException; public abstract long getLongValue() throws IOException; public abstract BigInteger getBigIntegerValue() throws IOException; public abstract float getFloatValue() throws IOException; public abstract double getDoubleValue() throws IOException; public abstract BigDecimal getDecimalValue() throws IOException; public boolean getBooleanValue() throws IOException; public Object getEmbeddedObject() throws IOException; public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException; public byte[] getBinaryValue() throws IOException; public int readBinaryValue(OutputStream out) throws IOException; public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException; public int getValueAsInt() throws IOException; public int getValueAsInt(int def) throws IOException; public long getValueAsLong() throws IOException; public long getValueAsLong(long def) throws IOException; public double getValueAsDouble() throws IOException; public double getValueAsDouble(double def) throws IOException; public boolean getValueAsBoolean() throws IOException; public boolean getValueAsBoolean(boolean def) throws IOException; public String getValueAsString() throws IOException; public abstract String getValueAsString(String def) throws IOException; public boolean canReadObjectId(); public boolean canReadTypeId(); public Object getObjectId() throws IOException; public Object getTypeId() throws IOException; public <T> T readValueAs(Class<T> valueType) throws IOException; @SuppressWarnings("unchecked") public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException; public <T> Iterator<T> readValuesAs(Class<T> valueType) throws IOException; public <T> Iterator<T> readValuesAs(TypeReference<T> valueTypeRef) throws IOException; @SuppressWarnings("unchecked") public <T extends TreeNode> T readValueAsTree() throws IOException; protected ObjectCodec _codec(); protected JsonParseException _constructError(String msg); protected void _reportUnsupportedOperation(); } // Abstract Java Test Class package com.fasterxml.jackson.core.read; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.testsupport.MockDataInput; import com.fasterxml.jackson.core.util.JsonParserDelegate; import java.io.*; import java.net.URL; import java.util.*; @SuppressWarnings("resource") public class JsonParserTest extends BaseTest { public void testConfig() throws Exception; public void testInterningWithStreams() throws Exception; public void testInterningWithReaders() throws Exception; private void _testIntern(boolean useStream, boolean enableIntern, String expName) throws IOException; public void testSpecExampleSkipping() throws Exception; public void testSpecExampleFully() throws Exception; public void testKeywords() throws Exception; private void _testKeywords(JsonParser p, boolean checkColumn) throws Exception; public void testSkipping() throws Exception; private void _testSkipping(int mode) throws Exception; public void testNameEscaping() throws IOException; private void _testNameEscaping(int mode) throws IOException; public void testLongText() throws Exception; private void _testLongText(int LEN) throws Exception; public void testBytesAsSource() throws Exception; public void testUtf8BOMHandling() throws Exception; public void testSpacesInURL() throws Exception; public void testHandlingOfInvalidSpaceByteStream() throws Exception; public void testHandlingOfInvalidSpaceChars() throws Exception; public void testHandlingOfInvalidSpaceDataInput() throws Exception; private void _testHandlingOfInvalidSpace(int mode) throws Exception; private void _testHandlingOfInvalidSpaceFromResource(boolean useStream) throws Exception; public void testGetValueAsTextBytes() throws Exception; public void testGetValueAsTextDataInput() throws Exception; public void testGetValueAsTextChars() throws Exception; private void _testGetValueAsText(int mode, boolean delegate) throws Exception; public void testGetTextViaWriter() throws Exception; private void _testGetTextViaWriter(int mode) throws Exception; public void testLongerReadText() throws Exception; private void _testLongerReadText(int mode) throws Exception; private void _doTestSpec(boolean verify) throws IOException; } ``` You are a professional Java test case writer, please create a test case named `testKeywords` for the `JsonParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Unit test that verifies that 3 basic keywords (null, true, false) * are properly parsed in various contexts. */ public void testKeywords() throws Exception { ```
public abstract class JsonParser implements Closeable, Versioned
package com.fasterxml.jackson.core.read; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.testsupport.MockDataInput; import com.fasterxml.jackson.core.util.JsonParserDelegate; import java.io.*; import java.net.URL; import java.util.*;
public void testConfig() throws Exception; public void testInterningWithStreams() throws Exception; public void testInterningWithReaders() throws Exception; private void _testIntern(boolean useStream, boolean enableIntern, String expName) throws IOException; public void testSpecExampleSkipping() throws Exception; public void testSpecExampleFully() throws Exception; public void testKeywords() throws Exception; private void _testKeywords(JsonParser p, boolean checkColumn) throws Exception; public void testSkipping() throws Exception; private void _testSkipping(int mode) throws Exception; public void testNameEscaping() throws IOException; private void _testNameEscaping(int mode) throws IOException; public void testLongText() throws Exception; private void _testLongText(int LEN) throws Exception; public void testBytesAsSource() throws Exception; public void testUtf8BOMHandling() throws Exception; public void testSpacesInURL() throws Exception; public void testHandlingOfInvalidSpaceByteStream() throws Exception; public void testHandlingOfInvalidSpaceChars() throws Exception; public void testHandlingOfInvalidSpaceDataInput() throws Exception; private void _testHandlingOfInvalidSpace(int mode) throws Exception; private void _testHandlingOfInvalidSpaceFromResource(boolean useStream) throws Exception; public void testGetValueAsTextBytes() throws Exception; public void testGetValueAsTextDataInput() throws Exception; public void testGetValueAsTextChars() throws Exception; private void _testGetValueAsText(int mode, boolean delegate) throws Exception; public void testGetTextViaWriter() throws Exception; private void _testGetTextViaWriter(int mode) throws Exception; public void testLongerReadText() throws Exception; private void _testLongerReadText(int mode) throws Exception; private void _doTestSpec(boolean verify) throws IOException;
bdd59fc7449f15757a3b59fc9c4eaa77a510e182578409b9fe886baa968ce62b
[ "com.fasterxml.jackson.core.read.JsonParserTest::testKeywords" ]
private final static int MIN_BYTE_I = (int) Byte.MIN_VALUE; private final static int MAX_BYTE_I = (int) 255; private final static int MIN_SHORT_I = (int) Short.MIN_VALUE; private final static int MAX_SHORT_I = (int) Short.MAX_VALUE; protected int _features; protected transient RequestPayload _requestPayload;
public void testKeywords() throws Exception
JacksonCore
package com.fasterxml.jackson.core.read; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.testsupport.MockDataInput; import com.fasterxml.jackson.core.util.JsonParserDelegate; import java.io.*; import java.net.URL; import java.util.*; /** * Set of basic unit tests for verifying that the basic parser * functionality works as expected. */ @SuppressWarnings("resource") public class JsonParserTest extends BaseTest { public void testConfig() throws Exception { JsonParser p = createParserUsingReader("[ ]"); p.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE); assertTrue(p.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); p.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE); assertFalse(p.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); p.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true); assertTrue(p.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); p.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); assertFalse(p.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); p.close(); } public void testInterningWithStreams() throws Exception { _testIntern(true, true, "a"); _testIntern(true, false, "b"); } public void testInterningWithReaders() throws Exception { _testIntern(false, true, "c"); _testIntern(false, false, "d"); } private void _testIntern(boolean useStream, boolean enableIntern, String expName) throws IOException { JsonFactory f = JsonFactory.builder() .configure(JsonFactory.Feature.INTERN_FIELD_NAMES, enableIntern) .build(); assertEquals(enableIntern, f.isEnabled(JsonFactory.Feature.INTERN_FIELD_NAMES)); final String JSON = "{ \""+expName+"\" : 1}"; JsonParser p = useStream ? createParserUsingStream(f, JSON, "UTF-8") : createParserUsingReader(f, JSON); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); // needs to be same of cours String actName = p.getCurrentName(); assertEquals(expName, actName); if (enableIntern) { assertSame(expName, actName); } else { assertNotSame(expName, actName); } p.close(); } /** * This basic unit test verifies that example given in the JSON * specification (RFC-4627 or later) is properly parsed at * high-level, without verifying values. */ public void testSpecExampleSkipping() throws Exception { _doTestSpec(false); } /** * Unit test that verifies that the spec example JSON is completely * parsed, and proper values are given for contents of all * events/tokens. */ public void testSpecExampleFully() throws Exception { _doTestSpec(true); } /** * Unit test that verifies that 3 basic keywords (null, true, false) * are properly parsed in various contexts. */ public void testKeywords() throws Exception { final String DOC = "{\n" +"\"key1\" : null,\n" +"\"key2\" : true,\n" +"\"key3\" : false,\n" +"\"key4\" : [ false, null, true ]\n" +"}" ; JsonParser p = createParserUsingStream(JSON_FACTORY, DOC, "UTF-8"); _testKeywords(p, true); p.close(); p = createParserUsingReader(JSON_FACTORY, DOC); _testKeywords(p, true); p.close(); p = createParserForDataInput(JSON_FACTORY, new MockDataInput(DOC)); _testKeywords(p, false); p.close(); } private void _testKeywords(JsonParser p, boolean checkColumn) throws Exception { JsonStreamContext ctxt = p.getParsingContext(); assertEquals("/", ctxt.toString()); assertTrue(ctxt.inRoot()); assertFalse(ctxt.inArray()); assertFalse(ctxt.inObject()); assertEquals(0, ctxt.getEntryCount()); assertEquals(0, ctxt.getCurrentIndex()); // Before advancing to content, we should have following default state... assertFalse(p.hasCurrentToken()); assertNull(p.getText()); assertNull(p.getTextCharacters()); assertEquals(0, p.getTextLength()); // not sure if this is defined but: assertEquals(0, p.getTextOffset()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertEquals("/", ctxt.toString()); assertTrue(p.hasCurrentToken()); JsonLocation loc = p.getTokenLocation(); assertNotNull(loc); assertEquals(1, loc.getLineNr()); if (checkColumn) { assertEquals(1, loc.getColumnNr()); } ctxt = p.getParsingContext(); assertFalse(ctxt.inRoot()); assertFalse(ctxt.inArray()); assertTrue(ctxt.inObject()); assertEquals(0, ctxt.getEntryCount()); assertEquals(0, ctxt.getCurrentIndex()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); verifyFieldName(p, "key1"); assertEquals("{\"key1\"}", ctxt.toString()); assertEquals(2, p.getTokenLocation().getLineNr()); ctxt = p.getParsingContext(); assertFalse(ctxt.inRoot()); assertFalse(ctxt.inArray()); assertTrue(ctxt.inObject()); assertEquals(1, ctxt.getEntryCount()); assertEquals(0, ctxt.getCurrentIndex()); assertEquals("key1", ctxt.getCurrentName()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertEquals("key1", ctxt.getCurrentName()); ctxt = p.getParsingContext(); assertEquals(1, ctxt.getEntryCount()); assertEquals(0, ctxt.getCurrentIndex()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); verifyFieldName(p, "key2"); ctxt = p.getParsingContext(); assertEquals(2, ctxt.getEntryCount()); assertEquals(1, ctxt.getCurrentIndex()); assertEquals("key2", ctxt.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertEquals("key2", ctxt.getCurrentName()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); verifyFieldName(p, "key3"); assertToken(JsonToken.VALUE_FALSE, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); verifyFieldName(p, "key4"); assertToken(JsonToken.START_ARRAY, p.nextToken()); ctxt = p.getParsingContext(); assertTrue(ctxt.inArray()); assertNull(ctxt.getCurrentName()); assertEquals("key4", ctxt.getParent().getCurrentName()); assertToken(JsonToken.VALUE_FALSE, p.nextToken()); assertEquals("[0]", ctxt.toString()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); ctxt = p.getParsingContext(); assertTrue(ctxt.inObject()); assertToken(JsonToken.END_OBJECT, p.nextToken()); ctxt = p.getParsingContext(); assertTrue(ctxt.inRoot()); assertNull(ctxt.getCurrentName()); } public void testSkipping() throws Exception { _testSkipping(MODE_INPUT_STREAM); _testSkipping(MODE_INPUT_STREAM_THROTTLED); _testSkipping(MODE_READER); _testSkipping(MODE_DATA_INPUT); } private void _testSkipping(int mode) throws Exception { // InputData has some limitations to take into consideration boolean isInputData = (mode == MODE_DATA_INPUT); String DOC = "[ 1, 3, [ true, null ], 3, { \"a\":\"b\" }, [ [ ] ], { } ]"; ; JsonParser p = createParser(mode, DOC); // First, skipping of the whole thing assertToken(JsonToken.START_ARRAY, p.nextToken()); p.skipChildren(); assertEquals(JsonToken.END_ARRAY, p.currentToken()); if (!isInputData) { JsonToken t = p.nextToken(); if (t != null) { fail("Expected null at end of doc, got "+t); } } p.close(); // Then individual ones p = createParser(mode, DOC); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); p.skipChildren(); // shouldn't move assertToken(JsonToken.VALUE_NUMBER_INT, p.currentToken()); assertEquals(1, p.getIntValue()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); // then skip array assertToken(JsonToken.START_ARRAY, p.nextToken()); p.skipChildren(); assertToken(JsonToken.END_ARRAY, p.currentToken()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertToken(JsonToken.START_OBJECT, p.nextToken()); p.skipChildren(); assertToken(JsonToken.END_OBJECT, p.currentToken()); assertToken(JsonToken.START_ARRAY, p.nextToken()); p.skipChildren(); assertToken(JsonToken.END_ARRAY, p.currentToken()); assertToken(JsonToken.START_OBJECT, p.nextToken()); p.skipChildren(); assertToken(JsonToken.END_OBJECT, p.currentToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); p.close(); } public void testNameEscaping() throws IOException { _testNameEscaping(MODE_INPUT_STREAM); _testNameEscaping(MODE_READER); _testNameEscaping(MODE_DATA_INPUT); } private void _testNameEscaping(int mode) throws IOException { final Map<String,String> NAME_MAP = new LinkedHashMap<String,String>(); NAME_MAP.put("", ""); NAME_MAP.put("\\\"funny\\\"", "\"funny\""); NAME_MAP.put("\\\\", "\\"); NAME_MAP.put("\\r", "\r"); NAME_MAP.put("\\n", "\n"); NAME_MAP.put("\\t", "\t"); NAME_MAP.put("\\r\\n", "\r\n"); NAME_MAP.put("\\\"\\\"", "\"\""); NAME_MAP.put("Line\\nfeed", "Line\nfeed"); NAME_MAP.put("Yet even longer \\\"name\\\"!", "Yet even longer \"name\"!"); int entry = 0; for (Map.Entry<String,String> en : NAME_MAP.entrySet()) { ++entry; String input = en.getKey(); String expResult = en.getValue(); final String DOC = "{ \""+input+"\":null}"; JsonParser p = createParser(mode, DOC); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); // first, sanity check (field name == getText() String act = p.getCurrentName(); assertEquals(act, getAndVerifyText(p)); if (!expResult.equals(act)) { String msg = "Failed for name #"+entry+"/"+NAME_MAP.size(); if (expResult.length() != act.length()) { fail(msg+": exp length "+expResult.length()+", actual "+act.length()); } assertEquals(msg, expResult, act); } assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); } } /** * Unit test that verifies that long text segments are handled * correctly; mostly to stress-test underlying segment-based * text buffer(s). */ public void testLongText() throws Exception { // lengths chosen to tease out problems with buffer allocation... _testLongText(310); _testLongText(7700); _testLongText(49000); _testLongText(96000); } private void _testLongText(int LEN) throws Exception { StringBuilder sb = new StringBuilder(LEN + 100); Random r = new Random(LEN); while (sb.length() < LEN) { sb.append(r.nextInt()); sb.append(" xyz foo"); if (r.nextBoolean()) { sb.append(" and \"bar\""); } else if (r.nextBoolean()) { sb.append(" [whatever].... "); } else { // Let's try some more 'exotic' chars sb.append(" UTF-8-fu: try this {\u00E2/\u0BF8/\uA123!} (look funny?)"); } if (r.nextBoolean()) { if (r.nextBoolean()) { sb.append('\n'); } else if (r.nextBoolean()) { sb.append('\r'); } else { sb.append("\r\n"); } } } final String VALUE = sb.toString(); // Let's use real generator to get JSON done right StringWriter sw = new StringWriter(LEN + (LEN >> 2)); JsonGenerator g = JSON_FACTORY.createGenerator(sw); g.writeStartObject(); g.writeFieldName("doc"); g.writeString(VALUE); g.writeEndObject(); g.close(); final String DOC = sw.toString(); for (int type = 0; type < 4; ++type) { JsonParser p; switch (type) { case MODE_INPUT_STREAM: case MODE_READER: case MODE_DATA_INPUT: p = createParser(type, DOC); break; default: p = JSON_FACTORY.createParser(encodeInUTF32BE(DOC)); } assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("doc", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); String act = getAndVerifyText(p); if (act.length() != VALUE.length()) { fail("Expected length "+VALUE.length()+", got "+act.length()+" (mode = "+type+")"); } if (!act.equals(VALUE)) { fail("Long text differs"); } // should still know the field name assertEquals("doc", p.getCurrentName()); assertToken(JsonToken.END_OBJECT, p.nextToken()); // InputDate somewhat special, so: if (type != MODE_DATA_INPUT) { assertNull(p.nextToken()); } p.close(); } } /** * Simple unit test that verifies that passing in a byte array * as source works as expected. */ public void testBytesAsSource() throws Exception { String JSON = "[ 1, 2, 3, 4 ]"; byte[] b = JSON.getBytes("UTF-8"); int offset = 50; int len = b.length; byte[] src = new byte[offset + len + offset]; System.arraycopy(b, 0, src, offset, len); JsonParser p = JSON_FACTORY.createParser(src, offset, len); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(1, p.getIntValue()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(2, p.getIntValue()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(3, p.getIntValue()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(4, p.getIntValue()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertNull(p.nextToken()); p.close(); } public void testUtf8BOMHandling() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // first, write BOM: bytes.write(0xEF); bytes.write(0xBB); bytes.write(0xBF); bytes.write("[ 1 ]".getBytes("UTF-8")); byte[] input = bytes.toByteArray(); JsonParser p = JSON_FACTORY.createParser(input); assertEquals(JsonToken.START_ARRAY, p.nextToken()); // should also have skipped first 3 bytes of BOM; but do we have offset available? /* 08-Oct-2013, tatu: Alas, due to [core#111], we have to omit BOM in calculations * as we do not know what the offset is due to -- may need to revisit, if this * discrepancy becomes an issue. For now it just means that BOM is considered * "out of stream" (not part of input). */ JsonLocation loc = p.getTokenLocation(); // so if BOM was consider in-stream (part of input), this should expect 3: assertEquals(0, loc.getByteOffset()); assertEquals(-1, loc.getCharOffset()); assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(JsonToken.END_ARRAY, p.nextToken()); p.close(); p = JSON_FACTORY.createParser(new MockDataInput(input)); assertEquals(JsonToken.START_ARRAY, p.nextToken()); // same BOM, but DataInput is more restrctive so can skip but offsets // are not reliable... loc = p.getTokenLocation(); assertNotNull(loc); assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(JsonToken.END_ARRAY, p.nextToken()); p.close(); } // [core#48] public void testSpacesInURL() throws Exception { File f = File.createTempFile("pre fix&stuff", ".txt"); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8")); w.write("{ }"); w.close(); URL url = f.toURI().toURL(); JsonParser p = JSON_FACTORY.createParser(url); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); } // [core#142] public void testHandlingOfInvalidSpaceByteStream() throws Exception { _testHandlingOfInvalidSpace(MODE_INPUT_STREAM); _testHandlingOfInvalidSpaceFromResource(true); } // [core#142] public void testHandlingOfInvalidSpaceChars() throws Exception { _testHandlingOfInvalidSpace(MODE_READER); _testHandlingOfInvalidSpaceFromResource(false); } // [core#142] public void testHandlingOfInvalidSpaceDataInput() throws Exception { _testHandlingOfInvalidSpace(MODE_DATA_INPUT); } private void _testHandlingOfInvalidSpace(int mode) throws Exception { final String JSON = "{ \u00A0 \"a\":1}"; JsonParser p = createParser(mode, JSON); assertToken(JsonToken.START_OBJECT, p.nextToken()); try { p.nextToken(); fail("Should have failed"); } catch (JsonParseException e) { verifyException(e, "unexpected character"); // and correct error code verifyException(e, "code 160"); } p.close(); } private void _testHandlingOfInvalidSpaceFromResource(boolean useStream) throws Exception { InputStream in = getClass().getResourceAsStream("/test_0xA0.json"); JsonParser p = useStream ? JSON_FACTORY.createParser(in) : JSON_FACTORY.createParser(new InputStreamReader(in, "UTF-8")); assertToken(JsonToken.START_OBJECT, p.nextToken()); try { assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("request", p.getCurrentName()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("mac", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertNotNull(p.getText()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("data", p.getCurrentName()); assertToken(JsonToken.START_OBJECT, p.nextToken()); // ... and from there on, just loop while (p.nextToken() != null) { } fail("Should have failed"); } catch (JsonParseException e) { verifyException(e, "unexpected character"); // and correct error code verifyException(e, "code 160"); } p.close(); } public void testGetValueAsTextBytes() throws Exception { _testGetValueAsText(MODE_INPUT_STREAM, false); _testGetValueAsText(MODE_INPUT_STREAM, true); } public void testGetValueAsTextDataInput() throws Exception { _testGetValueAsText(MODE_DATA_INPUT, false); _testGetValueAsText(MODE_DATA_INPUT, true); } public void testGetValueAsTextChars() throws Exception { _testGetValueAsText(MODE_READER, false); _testGetValueAsText(MODE_READER, true); } private void _testGetValueAsText(int mode, boolean delegate) throws Exception { String JSON = "{\"a\":1,\"b\":true,\"c\":null,\"d\":\"foo\"}"; JsonParser p = createParser(mode, JSON); if (delegate) { p = new JsonParserDelegate(p); } assertToken(JsonToken.START_OBJECT, p.nextToken()); assertNull(p.getValueAsString()); assertEquals("foobar", p.getValueAsString("foobar")); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("a", p.getText()); assertEquals("a", p.getValueAsString()); assertEquals("a", p.getValueAsString("default")); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals("1", p.getValueAsString()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("b", p.getValueAsString()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertEquals("true", p.getValueAsString()); assertEquals("true", p.getValueAsString("foobar")); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("c", p.getValueAsString()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); // null token returned as Java null, as per javadoc assertNull(p.getValueAsString()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("d", p.getValueAsString()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("foo", p.getValueAsString("default")); assertEquals("foo", p.getValueAsString()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.getValueAsString()); // InputData can't peek into end-of-input so: if (mode != MODE_DATA_INPUT) { assertNull(p.nextToken()); } p.close(); } public void testGetTextViaWriter() throws Exception { for (int mode : ALL_MODES) { _testGetTextViaWriter(mode); } } private void _testGetTextViaWriter(int mode) throws Exception { final String INPUT_TEXT = "this is a sample text for json parsing using readText() method"; final String JSON = "{\"a\":\""+INPUT_TEXT+"\",\"b\":true,\"c\":null,\"d\":\"foo\"}"; JsonParser parser = createParser(mode, JSON); assertToken(JsonToken.START_OBJECT, parser.nextToken()); assertToken(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("a", parser.getCurrentName()); assertToken(JsonToken.VALUE_STRING, parser.nextToken()); Writer writer = new StringWriter(); int len = parser.getText(writer); String resultString = writer.toString(); assertEquals(len, resultString.length()); assertEquals(INPUT_TEXT, resultString); parser.close(); } public void testLongerReadText() throws Exception { for (int mode : ALL_MODES) { _testLongerReadText(mode); } } private void _testLongerReadText(int mode) throws Exception { StringBuilder builder = new StringBuilder(); for(int i= 0; i < 1000; i++) { builder.append("Sample Text"+i); } String longText = builder.toString(); final String JSON = "{\"a\":\""+ longText +"\",\"b\":true,\"c\":null,\"d\":\"foo\"}"; JsonParser parser = createParser(MODE_READER, JSON); assertToken(JsonToken.START_OBJECT, parser.nextToken()); assertToken(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("a", parser.getCurrentName()); assertToken(JsonToken.VALUE_STRING, parser.nextToken()); Writer writer = new StringWriter(); int len = parser.getText(writer); String resultString = writer.toString(); assertEquals(len, resultString.length()); assertEquals(longText, resultString); parser.close(); } /* /********************************************************** /* Helper methods /********************************************************** */ private void _doTestSpec(boolean verify) throws IOException { JsonParser p; // First, using a StringReader: p = createParserUsingReader(JSON_FACTORY, SAMPLE_DOC_JSON_SPEC); verifyJsonSpecSampleDoc(p, verify); p.close(); // Then with streams using supported encodings: p = createParserUsingStream(JSON_FACTORY, SAMPLE_DOC_JSON_SPEC, "UTF-8"); verifyJsonSpecSampleDoc(p, verify); p.close(); p = createParserUsingStream(JSON_FACTORY, SAMPLE_DOC_JSON_SPEC, "UTF-16BE"); verifyJsonSpecSampleDoc(p, verify); p.close(); p = createParserUsingStream(JSON_FACTORY, SAMPLE_DOC_JSON_SPEC, "UTF-16LE"); verifyJsonSpecSampleDoc(p, verify); p.close(); // Hmmh. UTF-32 is harder only because JDK doesn't come with // a codec for it. Can't test it yet using this method p = createParserUsingStream(JSON_FACTORY, SAMPLE_DOC_JSON_SPEC, "UTF-32"); verifyJsonSpecSampleDoc(p, verify); p.close(); // and finally, new (as of May 2016) source, DataInput: p = createParserForDataInput(JSON_FACTORY, new MockDataInput(SAMPLE_DOC_JSON_SPEC)); verifyJsonSpecSampleDoc(p, verify); p.close(); } }
[ { "be_test_class_file": "com/fasterxml/jackson/core/JsonParser.java", "be_test_class_name": "com.fasterxml.jackson.core.JsonParser", "be_test_function_name": "isEnabled", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser$Feature;)Z", "line_numbers": [ "714" ], "method_line_rate": 1 } ]
public class NysiisTest extends StringEncoderAbstractTest<Nysiis>
@Test public void testRule1() throws EncoderException { this.assertEncodings( new String[] { "MACX", "MCX" }, new String[] { "KNX", "NX" }, new String[] { "KX", "CX" }, new String[] { "PHX", "FX" }, new String[] { "PFX", "FX" }, new String[] { "SCHX", "SX" }); }
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // import java.util.regex.Pattern; // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoder; // // // // public class Nysiis implements StringEncoder { // private static final char[] CHARS_A = new char[] { 'A' }; // private static final char[] CHARS_AF = new char[] { 'A', 'F' }; // private static final char[] CHARS_C = new char[] { 'C' }; // private static final char[] CHARS_FF = new char[] { 'F', 'F' }; // private static final char[] CHARS_G = new char[] { 'G' }; // private static final char[] CHARS_N = new char[] { 'N' }; // private static final char[] CHARS_NN = new char[] { 'N', 'N' }; // private static final char[] CHARS_S = new char[] { 'S' }; // private static final char[] CHARS_SSS = new char[] { 'S', 'S', 'S' }; // private static final Pattern PAT_MAC = Pattern.compile("^MAC"); // private static final Pattern PAT_KN = Pattern.compile("^KN"); // private static final Pattern PAT_K = Pattern.compile("^K"); // private static final Pattern PAT_PH_PF = Pattern.compile("^(PH|PF)"); // private static final Pattern PAT_SCH = Pattern.compile("^SCH"); // private static final Pattern PAT_EE_IE = Pattern.compile("(EE|IE)$"); // private static final Pattern PAT_DT_ETC = Pattern.compile("(DT|RT|RD|NT|ND)$"); // private static final char SPACE = ' '; // private static final int TRUE_LENGTH = 6; // private final boolean strict; // // private static boolean isVowel(final char c); // private static char[] transcodeRemaining(final char prev, final char curr, final char next, final char aNext); // public Nysiis(); // public Nysiis(final boolean strict); // @Override // public Object encode(final Object obj) throws EncoderException; // @Override // public String encode(final String str); // public boolean isStrict(); // public String nysiis(String str); // } // // // Abstract Java Test Class // package org.apache.commons.codec.language; // // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoderAbstractTest; // import org.junit.Assert; // import org.junit.Test; // // // // public class NysiisTest extends StringEncoderAbstractTest<Nysiis> { // private final Nysiis fullNysiis = new Nysiis(false); // // private void assertEncodings(final String[]... testValues) throws EncoderException; // @Override // protected Nysiis createStringEncoder(); // private void encodeAll(final String[] strings, final String expectedEncoding); // @Test // public void testBran(); // @Test // public void testCap(); // @Test // public void testDad(); // @Test // public void testDan(); // @Test // public void testDropBy() throws EncoderException; // @Test // public void testFal(); // @Test // public void testOthers() throws EncoderException; // @Test // public void testRule1() throws EncoderException; // @Test // public void testRule2() throws EncoderException; // @Test // public void testRule4Dot1() throws EncoderException; // @Test // public void testRule4Dot2() throws EncoderException; // @Test // public void testRule5() throws EncoderException; // @Test // public void testRule6() throws EncoderException; // @Test // public void testRule7() throws EncoderException; // @Test // public void testSnad(); // @Test // public void testSnat(); // @Test // public void testSpecialBranches(); // @Test // public void testTranan(); // @Test // public void testTrueVariant(); // } // You are a professional Java test case writer, please create a test case named `testRule1` for the `Nysiis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests rule 1: Translate first characters of name: MAC → MCC, KN → N, K → C, PH, PF → FF, SCH → SSS * * @throws EncoderException */
src/test/java/org/apache/commons/codec/language/NysiisTest.java
package org.apache.commons.codec.language; import java.util.regex.Pattern; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder;
private static boolean isVowel(final char c); private static char[] transcodeRemaining(final char prev, final char curr, final char next, final char aNext); public Nysiis(); public Nysiis(final boolean strict); @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); public boolean isStrict(); public String nysiis(String str);
182
testRule1
```java // Abstract Java Tested Class package org.apache.commons.codec.language; import java.util.regex.Pattern; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder; public class Nysiis implements StringEncoder { private static final char[] CHARS_A = new char[] { 'A' }; private static final char[] CHARS_AF = new char[] { 'A', 'F' }; private static final char[] CHARS_C = new char[] { 'C' }; private static final char[] CHARS_FF = new char[] { 'F', 'F' }; private static final char[] CHARS_G = new char[] { 'G' }; private static final char[] CHARS_N = new char[] { 'N' }; private static final char[] CHARS_NN = new char[] { 'N', 'N' }; private static final char[] CHARS_S = new char[] { 'S' }; private static final char[] CHARS_SSS = new char[] { 'S', 'S', 'S' }; private static final Pattern PAT_MAC = Pattern.compile("^MAC"); private static final Pattern PAT_KN = Pattern.compile("^KN"); private static final Pattern PAT_K = Pattern.compile("^K"); private static final Pattern PAT_PH_PF = Pattern.compile("^(PH|PF)"); private static final Pattern PAT_SCH = Pattern.compile("^SCH"); private static final Pattern PAT_EE_IE = Pattern.compile("(EE|IE)$"); private static final Pattern PAT_DT_ETC = Pattern.compile("(DT|RT|RD|NT|ND)$"); private static final char SPACE = ' '; private static final int TRUE_LENGTH = 6; private final boolean strict; private static boolean isVowel(final char c); private static char[] transcodeRemaining(final char prev, final char curr, final char next, final char aNext); public Nysiis(); public Nysiis(final boolean strict); @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); public boolean isStrict(); public String nysiis(String str); } // Abstract Java Test Class package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoderAbstractTest; import org.junit.Assert; import org.junit.Test; public class NysiisTest extends StringEncoderAbstractTest<Nysiis> { private final Nysiis fullNysiis = new Nysiis(false); private void assertEncodings(final String[]... testValues) throws EncoderException; @Override protected Nysiis createStringEncoder(); private void encodeAll(final String[] strings, final String expectedEncoding); @Test public void testBran(); @Test public void testCap(); @Test public void testDad(); @Test public void testDan(); @Test public void testDropBy() throws EncoderException; @Test public void testFal(); @Test public void testOthers() throws EncoderException; @Test public void testRule1() throws EncoderException; @Test public void testRule2() throws EncoderException; @Test public void testRule4Dot1() throws EncoderException; @Test public void testRule4Dot2() throws EncoderException; @Test public void testRule5() throws EncoderException; @Test public void testRule6() throws EncoderException; @Test public void testRule7() throws EncoderException; @Test public void testSnad(); @Test public void testSnat(); @Test public void testSpecialBranches(); @Test public void testTranan(); @Test public void testTrueVariant(); } ``` You are a professional Java test case writer, please create a test case named `testRule1` for the `Nysiis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests rule 1: Translate first characters of name: MAC → MCC, KN → N, K → C, PH, PF → FF, SCH → SSS * * @throws EncoderException */
173
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // import java.util.regex.Pattern; // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoder; // // // // public class Nysiis implements StringEncoder { // private static final char[] CHARS_A = new char[] { 'A' }; // private static final char[] CHARS_AF = new char[] { 'A', 'F' }; // private static final char[] CHARS_C = new char[] { 'C' }; // private static final char[] CHARS_FF = new char[] { 'F', 'F' }; // private static final char[] CHARS_G = new char[] { 'G' }; // private static final char[] CHARS_N = new char[] { 'N' }; // private static final char[] CHARS_NN = new char[] { 'N', 'N' }; // private static final char[] CHARS_S = new char[] { 'S' }; // private static final char[] CHARS_SSS = new char[] { 'S', 'S', 'S' }; // private static final Pattern PAT_MAC = Pattern.compile("^MAC"); // private static final Pattern PAT_KN = Pattern.compile("^KN"); // private static final Pattern PAT_K = Pattern.compile("^K"); // private static final Pattern PAT_PH_PF = Pattern.compile("^(PH|PF)"); // private static final Pattern PAT_SCH = Pattern.compile("^SCH"); // private static final Pattern PAT_EE_IE = Pattern.compile("(EE|IE)$"); // private static final Pattern PAT_DT_ETC = Pattern.compile("(DT|RT|RD|NT|ND)$"); // private static final char SPACE = ' '; // private static final int TRUE_LENGTH = 6; // private final boolean strict; // // private static boolean isVowel(final char c); // private static char[] transcodeRemaining(final char prev, final char curr, final char next, final char aNext); // public Nysiis(); // public Nysiis(final boolean strict); // @Override // public Object encode(final Object obj) throws EncoderException; // @Override // public String encode(final String str); // public boolean isStrict(); // public String nysiis(String str); // } // // // Abstract Java Test Class // package org.apache.commons.codec.language; // // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoderAbstractTest; // import org.junit.Assert; // import org.junit.Test; // // // // public class NysiisTest extends StringEncoderAbstractTest<Nysiis> { // private final Nysiis fullNysiis = new Nysiis(false); // // private void assertEncodings(final String[]... testValues) throws EncoderException; // @Override // protected Nysiis createStringEncoder(); // private void encodeAll(final String[] strings, final String expectedEncoding); // @Test // public void testBran(); // @Test // public void testCap(); // @Test // public void testDad(); // @Test // public void testDan(); // @Test // public void testDropBy() throws EncoderException; // @Test // public void testFal(); // @Test // public void testOthers() throws EncoderException; // @Test // public void testRule1() throws EncoderException; // @Test // public void testRule2() throws EncoderException; // @Test // public void testRule4Dot1() throws EncoderException; // @Test // public void testRule4Dot2() throws EncoderException; // @Test // public void testRule5() throws EncoderException; // @Test // public void testRule6() throws EncoderException; // @Test // public void testRule7() throws EncoderException; // @Test // public void testSnad(); // @Test // public void testSnat(); // @Test // public void testSpecialBranches(); // @Test // public void testTranan(); // @Test // public void testTrueVariant(); // } // You are a professional Java test case writer, please create a test case named `testRule1` for the `Nysiis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests rule 1: Translate first characters of name: MAC → MCC, KN → N, K → C, PH, PF → FF, SCH → SSS * * @throws EncoderException */ @Test public void testRule1() throws EncoderException {
/** * Tests rule 1: Translate first characters of name: MAC → MCC, KN → N, K → C, PH, PF → FF, SCH → SSS * * @throws EncoderException */
18
org.apache.commons.codec.language.Nysiis
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.codec.language; import java.util.regex.Pattern; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder; public class Nysiis implements StringEncoder { private static final char[] CHARS_A = new char[] { 'A' }; private static final char[] CHARS_AF = new char[] { 'A', 'F' }; private static final char[] CHARS_C = new char[] { 'C' }; private static final char[] CHARS_FF = new char[] { 'F', 'F' }; private static final char[] CHARS_G = new char[] { 'G' }; private static final char[] CHARS_N = new char[] { 'N' }; private static final char[] CHARS_NN = new char[] { 'N', 'N' }; private static final char[] CHARS_S = new char[] { 'S' }; private static final char[] CHARS_SSS = new char[] { 'S', 'S', 'S' }; private static final Pattern PAT_MAC = Pattern.compile("^MAC"); private static final Pattern PAT_KN = Pattern.compile("^KN"); private static final Pattern PAT_K = Pattern.compile("^K"); private static final Pattern PAT_PH_PF = Pattern.compile("^(PH|PF)"); private static final Pattern PAT_SCH = Pattern.compile("^SCH"); private static final Pattern PAT_EE_IE = Pattern.compile("(EE|IE)$"); private static final Pattern PAT_DT_ETC = Pattern.compile("(DT|RT|RD|NT|ND)$"); private static final char SPACE = ' '; private static final int TRUE_LENGTH = 6; private final boolean strict; private static boolean isVowel(final char c); private static char[] transcodeRemaining(final char prev, final char curr, final char next, final char aNext); public Nysiis(); public Nysiis(final boolean strict); @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); public boolean isStrict(); public String nysiis(String str); } // Abstract Java Test Class package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoderAbstractTest; import org.junit.Assert; import org.junit.Test; public class NysiisTest extends StringEncoderAbstractTest<Nysiis> { private final Nysiis fullNysiis = new Nysiis(false); private void assertEncodings(final String[]... testValues) throws EncoderException; @Override protected Nysiis createStringEncoder(); private void encodeAll(final String[] strings, final String expectedEncoding); @Test public void testBran(); @Test public void testCap(); @Test public void testDad(); @Test public void testDan(); @Test public void testDropBy() throws EncoderException; @Test public void testFal(); @Test public void testOthers() throws EncoderException; @Test public void testRule1() throws EncoderException; @Test public void testRule2() throws EncoderException; @Test public void testRule4Dot1() throws EncoderException; @Test public void testRule4Dot2() throws EncoderException; @Test public void testRule5() throws EncoderException; @Test public void testRule6() throws EncoderException; @Test public void testRule7() throws EncoderException; @Test public void testSnad(); @Test public void testSnat(); @Test public void testSpecialBranches(); @Test public void testTranan(); @Test public void testTrueVariant(); } ``` You are a professional Java test case writer, please create a test case named `testRule1` for the `Nysiis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests rule 1: Translate first characters of name: MAC → MCC, KN → N, K → C, PH, PF → FF, SCH → SSS * * @throws EncoderException */ @Test public void testRule1() throws EncoderException { ```
public class Nysiis implements StringEncoder
package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoderAbstractTest; import org.junit.Assert; import org.junit.Test;
private void assertEncodings(final String[]... testValues) throws EncoderException; @Override protected Nysiis createStringEncoder(); private void encodeAll(final String[] strings, final String expectedEncoding); @Test public void testBran(); @Test public void testCap(); @Test public void testDad(); @Test public void testDan(); @Test public void testDropBy() throws EncoderException; @Test public void testFal(); @Test public void testOthers() throws EncoderException; @Test public void testRule1() throws EncoderException; @Test public void testRule2() throws EncoderException; @Test public void testRule4Dot1() throws EncoderException; @Test public void testRule4Dot2() throws EncoderException; @Test public void testRule5() throws EncoderException; @Test public void testRule6() throws EncoderException; @Test public void testRule7() throws EncoderException; @Test public void testSnad(); @Test public void testSnat(); @Test public void testSpecialBranches(); @Test public void testTranan(); @Test public void testTrueVariant();
be262426c7b4689fc6eb54ce9e966b98474fcd26cbae0ff4ed39ae2e35a047f5
[ "org.apache.commons.codec.language.NysiisTest::testRule1" ]
private static final char[] CHARS_A = new char[] { 'A' }; private static final char[] CHARS_AF = new char[] { 'A', 'F' }; private static final char[] CHARS_C = new char[] { 'C' }; private static final char[] CHARS_FF = new char[] { 'F', 'F' }; private static final char[] CHARS_G = new char[] { 'G' }; private static final char[] CHARS_N = new char[] { 'N' }; private static final char[] CHARS_NN = new char[] { 'N', 'N' }; private static final char[] CHARS_S = new char[] { 'S' }; private static final char[] CHARS_SSS = new char[] { 'S', 'S', 'S' }; private static final Pattern PAT_MAC = Pattern.compile("^MAC"); private static final Pattern PAT_KN = Pattern.compile("^KN"); private static final Pattern PAT_K = Pattern.compile("^K"); private static final Pattern PAT_PH_PF = Pattern.compile("^(PH|PF)"); private static final Pattern PAT_SCH = Pattern.compile("^SCH"); private static final Pattern PAT_EE_IE = Pattern.compile("(EE|IE)$"); private static final Pattern PAT_DT_ETC = Pattern.compile("(DT|RT|RD|NT|ND)$"); private static final char SPACE = ' '; private static final int TRUE_LENGTH = 6; private final boolean strict;
@Test public void testRule1() throws EncoderException
private final Nysiis fullNysiis = new Nysiis(false);
Codec
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoderAbstractTest; import org.junit.Assert; import org.junit.Test; /** * Tests {@link Nysiis} * * @since 1.7 * @version $Id$ */ public class NysiisTest extends StringEncoderAbstractTest<Nysiis> { private final Nysiis fullNysiis = new Nysiis(false); /** * Takes an array of String pairs where each pair's first element is the input and the second element the expected * encoding. * * @param testValues * an array of String pairs where each pair's first element is the input and the second element the * expected encoding. * @throws EncoderException */ private void assertEncodings(final String[]... testValues) throws EncoderException { for (final String[] arr : testValues) { Assert.assertEquals("Problem with " + arr[0], arr[1], this.fullNysiis.encode(arr[0])); } } @Override protected Nysiis createStringEncoder() { return new Nysiis(); } private void encodeAll(final String[] strings, final String expectedEncoding) { for (final String string : strings) { Assert.assertEquals("Problem with " + string, expectedEncoding, getStringEncoder().encode(string)); } } @Test public void testBran() { encodeAll(new String[] { "Brian", "Brown", "Brun" }, "BRAN"); } @Test public void testCap() { this.encodeAll(new String[] { "Capp", "Cope", "Copp", "Kipp" }, "CAP"); } @Test public void testDad() { // Data Quality and Record Linkage Techniques P.121 claims this is DAN, // but it should be DAD, verified also with dropby.com this.encodeAll(new String[] { "Dent" }, "DAD"); } @Test public void testDan() { this.encodeAll(new String[] { "Dane", "Dean", "Dionne" }, "DAN"); } /** * Tests data gathered from around the internet. * * @see <a href="http://www.dropby.com/NYSIISTextStrings.html">http://www.dropby.com/NYSIISTextStrings.html</a> * @throws EncoderException */ @Test public void testDropBy() throws EncoderException { // Explanation of differences between this implementation and the one at dropby.com is // prepended to the test string. The referenced rules refer to the outlined steps the // class description for Nysiis. this.assertEncodings( // 1. Transcode first characters of name new String[] { "MACINTOSH", "MCANT" }, // violates 4j: the second N should not be added, as the first // key char is already a N new String[] { "KNUTH", "NAT" }, // Original: NNAT; modified: NATH // O and E are transcoded to A because of rule 4a // H also to A because of rule 4h // the N gets mysteriously lost, maybe because of a wrongly implemented rule 4h // that skips the next char in such a case? // the remaining A is removed because of rule 7 new String[] { "KOEHN", "CAN" }, // Original: C // violates 4j: see also KNUTH new String[] { "PHILLIPSON", "FALAPSAN" }, // Original: FFALAP[SAN] // violates 4j: see also KNUTH new String[] { "PFEISTER", "FASTAR" }, // Original: FFASTA[R] // violates 4j: see also KNUTH new String[] { "SCHOENHOEFT", "SANAFT" }, // Original: SSANAF[T] // 2. Transcode last characters of name: new String[] { "MCKEE", "MCY" }, new String[] { "MACKIE", "MCY" }, new String[] { "HEITSCHMIDT", "HATSNAD" }, new String[] { "BART", "BAD" }, new String[] { "HURD", "HAD" }, new String[] { "HUNT", "HAD" }, new String[] { "WESTERLUND", "WASTARLAD" }, // 4. Transcode remaining characters by following these rules, // incrementing by one character each time: new String[] { "CASSTEVENS", "CASTAFAN" }, new String[] { "VASQUEZ", "VASG" }, new String[] { "FRAZIER", "FRASAR" }, new String[] { "BOWMAN", "BANAN" }, new String[] { "MCKNIGHT", "MCNAGT" }, new String[] { "RICKERT", "RACAD" }, // violates 5: the last S is not removed // when comparing to DEUTS, which is phonetically similar // the result it also DAT, which is correct for DEUTSCH too imo new String[] { "DEUTSCH", "DAT" }, // Original: DATS new String[] { "WESTPHAL", "WASTFAL" }, // violates 4h: the H should be transcoded to S and thus ignored as // the first key character is also S new String[] { "SHRIVER", "SRAVAR" }, // Original: SHRAVA[R] // same as KOEHN, the L gets mysteriously lost new String[] { "KUHL", "CAL" }, // Original: C new String[] { "RAWSON", "RASAN" }, // If last character is S, remove it new String[] { "JILES", "JAL" }, // violates 6: if the last two characters are AY, remove A new String[] { "CARRAWAY", "CARY" }, // Original: CARAY new String[] { "YAMADA", "YANAD" }); } @Test public void testFal() { this.encodeAll(new String[] { "Phil" }, "FAL"); } /** * Tests data gathered from around the internets. * * @throws EncoderException */ @Test public void testOthers() throws EncoderException { this.assertEncodings( new String[] { "O'Daniel", "ODANAL" }, new String[] { "O'Donnel", "ODANAL" }, new String[] { "Cory", "CARY" }, new String[] { "Corey", "CARY" }, new String[] { "Kory", "CARY" }, // new String[] { "FUZZY", "FASY" }); } /** * Tests rule 1: Translate first characters of name: MAC → MCC, KN → N, K → C, PH, PF → FF, SCH → SSS * * @throws EncoderException */ @Test public void testRule1() throws EncoderException { this.assertEncodings( new String[] { "MACX", "MCX" }, new String[] { "KNX", "NX" }, new String[] { "KX", "CX" }, new String[] { "PHX", "FX" }, new String[] { "PFX", "FX" }, new String[] { "SCHX", "SX" }); } /** * Tests rule 2: Translate last characters of name: EE → Y, IE → Y, DT, RT, RD, NT, ND → D * * @throws EncoderException */ @Test public void testRule2() throws EncoderException { this.assertEncodings( new String[] { "XEE", "XY" }, new String[] { "XIE", "XY" }, new String[] { "XDT", "XD" }, new String[] { "XRT", "XD" }, new String[] { "XRD", "XD" }, new String[] { "XNT", "XD" }, new String[] { "XND", "XD" }); } /** * Tests rule 4.1: EV → AF else A, E, I, O, U → A * * @throws EncoderException */ @Test public void testRule4Dot1() throws EncoderException { this.assertEncodings( new String[] { "XEV", "XAF" }, new String[] { "XAX", "XAX" }, new String[] { "XEX", "XAX" }, new String[] { "XIX", "XAX" }, new String[] { "XOX", "XAX" }, new String[] { "XUX", "XAX" }); } /** * Tests rule 4.2: Q → G, Z → S, M → N * * @throws EncoderException */ @Test public void testRule4Dot2() throws EncoderException { this.assertEncodings( new String[] { "XQ", "XG" }, new String[] { "XZ", "X" }, new String[] { "XM", "XN" }); } /** * Tests rule 5: If last character is S, remove it. * * @throws EncoderException */ @Test public void testRule5() throws EncoderException { this.assertEncodings( new String[] { "XS", "X" }, new String[] { "XSS", "X" }); } /** * Tests rule 6: If last characters are AY, replace with Y. * * @throws EncoderException */ @Test public void testRule6() throws EncoderException { this.assertEncodings( new String[] { "XAY", "XY" }, new String[] { "XAYS", "XY" }); // Rules 5, 6 } /** * Tests rule 7: If last character is A, remove it. * * @throws EncoderException */ @Test public void testRule7() throws EncoderException { this.assertEncodings( new String[] { "XA", "X" }, new String[] { "XAS", "X" }); // Rules 5, 7 } @Test public void testSnad() { // Data Quality and Record Linkage Techniques P.121 claims this is SNAT, // but it should be SNAD this.encodeAll(new String[] { "Schmidt" }, "SNAD"); } @Test public void testSnat() { this.encodeAll(new String[] { "Smith", "Schmit" }, "SNAT"); } @Test public void testSpecialBranches() { this.encodeAll(new String[] { "Kobwick" }, "CABWAC"); this.encodeAll(new String[] { "Kocher" }, "CACAR"); this.encodeAll(new String[] { "Fesca" }, "FASC"); this.encodeAll(new String[] { "Shom" }, "SAN"); this.encodeAll(new String[] { "Ohlo" }, "OL"); this.encodeAll(new String[] { "Uhu" }, "UH"); this.encodeAll(new String[] { "Um" }, "UN"); } @Test public void testTranan() { this.encodeAll(new String[] { "Trueman", "Truman" }, "TRANAN"); } @Test public void testTrueVariant() { final Nysiis encoder = new Nysiis(true); final String encoded = encoder.encode("WESTERLUND"); Assert.assertTrue(encoded.length() <= 6); Assert.assertEquals("WASTAR", encoded); } }
[ { "be_test_class_file": "org/apache/commons/codec/language/Nysiis.java", "be_test_class_name": "org.apache.commons.codec.language.Nysiis", "be_test_function_name": "encode", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "227" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Nysiis.java", "be_test_class_name": "org.apache.commons.codec.language.Nysiis", "be_test_function_name": "isStrict", "be_test_function_signature": "()Z", "line_numbers": [ "236" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Nysiis.java", "be_test_class_name": "org.apache.commons.codec.language.Nysiis", "be_test_function_name": "isVowel", "be_test_function_signature": "(C)Z", "line_numbers": [ "101" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Nysiis.java", "be_test_class_name": "org.apache.commons.codec.language.Nysiis", "be_test_function_name": "nysiis", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "247", "248", "252", "254", "255", "260", "261", "262", "263", "264", "268", "269", "272", "273", "276", "277", "279", "280", "281", "282", "283", "286", "287", "291", "292", "295", "296", "297", "300", "301", "303", "304", "309", "310", "314", "315" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/apache/commons/codec/language/Nysiis.java", "be_test_class_name": "org.apache.commons.codec.language.Nysiis", "be_test_function_name": "transcodeRemaining", "be_test_function_signature": "(CCCC)[C", "line_numbers": [ "120", "121", "125", "126", "130", "131", "132", "133", "134", "135", "139", "140", "141", "143", "147", "148", "152", "153", "157", "158", "162", "163", "166" ], "method_line_rate": 0.4782608695652174 } ]
public class TimeSeriesTests extends TestCase implements SeriesChangeListener
public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series"); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } }
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.lang.reflect.InvocationTargetException; // import java.lang.reflect.Method; // import java.util.Collection; // import java.util.Collections; // import java.util.Date; // import java.util.Iterator; // import java.util.List; // import java.util.TimeZone; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.data.general.Series; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.general.SeriesException; // // // // public class TimeSeries extends Series implements Cloneable, Serializable { // private static final long serialVersionUID = -5032960206869675528L; // protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; // protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; // private String domain; // private String range; // protected Class timePeriodClass; // protected List data; // private int maximumItemCount; // private long maximumItemAge; // private double minY; // private double maxY; // // public TimeSeries(Comparable name); // public TimeSeries(Comparable name, String domain, String range); // public String getDomainDescription(); // public void setDomainDescription(String description); // public String getRangeDescription(); // public void setRangeDescription(String description); // public int getItemCount(); // public List getItems(); // public int getMaximumItemCount(); // public void setMaximumItemCount(int maximum); // public long getMaximumItemAge(); // public void setMaximumItemAge(long periods); // public double getMinY(); // public double getMaxY(); // public Class getTimePeriodClass(); // public TimeSeriesDataItem getDataItem(int index); // public TimeSeriesDataItem getDataItem(RegularTimePeriod period); // TimeSeriesDataItem getRawDataItem(int index); // TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); // public RegularTimePeriod getTimePeriod(int index); // public RegularTimePeriod getNextTimePeriod(); // public Collection getTimePeriods(); // public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); // public int getIndex(RegularTimePeriod period); // public Number getValue(int index); // public Number getValue(RegularTimePeriod period); // public void add(TimeSeriesDataItem item); // public void add(TimeSeriesDataItem item, boolean notify); // public void add(RegularTimePeriod period, double value); // public void add(RegularTimePeriod period, double value, boolean notify); // public void add(RegularTimePeriod period, Number value); // public void add(RegularTimePeriod period, Number value, boolean notify); // public void update(RegularTimePeriod period, Number value); // public void update(int index, Number value); // public TimeSeries addAndOrUpdate(TimeSeries series); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // double value); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // Number value); // public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); // public void removeAgedItems(boolean notify); // public void removeAgedItems(long latest, boolean notify); // public void clear(); // public void delete(RegularTimePeriod period); // public void delete(int start, int end); // public void delete(int start, int end, boolean notify); // public Object clone() throws CloneNotSupportedException; // public TimeSeries createCopy(int start, int end) // throws CloneNotSupportedException; // public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) // throws CloneNotSupportedException; // public boolean equals(Object obj); // public int hashCode(); // private void updateBoundsForAddedItem(TimeSeriesDataItem item); // private void updateBoundsForRemovedItem(TimeSeriesDataItem item); // private void findBoundsByIteration(); // private double minIgnoreNaN(double a, double b); // private double maxIgnoreNaN(double a, double b); // } // // // Abstract Java Test Class // package org.jfree.data.time.junit; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.event.SeriesChangeListener; // import org.jfree.data.general.SeriesException; // import org.jfree.data.time.Day; // import org.jfree.data.time.FixedMillisecond; // import org.jfree.data.time.Month; // import org.jfree.data.time.MonthConstants; // import org.jfree.data.time.RegularTimePeriod; // import org.jfree.data.time.TimeSeries; // import org.jfree.data.time.TimeSeriesDataItem; // import org.jfree.data.time.Year; // // // // public class TimeSeriesTests extends TestCase implements SeriesChangeListener { // private TimeSeries seriesA; // private TimeSeries seriesB; // private TimeSeries seriesC; // private boolean gotSeriesChangeEvent = false; // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public TimeSeriesTests(String name); // protected void setUp(); // public void seriesChanged(SeriesChangeEvent event); // public void testClone(); // public void testClone2(); // public void testAddValue(); // public void testGetValue(); // public void testDelete(); // public void testDelete2(); // public void testDelete3(); // public void testDelete_RegularTimePeriod(); // public void testSerialization(); // public void testEquals(); // public void testEquals2(); // public void testCreateCopy1(); // public void testCreateCopy2(); // public void testCreateCopy3() throws CloneNotSupportedException; // public void testSetMaximumItemCount(); // public void testAddOrUpdate(); // public void testAddOrUpdate2(); // public void testAddOrUpdate3(); // public void testAddOrUpdate4(); // public void testBug1075255(); // public void testBug1832432(); // public void testGetIndex(); // public void testGetDataItem1(); // public void testGetDataItem2(); // public void testRemoveAgedItems(); // public void testRemoveAgedItems2(); // public void testRemoveAgedItems3(); // public void testRemoveAgedItems4(); // public void testRemoveAgedItems5(); // public void testHashCode(); // public void testBug1864222(); // public void testGetMinY(); // public void testGetMaxY(); // public void testClear(); // public void testAdd(); // public void testUpdate_RegularTimePeriod(); // public void testAdd_TimeSeriesDataItem(); // } // You are a professional Java test case writer, please create a test case named `testCreateCopy1` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */
tests/org/jfree/data/time/junit/TimeSeriesTests.java
package org.jfree.data.time; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimeZone; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.general.Series; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.general.SeriesException;
public TimeSeries(Comparable name); public TimeSeries(Comparable name, String domain, String range); public String getDomainDescription(); public void setDomainDescription(String description); public String getRangeDescription(); public void setRangeDescription(String description); public int getItemCount(); public List getItems(); public int getMaximumItemCount(); public void setMaximumItemCount(int maximum); public long getMaximumItemAge(); public void setMaximumItemAge(long periods); public double getMinY(); public double getMaxY(); public Class getTimePeriodClass(); public TimeSeriesDataItem getDataItem(int index); public TimeSeriesDataItem getDataItem(RegularTimePeriod period); TimeSeriesDataItem getRawDataItem(int index); TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); public RegularTimePeriod getTimePeriod(int index); public RegularTimePeriod getNextTimePeriod(); public Collection getTimePeriods(); public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); public int getIndex(RegularTimePeriod period); public Number getValue(int index); public Number getValue(RegularTimePeriod period); public void add(TimeSeriesDataItem item); public void add(TimeSeriesDataItem item, boolean notify); public void add(RegularTimePeriod period, double value); public void add(RegularTimePeriod period, double value, boolean notify); public void add(RegularTimePeriod period, Number value); public void add(RegularTimePeriod period, Number value, boolean notify); public void update(RegularTimePeriod period, Number value); public void update(int index, Number value); public TimeSeries addAndOrUpdate(TimeSeries series); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, double value); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value); public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); public void removeAgedItems(boolean notify); public void removeAgedItems(long latest, boolean notify); public void clear(); public void delete(RegularTimePeriod period); public void delete(int start, int end); public void delete(int start, int end, boolean notify); public Object clone() throws CloneNotSupportedException; public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException; public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); private void updateBoundsForAddedItem(TimeSeriesDataItem item); private void updateBoundsForRemovedItem(TimeSeriesDataItem item); private void findBoundsByIteration(); private double minIgnoreNaN(double a, double b); private double maxIgnoreNaN(double a, double b);
512
testCreateCopy1
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimeZone; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.general.Series; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.general.SeriesException; public class TimeSeries extends Series implements Cloneable, Serializable { private static final long serialVersionUID = -5032960206869675528L; protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; private String domain; private String range; protected Class timePeriodClass; protected List data; private int maximumItemCount; private long maximumItemAge; private double minY; private double maxY; public TimeSeries(Comparable name); public TimeSeries(Comparable name, String domain, String range); public String getDomainDescription(); public void setDomainDescription(String description); public String getRangeDescription(); public void setRangeDescription(String description); public int getItemCount(); public List getItems(); public int getMaximumItemCount(); public void setMaximumItemCount(int maximum); public long getMaximumItemAge(); public void setMaximumItemAge(long periods); public double getMinY(); public double getMaxY(); public Class getTimePeriodClass(); public TimeSeriesDataItem getDataItem(int index); public TimeSeriesDataItem getDataItem(RegularTimePeriod period); TimeSeriesDataItem getRawDataItem(int index); TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); public RegularTimePeriod getTimePeriod(int index); public RegularTimePeriod getNextTimePeriod(); public Collection getTimePeriods(); public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); public int getIndex(RegularTimePeriod period); public Number getValue(int index); public Number getValue(RegularTimePeriod period); public void add(TimeSeriesDataItem item); public void add(TimeSeriesDataItem item, boolean notify); public void add(RegularTimePeriod period, double value); public void add(RegularTimePeriod period, double value, boolean notify); public void add(RegularTimePeriod period, Number value); public void add(RegularTimePeriod period, Number value, boolean notify); public void update(RegularTimePeriod period, Number value); public void update(int index, Number value); public TimeSeries addAndOrUpdate(TimeSeries series); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, double value); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value); public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); public void removeAgedItems(boolean notify); public void removeAgedItems(long latest, boolean notify); public void clear(); public void delete(RegularTimePeriod period); public void delete(int start, int end); public void delete(int start, int end, boolean notify); public Object clone() throws CloneNotSupportedException; public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException; public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); private void updateBoundsForAddedItem(TimeSeriesDataItem item); private void updateBoundsForRemovedItem(TimeSeriesDataItem item); private void findBoundsByIteration(); private double minIgnoreNaN(double a, double b); private double maxIgnoreNaN(double a, double b); } // Abstract Java Test Class package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; public class TimeSeriesTests extends TestCase implements SeriesChangeListener { private TimeSeries seriesA; private TimeSeries seriesB; private TimeSeries seriesC; private boolean gotSeriesChangeEvent = false; private static final double EPSILON = 0.0000000001; public static Test suite(); public TimeSeriesTests(String name); protected void setUp(); public void seriesChanged(SeriesChangeEvent event); public void testClone(); public void testClone2(); public void testAddValue(); public void testGetValue(); public void testDelete(); public void testDelete2(); public void testDelete3(); public void testDelete_RegularTimePeriod(); public void testSerialization(); public void testEquals(); public void testEquals2(); public void testCreateCopy1(); public void testCreateCopy2(); public void testCreateCopy3() throws CloneNotSupportedException; public void testSetMaximumItemCount(); public void testAddOrUpdate(); public void testAddOrUpdate2(); public void testAddOrUpdate3(); public void testAddOrUpdate4(); public void testBug1075255(); public void testBug1832432(); public void testGetIndex(); public void testGetDataItem1(); public void testGetDataItem2(); public void testRemoveAgedItems(); public void testRemoveAgedItems2(); public void testRemoveAgedItems3(); public void testRemoveAgedItems4(); public void testRemoveAgedItems5(); public void testHashCode(); public void testBug1864222(); public void testGetMinY(); public void testGetMaxY(); public void testClear(); public void testAdd(); public void testUpdate_RegularTimePeriod(); public void testAdd_TimeSeriesDataItem(); } ``` You are a professional Java test case writer, please create a test case named `testCreateCopy1` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */
424
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.lang.reflect.InvocationTargetException; // import java.lang.reflect.Method; // import java.util.Collection; // import java.util.Collections; // import java.util.Date; // import java.util.Iterator; // import java.util.List; // import java.util.TimeZone; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.data.general.Series; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.general.SeriesException; // // // // public class TimeSeries extends Series implements Cloneable, Serializable { // private static final long serialVersionUID = -5032960206869675528L; // protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; // protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; // private String domain; // private String range; // protected Class timePeriodClass; // protected List data; // private int maximumItemCount; // private long maximumItemAge; // private double minY; // private double maxY; // // public TimeSeries(Comparable name); // public TimeSeries(Comparable name, String domain, String range); // public String getDomainDescription(); // public void setDomainDescription(String description); // public String getRangeDescription(); // public void setRangeDescription(String description); // public int getItemCount(); // public List getItems(); // public int getMaximumItemCount(); // public void setMaximumItemCount(int maximum); // public long getMaximumItemAge(); // public void setMaximumItemAge(long periods); // public double getMinY(); // public double getMaxY(); // public Class getTimePeriodClass(); // public TimeSeriesDataItem getDataItem(int index); // public TimeSeriesDataItem getDataItem(RegularTimePeriod period); // TimeSeriesDataItem getRawDataItem(int index); // TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); // public RegularTimePeriod getTimePeriod(int index); // public RegularTimePeriod getNextTimePeriod(); // public Collection getTimePeriods(); // public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); // public int getIndex(RegularTimePeriod period); // public Number getValue(int index); // public Number getValue(RegularTimePeriod period); // public void add(TimeSeriesDataItem item); // public void add(TimeSeriesDataItem item, boolean notify); // public void add(RegularTimePeriod period, double value); // public void add(RegularTimePeriod period, double value, boolean notify); // public void add(RegularTimePeriod period, Number value); // public void add(RegularTimePeriod period, Number value, boolean notify); // public void update(RegularTimePeriod period, Number value); // public void update(int index, Number value); // public TimeSeries addAndOrUpdate(TimeSeries series); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // double value); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // Number value); // public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); // public void removeAgedItems(boolean notify); // public void removeAgedItems(long latest, boolean notify); // public void clear(); // public void delete(RegularTimePeriod period); // public void delete(int start, int end); // public void delete(int start, int end, boolean notify); // public Object clone() throws CloneNotSupportedException; // public TimeSeries createCopy(int start, int end) // throws CloneNotSupportedException; // public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) // throws CloneNotSupportedException; // public boolean equals(Object obj); // public int hashCode(); // private void updateBoundsForAddedItem(TimeSeriesDataItem item); // private void updateBoundsForRemovedItem(TimeSeriesDataItem item); // private void findBoundsByIteration(); // private double minIgnoreNaN(double a, double b); // private double maxIgnoreNaN(double a, double b); // } // // // Abstract Java Test Class // package org.jfree.data.time.junit; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.event.SeriesChangeListener; // import org.jfree.data.general.SeriesException; // import org.jfree.data.time.Day; // import org.jfree.data.time.FixedMillisecond; // import org.jfree.data.time.Month; // import org.jfree.data.time.MonthConstants; // import org.jfree.data.time.RegularTimePeriod; // import org.jfree.data.time.TimeSeries; // import org.jfree.data.time.TimeSeriesDataItem; // import org.jfree.data.time.Year; // // // // public class TimeSeriesTests extends TestCase implements SeriesChangeListener { // private TimeSeries seriesA; // private TimeSeries seriesB; // private TimeSeries seriesC; // private boolean gotSeriesChangeEvent = false; // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public TimeSeriesTests(String name); // protected void setUp(); // public void seriesChanged(SeriesChangeEvent event); // public void testClone(); // public void testClone2(); // public void testAddValue(); // public void testGetValue(); // public void testDelete(); // public void testDelete2(); // public void testDelete3(); // public void testDelete_RegularTimePeriod(); // public void testSerialization(); // public void testEquals(); // public void testEquals2(); // public void testCreateCopy1(); // public void testCreateCopy2(); // public void testCreateCopy3() throws CloneNotSupportedException; // public void testSetMaximumItemCount(); // public void testAddOrUpdate(); // public void testAddOrUpdate2(); // public void testAddOrUpdate3(); // public void testAddOrUpdate4(); // public void testBug1075255(); // public void testBug1832432(); // public void testGetIndex(); // public void testGetDataItem1(); // public void testGetDataItem2(); // public void testRemoveAgedItems(); // public void testRemoveAgedItems2(); // public void testRemoveAgedItems3(); // public void testRemoveAgedItems4(); // public void testRemoveAgedItems5(); // public void testHashCode(); // public void testBug1864222(); // public void testGetMinY(); // public void testGetMaxY(); // public void testClear(); // public void testAdd(); // public void testUpdate_RegularTimePeriod(); // public void testAdd_TimeSeriesDataItem(); // } // You are a professional Java test case writer, please create a test case named `testCreateCopy1` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() {
/** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */
1
org.jfree.data.time.TimeSeries
tests
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimeZone; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.general.Series; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.general.SeriesException; public class TimeSeries extends Series implements Cloneable, Serializable { private static final long serialVersionUID = -5032960206869675528L; protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; private String domain; private String range; protected Class timePeriodClass; protected List data; private int maximumItemCount; private long maximumItemAge; private double minY; private double maxY; public TimeSeries(Comparable name); public TimeSeries(Comparable name, String domain, String range); public String getDomainDescription(); public void setDomainDescription(String description); public String getRangeDescription(); public void setRangeDescription(String description); public int getItemCount(); public List getItems(); public int getMaximumItemCount(); public void setMaximumItemCount(int maximum); public long getMaximumItemAge(); public void setMaximumItemAge(long periods); public double getMinY(); public double getMaxY(); public Class getTimePeriodClass(); public TimeSeriesDataItem getDataItem(int index); public TimeSeriesDataItem getDataItem(RegularTimePeriod period); TimeSeriesDataItem getRawDataItem(int index); TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); public RegularTimePeriod getTimePeriod(int index); public RegularTimePeriod getNextTimePeriod(); public Collection getTimePeriods(); public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); public int getIndex(RegularTimePeriod period); public Number getValue(int index); public Number getValue(RegularTimePeriod period); public void add(TimeSeriesDataItem item); public void add(TimeSeriesDataItem item, boolean notify); public void add(RegularTimePeriod period, double value); public void add(RegularTimePeriod period, double value, boolean notify); public void add(RegularTimePeriod period, Number value); public void add(RegularTimePeriod period, Number value, boolean notify); public void update(RegularTimePeriod period, Number value); public void update(int index, Number value); public TimeSeries addAndOrUpdate(TimeSeries series); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, double value); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value); public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); public void removeAgedItems(boolean notify); public void removeAgedItems(long latest, boolean notify); public void clear(); public void delete(RegularTimePeriod period); public void delete(int start, int end); public void delete(int start, int end, boolean notify); public Object clone() throws CloneNotSupportedException; public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException; public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); private void updateBoundsForAddedItem(TimeSeriesDataItem item); private void updateBoundsForRemovedItem(TimeSeriesDataItem item); private void findBoundsByIteration(); private double minIgnoreNaN(double a, double b); private double maxIgnoreNaN(double a, double b); } // Abstract Java Test Class package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; public class TimeSeriesTests extends TestCase implements SeriesChangeListener { private TimeSeries seriesA; private TimeSeries seriesB; private TimeSeries seriesC; private boolean gotSeriesChangeEvent = false; private static final double EPSILON = 0.0000000001; public static Test suite(); public TimeSeriesTests(String name); protected void setUp(); public void seriesChanged(SeriesChangeEvent event); public void testClone(); public void testClone2(); public void testAddValue(); public void testGetValue(); public void testDelete(); public void testDelete2(); public void testDelete3(); public void testDelete_RegularTimePeriod(); public void testSerialization(); public void testEquals(); public void testEquals2(); public void testCreateCopy1(); public void testCreateCopy2(); public void testCreateCopy3() throws CloneNotSupportedException; public void testSetMaximumItemCount(); public void testAddOrUpdate(); public void testAddOrUpdate2(); public void testAddOrUpdate3(); public void testAddOrUpdate4(); public void testBug1075255(); public void testBug1832432(); public void testGetIndex(); public void testGetDataItem1(); public void testGetDataItem2(); public void testRemoveAgedItems(); public void testRemoveAgedItems2(); public void testRemoveAgedItems3(); public void testRemoveAgedItems4(); public void testRemoveAgedItems5(); public void testHashCode(); public void testBug1864222(); public void testGetMinY(); public void testGetMaxY(); public void testClear(); public void testAdd(); public void testUpdate_RegularTimePeriod(); public void testAdd_TimeSeriesDataItem(); } ``` You are a professional Java test case writer, please create a test case named `testCreateCopy1` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { ```
public class TimeSeries extends Series implements Cloneable, Serializable
package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year;
public static Test suite(); public TimeSeriesTests(String name); protected void setUp(); public void seriesChanged(SeriesChangeEvent event); public void testClone(); public void testClone2(); public void testAddValue(); public void testGetValue(); public void testDelete(); public void testDelete2(); public void testDelete3(); public void testDelete_RegularTimePeriod(); public void testSerialization(); public void testEquals(); public void testEquals2(); public void testCreateCopy1(); public void testCreateCopy2(); public void testCreateCopy3() throws CloneNotSupportedException; public void testSetMaximumItemCount(); public void testAddOrUpdate(); public void testAddOrUpdate2(); public void testAddOrUpdate3(); public void testAddOrUpdate4(); public void testBug1075255(); public void testBug1832432(); public void testGetIndex(); public void testGetDataItem1(); public void testGetDataItem2(); public void testRemoveAgedItems(); public void testRemoveAgedItems2(); public void testRemoveAgedItems3(); public void testRemoveAgedItems4(); public void testRemoveAgedItems5(); public void testHashCode(); public void testBug1864222(); public void testGetMinY(); public void testGetMaxY(); public void testClear(); public void testAdd(); public void testUpdate_RegularTimePeriod(); public void testAdd_TimeSeriesDataItem();
be2d84138f162788a27c7b08376093a99434d648fb3f5747423fc3070f6c3c70
[ "org.jfree.data.time.junit.TimeSeriesTests::testCreateCopy1" ]
private static final long serialVersionUID = -5032960206869675528L; protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; private String domain; private String range; protected Class timePeriodClass; protected List data; private int maximumItemCount; private long maximumItemAge; private double minY; private double maxY;
public void testCreateCopy1()
private TimeSeries seriesA; private TimeSeries seriesB; private TimeSeries seriesC; private boolean gotSeriesChangeEvent = false; private static final double EPSILON = 0.0000000001;
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2009, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TimeSeriesTests.java * -------------------- * (C) Copyright 2001-2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2001 : Version 1 (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 15-Oct-2003 : Added test for setMaximumItemCount method (DG); * 23-Aug-2004 : Added test that highlights a bug where the addOrUpdate() * method can lead to more than maximumItemCount items in the * dataset (DG); * 24-May-2006 : Added new tests (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 31-Oct-2007 : New hashCode() test (DG); * 21-Nov-2007 : Added testBug1832432() and testClone2() (DG); * 10-Jan-2008 : Added testBug1864222() (DG); * 13-Jan-2009 : Added testEquals3() and testRemoveAgedItems3() (DG); * 26-May-2009 : Added various tests for min/maxY values (DG); * 09-Jun-2009 : Added testAdd_TimeSeriesDataItem (DG); * 31-Aug-2009 : Added new test for createCopy() method (DG); * */ package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; /** * A collection of test cases for the {@link TimeSeries} class. */ public class TimeSeriesTests extends TestCase implements SeriesChangeListener { /** A time series. */ private TimeSeries seriesA; /** A time series. */ private TimeSeries seriesB; /** A time series. */ private TimeSeries seriesC; /** A flag that indicates whether or not a change event was fired. */ private boolean gotSeriesChangeEvent = false; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.seriesA = new TimeSeries("Series A"); try { this.seriesA.add(new Year(2000), new Integer(102000)); this.seriesA.add(new Year(2001), new Integer(102001)); this.seriesA.add(new Year(2002), new Integer(102002)); this.seriesA.add(new Year(2003), new Integer(102003)); this.seriesA.add(new Year(2004), new Integer(102004)); this.seriesA.add(new Year(2005), new Integer(102005)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesB = new TimeSeries("Series B"); try { this.seriesB.add(new Year(2006), new Integer(202006)); this.seriesB.add(new Year(2007), new Integer(202007)); this.seriesB.add(new Year(2008), new Integer(202008)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesC = new TimeSeries("Series C"); try { this.seriesC.add(new Year(1999), new Integer(301999)); this.seriesC.add(new Year(2000), new Integer(302000)); this.seriesC.add(new Year(2002), new Integer(302002)); } catch (SeriesException e) { System.err.println("Problem creating series."); } } /** * Sets the flag to indicate that a {@link SeriesChangeEvent} has been * received. * * @param event the event. */ public void seriesChanged(SeriesChangeEvent event) { this.gotSeriesChangeEvent = true; } /** * Check that cloning works. */ public void testClone() { TimeSeries series = new TimeSeries("Test Series"); RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002); try { series.add(jan1st2002, new Integer(42)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } TimeSeries clone = null; try { clone = (TimeSeries) series.clone(); clone.setKey("Clone Series"); try { clone.update(jan1st2002, new Integer(10)); } catch (SeriesException e) { e.printStackTrace(); } } catch (CloneNotSupportedException e) { assertTrue(false); } int seriesValue = series.getValue(jan1st2002).intValue(); int cloneValue = Integer.MAX_VALUE; if (clone != null) { cloneValue = clone.getValue(jan1st2002).intValue(); } assertEquals(42, seriesValue); assertEquals(10, cloneValue); assertEquals("Test Series", series.getKey()); if (clone != null) { assertEquals("Clone Series", clone.getKey()); } else { assertTrue(false); } } /** * Another test of the clone() method. */ public void testClone2() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2007), 100.0); s1.add(new Year(2008), null); s1.add(new Year(2009), 200.0); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.addOrUpdate(new Year(2009), 300.0); assertFalse(s1.equals(s2)); s1.addOrUpdate(new Year(2009), 300.0); assertTrue(s1.equals(s2)); } /** * Add a value to series A for 1999. It should be added at index 0. */ public void testAddValue() { try { this.seriesA.add(new Year(1999), new Integer(1)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } int value = this.seriesA.getValue(0).intValue(); assertEquals(1, value); } /** * Tests the retrieval of values. */ public void testGetValue() { Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } /** * Tests the deletion of values. */ public void testDelete() { this.seriesA.delete(0, 0); assertEquals(5, this.seriesA.getItemCount()); Number value = this.seriesA.getValue(new Year(2000)); assertNull(value); } /** * Basic tests for the delete() method. */ public void testDelete2() { TimeSeries s1 = new TimeSeries("Series"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } /** * Some checks for the delete(int, int) method. */ public void testDelete3() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2011), 1.1); s1.add(new Year(2012), 2.2); s1.add(new Year(2013), 3.3); s1.add(new Year(2014), 4.4); s1.add(new Year(2015), 5.5); s1.add(new Year(2016), 6.6); s1.delete(2, 5); assertEquals(2, s1.getItemCount()); assertEquals(new Year(2011), s1.getTimePeriod(0)); assertEquals(new Year(2012), s1.getTimePeriod(1)); assertEquals(1.1, s1.getMinY(), EPSILON); assertEquals(2.2, s1.getMaxY(), EPSILON); } /** * Check that the item bounds are determined correctly when there is a * maximum item count and a new value is added. */ public void testDelete_RegularTimePeriod() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.add(new Year(2013), 4.4); s1.delete(new Year(2010)); s1.delete(new Year(2013)); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); } /** * Tests the equals method. */ public void testEquals() { TimeSeries s1 = new TimeSeries("Time Series 1"); TimeSeries s2 = new TimeSeries("Time Series 2"); boolean b1 = s1.equals(s2); assertFalse("b1", b1); s2.setKey("Time Series 1"); boolean b2 = s1.equals(s2); assertTrue("b2", b2); RegularTimePeriod p1 = new Day(); RegularTimePeriod p2 = p1.next(); s1.add(p1, 100.0); s1.add(p2, 200.0); boolean b3 = s1.equals(s2); assertFalse("b3", b3); s2.add(p1, 100.0); s2.add(p2, 200.0); boolean b4 = s1.equals(s2); assertTrue("b4", b4); s1.setMaximumItemCount(100); boolean b5 = s1.equals(s2); assertFalse("b5", b5); s2.setMaximumItemCount(100); boolean b6 = s1.equals(s2); assertTrue("b6", b6); s1.setMaximumItemAge(100); boolean b7 = s1.equals(s2); assertFalse("b7", b7); s2.setMaximumItemAge(100); boolean b8 = s1.equals(s2); assertTrue("b8", b8); } /** * Tests a specific bug report where null arguments in the constructor * cause the equals() method to fail. Fixed for 0.9.21. */ public void testEquals2() { TimeSeries s1 = new TimeSeries("Series", null, null); TimeSeries s2 = new TimeSeries("Series", null, null); assertTrue(s1.equals(s2)); } /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series"); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Some tests to ensure that the createCopy(int, int) method is * functioning correctly. */ public void testCreateCopy2() { TimeSeries series = new TimeSeries("Series"); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy just the first item... TimeSeries result1 = series.createCopy(0, 0); assertEquals(new Month(1, 2003), result1.getTimePeriod(0)); // copy the first two items... result1 = series.createCopy(0, 1); assertEquals(new Month(2, 2003), result1.getTimePeriod(1)); // copy the middle three items... result1 = series.createCopy(1, 3); assertEquals(new Month(2, 2003), result1.getTimePeriod(0)); assertEquals(new Month(11, 2003), result1.getTimePeriod(2)); // copy the last two items... result1 = series.createCopy(3, 4); assertEquals(new Month(11, 2003), result1.getTimePeriod(0)); assertEquals(new Month(12, 2003), result1.getTimePeriod(1)); // copy the last item... result1 = series.createCopy(4, 4); assertEquals(new Month(12, 2003), result1.getTimePeriod(0)); } catch (CloneNotSupportedException e) { assertTrue(false); } // check negative first argument boolean pass = false; try { /* TimeSeries result = */ series.createCopy(-1, 1); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); // check second argument less than first argument pass = false; try { /* TimeSeries result = */ series.createCopy(1, 0); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); TimeSeries series2 = new TimeSeries("Series 2"); try { TimeSeries series3 = series2.createCopy(99, 999); assertEquals(0, series3.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Checks that the min and max y values are updated correctly when copying * a subset. * * @throws java.lang.CloneNotSupportedException */ public void testCreateCopy3() throws CloneNotSupportedException { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2009), 100.0); s1.add(new Year(2010), 101.0); s1.add(new Year(2011), 102.0); assertEquals(100.0, s1.getMinY(), EPSILON); assertEquals(102.0, s1.getMaxY(), EPSILON); TimeSeries s2 = s1.createCopy(0, 1); assertEquals(100.0, s2.getMinY(), EPSILON); assertEquals(101.0, s2.getMaxY(), EPSILON); TimeSeries s3 = s1.createCopy(1, 2); assertEquals(101.0, s3.getMinY(), EPSILON); assertEquals(102.0, s3.getMaxY(), EPSILON); } /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); assertEquals(16.89, s1.getMinY(), EPSILON); assertEquals(19.32, s1.getMaxY(), EPSILON); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2000), 100.0); assertEquals(1, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 101.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 102.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2002), 103.0); assertEquals(2, s1.getItemCount()); } /** * Test the add branch of the addOrUpdate() method. */ public void testAddOrUpdate2() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2010), 1.1); s1.addOrUpdate(new Year(2011), 2.2); s1.addOrUpdate(new Year(2012), 3.3); assertEquals(2, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Test that the addOrUpdate() method won't allow multiple time period * classes. */ public void testAddOrUpdate3() { TimeSeries s1 = new TimeSeries("S1"); s1.addOrUpdate(new Year(2010), 1.1); assertEquals(Year.class, s1.getTimePeriodClass()); boolean pass = false; try { s1.addOrUpdate(new Month(1, 2009), 0.0); } catch (SeriesException e) { pass = true; } assertTrue(pass); } /** * Some more checks for the addOrUpdate() method. */ public void testAddOrUpdate4() { TimeSeries ts = new TimeSeries("S"); TimeSeriesDataItem overwritten = ts.addOrUpdate(new Year(2009), 20.09); assertNull(overwritten); overwritten = ts.addOrUpdate(new Year(2009), 1.0); assertEquals(new Double(20.09), overwritten.getValue()); assertEquals(new Double(1.0), ts.getValue(new Year(2009))); // changing the overwritten record shouldn't affect the series overwritten.setValue(null); assertEquals(new Double(1.0), ts.getValue(new Year(2009))); TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2010), 20.10); overwritten = ts.addOrUpdate(item); assertNull(overwritten); assertEquals(new Double(20.10), ts.getValue(new Year(2010))); // changing the item that was added should not change the series item.setValue(null); assertEquals(new Double(20.10), ts.getValue(new Year(2010))); } /** * A test for the bug report 1075255. */ public void testBug1075255() { TimeSeries ts = new TimeSeries("dummy"); ts.add(new FixedMillisecond(0L), 0.0); TimeSeries ts2 = new TimeSeries("dummy2"); ts2.add(new FixedMillisecond(0L), 1.0); try { ts.addAndOrUpdate(ts2); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } assertEquals(1, ts.getItemCount()); } /** * A test for bug 1832432. */ public void testBug1832432() { TimeSeries s1 = new TimeSeries("Series"); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); // test independence s1.add(new Day(1, 1, 2007), 100.0); assertFalse(s1.equals(s2)); } /** * Some checks for the getIndex() method. */ public void testGetIndex() { TimeSeries series = new TimeSeries("Series"); assertEquals(-1, series.getIndex(new Month(1, 2003))); series.add(new Month(1, 2003), 45.0); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(-2, series.getIndex(new Month(2, 2003))); series.add(new Month(3, 2003), 55.0); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-2, series.getIndex(new Month(2, 2003))); assertEquals(1, series.getIndex(new Month(3, 2003))); assertEquals(-3, series.getIndex(new Month(4, 2003))); } /** * Some checks for the getDataItem(int) method. */ public void testGetDataItem1() { TimeSeries series = new TimeSeries("S"); // can't get anything yet...just an exception boolean pass = false; try { /*TimeSeriesDataItem item =*/ series.getDataItem(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); series.add(new Year(2006), 100.0); TimeSeriesDataItem item = series.getDataItem(0); assertEquals(new Year(2006), item.getPeriod()); pass = false; try { /*item = */series.getDataItem(-1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); pass = false; try { /*item = */series.getDataItem(1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getDataItem(RegularTimePeriod) method. */ public void testGetDataItem2() { TimeSeries series = new TimeSeries("S"); assertNull(series.getDataItem(new Year(2006))); // try a null argument boolean pass = false; try { /* TimeSeriesDataItem item = */ series.getDataItem(null); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the removeAgedItems() method. */ public void testRemoveAgedItems() { TimeSeries series = new TimeSeries("Test Series"); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with one item series.add(new Year(1999), 1.0); series.setMaximumItemAge(0); this.gotSeriesChangeEvent = false; series.removeAgedItems(true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with two items series.setMaximumItemAge(10); series.add(new Year(2001), 2.0); this.gotSeriesChangeEvent = false; series.setMaximumItemAge(2); assertEquals(2, series.getItemCount()); assertEquals(0, series.getIndex(new Year(1999))); assertFalse(this.gotSeriesChangeEvent); series.setMaximumItemAge(1); assertEquals(1, series.getItemCount()); assertEquals(0, series.getIndex(new Year(2001))); assertTrue(this.gotSeriesChangeEvent); } /** * Some checks for the removeAgedItems(long, boolean) method. */ public void testRemoveAgedItems2() { long y2006 = 1157087372534L; // milliseconds somewhere in 2006 TimeSeries series = new TimeSeries("Test Series"); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test a series with 1 item series.add(new Year(2004), 1.0); series.setMaximumItemAge(1); this.gotSeriesChangeEvent = false; series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); // test a series with two items series.setMaximumItemAge(2); series.add(new Year(2003), 1.0); series.add(new Year(2005), 2.0); assertEquals(2, series.getItemCount()); this.gotSeriesChangeEvent = false; assertEquals(2, series.getItemCount()); series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(2, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(1, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); } /** * Calling removeAgedItems() on an empty series should not throw any * exception. */ public void testRemoveAgedItems3() { TimeSeries s = new TimeSeries("Test"); boolean pass = true; try { s.removeAgedItems(0L, true); } catch (Exception e) { pass = false; } assertTrue(pass); } /** * Check that the item bounds are determined correctly when there is a * maximum item count. */ public void testRemoveAgedItems4() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemAge(2); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.add(new Year(2013), 2.5); assertEquals(3, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Check that the item bounds are determined correctly after a call to * removeAgedItems(). */ public void testRemoveAgedItems5() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemAge(4); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.add(new Year(2013), 2.5); s1.removeAgedItems(new Year(2015).getMiddleMillisecond(), true); assertEquals(3, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { TimeSeries s1 = new TimeSeries("Test"); TimeSeries s2 = new TimeSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(1, 1, 2007), 500.0); s2.add(new Day(1, 1, 2007), 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(2, 1, 2007), null); s2.add(new Day(2, 1, 2007), null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(5, 1, 2007), 111.0); s2.add(new Day(5, 1, 2007), 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(9, 1, 2007), 1.0); s2.add(new Day(9, 1, 2007), 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } /** * Test for bug report 1864222. */ public void testBug1864222() { TimeSeries s = new TimeSeries("S"); s.add(new Day(19, 8, 2005), 1); s.add(new Day(31, 1, 2006), 1); boolean pass = true; try { s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006)); } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); } private static final double EPSILON = 0.0000000001; /** * Some checks for the getMinY() method. */ public void testGetMinY() { TimeSeries s1 = new TimeSeries("S1"); assertTrue(Double.isNaN(s1.getMinY())); s1.add(new Year(2008), 1.1); assertEquals(1.1, s1.getMinY(), EPSILON); s1.add(new Year(2009), 2.2); assertEquals(1.1, s1.getMinY(), EPSILON); s1.add(new Year(2000), 99.9); assertEquals(1.1, s1.getMinY(), EPSILON); s1.add(new Year(2002), -1.1); assertEquals(-1.1, s1.getMinY(), EPSILON); s1.add(new Year(2003), null); assertEquals(-1.1, s1.getMinY(), EPSILON); s1.addOrUpdate(new Year(2002), null); assertEquals(1.1, s1.getMinY(), EPSILON); } /** * Some checks for the getMaxY() method. */ public void testGetMaxY() { TimeSeries s1 = new TimeSeries("S1"); assertTrue(Double.isNaN(s1.getMaxY())); s1.add(new Year(2008), 1.1); assertEquals(1.1, s1.getMaxY(), EPSILON); s1.add(new Year(2009), 2.2); assertEquals(2.2, s1.getMaxY(), EPSILON); s1.add(new Year(2000), 99.9); assertEquals(99.9, s1.getMaxY(), EPSILON); s1.add(new Year(2002), -1.1); assertEquals(99.9, s1.getMaxY(), EPSILON); s1.add(new Year(2003), null); assertEquals(99.9, s1.getMaxY(), EPSILON); s1.addOrUpdate(new Year(2000), null); assertEquals(2.2, s1.getMaxY(), EPSILON); } /** * A test for the clear method. */ public void testClear() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2009), 1.1); s1.add(new Year(2010), 2.2); assertEquals(2, s1.getItemCount()); s1.clear(); assertEquals(0, s1.getItemCount()); assertTrue(Double.isNaN(s1.getMinY())); assertTrue(Double.isNaN(s1.getMaxY())); } /** * Check that the item bounds are determined correctly when there is a * maximum item count and a new value is added. */ public void testAdd() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemCount(2); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); assertEquals(2, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Some checks for the update(RegularTimePeriod...method). */ public void testUpdate_RegularTimePeriod() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.update(new Year(2012), new Double(4.4)); assertEquals(4.4, s1.getMaxY(), EPSILON); s1.update(new Year(2010), new Double(0.5)); assertEquals(0.5, s1.getMinY(), EPSILON); s1.update(new Year(2012), null); assertEquals(2.2, s1.getMaxY(), EPSILON); s1.update(new Year(2010), null); assertEquals(2.2, s1.getMinY(), EPSILON); } /** * Create a TimeSeriesDataItem, add it to a TimeSeries. Now, modifying * the original TimeSeriesDataItem should NOT affect the TimeSeries. */ public void testAdd_TimeSeriesDataItem() { TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2009), 1.0); TimeSeries series = new TimeSeries("S1"); series.add(item); assertTrue(item.equals(series.getDataItem(0))); item.setValue(new Double(99.9)); assertFalse(item.equals(series.getDataItem(0))); } }
[ { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;D)V", "line_numbers": [ "653", "654" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;DZ)V", "line_numbers": [ "666", "667", "668" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;Ljava/lang/Number;)V", "line_numbers": [ "680", "681" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;Ljava/lang/Number;Z)V", "line_numbers": [ "693", "694", "695" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/TimeSeriesDataItem;)V", "line_numbers": [ "564", "565" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/TimeSeriesDataItem;Z)V", "line_numbers": [ "576", "577", "579", "580", "581", "582", "584", "585", "586", "587", "588", "589", "590", "591", "592", "596", "597", "598", "599", "600", "603", "604", "605", "606", "609", "610", "611", "612", "615", "616", "617", "618", "619", "620", "621", "622", "626", "627", "629", "630", "631", "634", "637", "638", "642" ], "method_line_rate": 0.4888888888888889 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "createCopy", "be_test_function_signature": "(II)Lorg/jfree/data/time/TimeSeries;", "line_numbers": [ "1050", "1051", "1053", "1054", "1056", "1057", "1058", "1059", "1060", "1061", "1062", "1064", "1066", "1068", "1069", "1070", "1073" ], "method_line_rate": 0.7647058823529411 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "createCopy", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;Lorg/jfree/data/time/RegularTimePeriod;)Lorg/jfree/data/time/TimeSeries;", "line_numbers": [ "1093", "1094", "1096", "1097", "1099", "1100", "1103", "1104", "1105", "1106", "1107", "1108", "1111", "1112", "1113", "1114", "1116", "1117", "1119", "1120", "1121", "1122", "1125" ], "method_line_rate": 0.8695652173913043 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getIndex", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;)I", "line_numbers": [ "519", "520", "522", "524" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getItemCount", "be_test_function_signature": "()I", "line_numbers": [ "254" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getRawDataItem", "be_test_function_signature": "(I)Lorg/jfree/data/time/TimeSeriesDataItem;", "line_numbers": [ "429" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getTimePeriod", "be_test_function_signature": "(I)Lorg/jfree/data/time/RegularTimePeriod;", "line_numbers": [ "463" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "maxIgnoreNaN", "be_test_function_signature": "(DD)D", "line_numbers": [ "1290", "1291", "1294", "1295", "1298" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "minIgnoreNaN", "be_test_function_signature": "(DD)D", "line_numbers": [ "1267", "1268", "1271", "1272", "1275" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "removeAgedItems", "be_test_function_signature": "(Z)V", "line_numbers": [ "877", "878", "879", "881", "882", "883", "885", "886", "887", "888", "892" ], "method_line_rate": 0.5454545454545454 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "updateBoundsForAddedItem", "be_test_function_signature": "(Lorg/jfree/data/time/TimeSeriesDataItem;)V", "line_numbers": [ "1213", "1214", "1215", "1216", "1217", "1219" ], "method_line_rate": 1 } ]
public class TestTokenBuffer extends BaseMapTest
public void testBasicConfig() throws IOException { TokenBuffer buf; buf = new TokenBuffer(MAPPER, false); assertEquals(MAPPER.version(), buf.version()); assertSame(MAPPER, buf.getCodec()); assertNotNull(buf.getOutputContext()); assertFalse(buf.isClosed()); buf.setCodec(null); assertNull(buf.getCodec()); assertFalse(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII); assertTrue(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII); assertFalse(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.close(); assertTrue(buf.isClosed()); }
// protected final void _appendValue(JsonToken type, Object value); // @Override // protected void _reportUnsupportedOperation(); // @Deprecated // since 2.9 // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds); // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds, // JsonStreamContext parentContext); // public void setLocation(JsonLocation l); // @Override // public ObjectCodec getCodec(); // @Override // public void setCodec(ObjectCodec c); // @Override // public Version version(); // public JsonToken peekNextToken() throws IOException; // @Override // public void close() throws IOException; // @Override // public JsonToken nextToken() throws IOException; // @Override // public String nextFieldName() throws IOException; // @Override // public boolean isClosed(); // @Override // public JsonStreamContext getParsingContext(); // @Override // public JsonLocation getTokenLocation(); // @Override // public JsonLocation getCurrentLocation(); // @Override // public String getCurrentName(); // @Override // public void overrideCurrentName(String name); // @Override // public String getText(); // @Override // public char[] getTextCharacters(); // @Override // public int getTextLength(); // @Override // public int getTextOffset(); // @Override // public boolean hasTextCharacters(); // @Override // public boolean isNaN(); // @Override // public BigInteger getBigIntegerValue() throws IOException; // @Override // public BigDecimal getDecimalValue() throws IOException; // @Override // public double getDoubleValue() throws IOException; // @Override // public float getFloatValue() throws IOException; // @Override // public int getIntValue() throws IOException; // @Override // public long getLongValue() throws IOException; // @Override // public NumberType getNumberType() throws IOException; // @Override // public final Number getNumberValue() throws IOException; // private final boolean _smallerThanInt(Number n); // private final boolean _smallerThanLong(Number n); // protected int _convertNumberToInt(Number n) throws IOException; // protected long _convertNumberToLong(Number n) throws IOException; // @Override // public Object getEmbeddedObject(); // @Override // @SuppressWarnings("resource") // public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; // @Override // public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; // @Override // public boolean canReadObjectId(); // @Override // public boolean canReadTypeId(); // @Override // public Object getTypeId(); // @Override // public Object getObjectId(); // protected final Object _currentObject(); // protected final void _checkIsNumber() throws JsonParseException; // @Override // protected void _handleEOF() throws JsonParseException; // public Segment(); // public JsonToken type(int index); // public int rawType(int index); // public Object get(int index); // public Segment next(); // public boolean hasIds(); // public Segment append(int index, JsonToken tokenType); // public Segment append(int index, JsonToken tokenType, // Object objectId, Object typeId); // public Segment append(int index, JsonToken tokenType, Object value); // public Segment append(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType); // private void set(int index, JsonToken tokenType, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType, Object value); // private void set(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private final void assignNativeIds(int index, Object objectId, Object typeId); // private Object findObjectId(int index); // private Object findTypeId(int index); // private final int _typeIdIndex(int i); // private final int _objectIdIndex(int i); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.util; // // import java.io.*; // import java.math.BigDecimal; // import java.math.BigInteger; // import java.util.UUID; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.JsonParser.NumberType; // import com.fasterxml.jackson.core.io.SerializedString; // import com.fasterxml.jackson.core.util.JsonParserSequence; // import com.fasterxml.jackson.databind.*; // // // // public class TestTokenBuffer extends BaseMapTest // { // private final ObjectMapper MAPPER = objectMapper(); // // public void testBasicConfig() throws IOException; // public void testSimpleWrites() throws IOException; // public void testSimpleNumberWrites() throws IOException; // public void testNumberOverflowInt() throws IOException; // public void testNumberOverflowLong() throws IOException; // public void testParentContext() throws IOException; // public void testSimpleArray() throws IOException; // public void testSimpleObject() throws IOException; // public void testWithJSONSampleDoc() throws Exception; // public void testAppend() throws IOException; // public void testWithUUID() throws IOException; // public void testOutputContext() throws IOException; // private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); // private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); // public void testParentSiblingContext() throws IOException; // public void testBasicSerialize() throws IOException; // public void testWithJsonParserSequenceSimple() throws IOException; // @SuppressWarnings("resource") // public void testWithMultipleJsonParserSequences() throws IOException; // public void testRawValues() throws Exception; // public void testEmbeddedObjectCoerceCheck() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testBasicConfig` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Basic TokenBuffer tests /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/util/TestTokenBuffer.java
package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.TreeMap; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.base.ParserMinimalBase; import com.fasterxml.jackson.core.json.JsonWriteContext; import com.fasterxml.jackson.core.util.ByteArrayBuilder; import com.fasterxml.jackson.databind.*;
public TokenBuffer(ObjectCodec codec, boolean hasNativeIds); public TokenBuffer(JsonParser p); public TokenBuffer(JsonParser p, DeserializationContext ctxt); public static TokenBuffer asCopyOfValue(JsonParser p) throws IOException; public TokenBuffer overrideParentContext(JsonStreamContext ctxt); public TokenBuffer forceUseOfBigDecimal(boolean b); @Override public Version version(); public JsonParser asParser(); public JsonParser asParserOnFirstToken() throws IOException; public JsonParser asParser(ObjectCodec codec); public JsonParser asParser(JsonParser src); public JsonToken firstToken(); @SuppressWarnings("resource") public TokenBuffer append(TokenBuffer other) throws IOException; public void serialize(JsonGenerator gen) throws IOException; public TokenBuffer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException; @Override @SuppressWarnings("resource") public String toString(); private final void _appendNativeIds(StringBuilder sb); @Override public JsonGenerator enable(Feature f); @Override public JsonGenerator disable(Feature f); @Override public boolean isEnabled(Feature f); @Override public int getFeatureMask(); @Override @Deprecated public JsonGenerator setFeatureMask(int mask); @Override public JsonGenerator overrideStdFeatures(int values, int mask); @Override public JsonGenerator useDefaultPrettyPrinter(); @Override public JsonGenerator setCodec(ObjectCodec oc); @Override public ObjectCodec getCodec(); @Override public final JsonWriteContext getOutputContext(); @Override public boolean canWriteBinaryNatively(); @Override public void flush() throws IOException; @Override public void close() throws IOException; @Override public boolean isClosed(); @Override public final void writeStartArray() throws IOException; @Override public final void writeEndArray() throws IOException; @Override public final void writeStartObject() throws IOException; @Override // since 2.8 public void writeStartObject(Object forValue) throws IOException; @Override public final void writeEndObject() throws IOException; @Override public final void writeFieldName(String name) throws IOException; @Override public void writeFieldName(SerializableString name) throws IOException; @Override public void writeString(String text) throws IOException; @Override public void writeString(char[] text, int offset, int len) throws IOException; @Override public void writeString(SerializableString text) throws IOException; @Override public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException; @Override public void writeUTF8String(byte[] text, int offset, int length) throws IOException; @Override public void writeRaw(String text) throws IOException; @Override public void writeRaw(String text, int offset, int len) throws IOException; @Override public void writeRaw(SerializableString text) throws IOException; @Override public void writeRaw(char[] text, int offset, int len) throws IOException; @Override public void writeRaw(char c) throws IOException; @Override public void writeRawValue(String text) throws IOException; @Override public void writeRawValue(String text, int offset, int len) throws IOException; @Override public void writeRawValue(char[] text, int offset, int len) throws IOException; @Override public void writeNumber(short i) throws IOException; @Override public void writeNumber(int i) throws IOException; @Override public void writeNumber(long l) throws IOException; @Override public void writeNumber(double d) throws IOException; @Override public void writeNumber(float f) throws IOException; @Override public void writeNumber(BigDecimal dec) throws IOException; @Override public void writeNumber(BigInteger v) throws IOException; @Override public void writeNumber(String encodedValue) throws IOException; @Override public void writeBoolean(boolean state) throws IOException; @Override public void writeNull() throws IOException; @Override public void writeObject(Object value) throws IOException; @Override public void writeTree(TreeNode node) throws IOException; @Override public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException; @Override public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength); @Override public boolean canWriteTypeId(); @Override public boolean canWriteObjectId(); @Override public void writeTypeId(Object id); @Override public void writeObjectId(Object id); @Override // since 2.8 public void writeEmbeddedObject(Object object) throws IOException; @Override public void copyCurrentEvent(JsonParser p) throws IOException; @Override public void copyCurrentStructure(JsonParser p) throws IOException; private final void _checkNativeIds(JsonParser jp) throws IOException; protected final void _append(JsonToken type); protected final void _append(JsonToken type, Object value); protected final void _appendValue(JsonToken type); protected final void _appendValue(JsonToken type, Object value); @Override protected void _reportUnsupportedOperation(); @Deprecated // since 2.9 public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds); public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds, JsonStreamContext parentContext); public void setLocation(JsonLocation l); @Override public ObjectCodec getCodec(); @Override public void setCodec(ObjectCodec c); @Override public Version version(); public JsonToken peekNextToken() throws IOException; @Override public void close() throws IOException; @Override public JsonToken nextToken() throws IOException; @Override public String nextFieldName() throws IOException; @Override public boolean isClosed(); @Override public JsonStreamContext getParsingContext(); @Override public JsonLocation getTokenLocation(); @Override public JsonLocation getCurrentLocation(); @Override public String getCurrentName(); @Override public void overrideCurrentName(String name); @Override public String getText(); @Override public char[] getTextCharacters(); @Override public int getTextLength(); @Override public int getTextOffset(); @Override public boolean hasTextCharacters(); @Override public boolean isNaN(); @Override public BigInteger getBigIntegerValue() throws IOException; @Override public BigDecimal getDecimalValue() throws IOException; @Override public double getDoubleValue() throws IOException; @Override public float getFloatValue() throws IOException; @Override public int getIntValue() throws IOException; @Override public long getLongValue() throws IOException; @Override public NumberType getNumberType() throws IOException; @Override public final Number getNumberValue() throws IOException; private final boolean _smallerThanInt(Number n); private final boolean _smallerThanLong(Number n); protected int _convertNumberToInt(Number n) throws IOException; protected long _convertNumberToLong(Number n) throws IOException; @Override public Object getEmbeddedObject(); @Override @SuppressWarnings("resource") public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; @Override public boolean canReadObjectId(); @Override public boolean canReadTypeId(); @Override public Object getTypeId(); @Override public Object getObjectId(); protected final Object _currentObject(); protected final void _checkIsNumber() throws JsonParseException; @Override protected void _handleEOF() throws JsonParseException; public Segment(); public JsonToken type(int index); public int rawType(int index); public Object get(int index); public Segment next(); public boolean hasIds(); public Segment append(int index, JsonToken tokenType); public Segment append(int index, JsonToken tokenType, Object objectId, Object typeId); public Segment append(int index, JsonToken tokenType, Object value); public Segment append(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private void set(int index, JsonToken tokenType); private void set(int index, JsonToken tokenType, Object objectId, Object typeId); private void set(int index, JsonToken tokenType, Object value); private void set(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private final void assignNativeIds(int index, Object objectId, Object typeId); private Object findObjectId(int index); private Object findTypeId(int index); private final int _typeIdIndex(int i); private final int _objectIdIndex(int i);
49
testBasicConfig
```java protected final void _appendValue(JsonToken type, Object value); @Override protected void _reportUnsupportedOperation(); @Deprecated // since 2.9 public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds); public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds, JsonStreamContext parentContext); public void setLocation(JsonLocation l); @Override public ObjectCodec getCodec(); @Override public void setCodec(ObjectCodec c); @Override public Version version(); public JsonToken peekNextToken() throws IOException; @Override public void close() throws IOException; @Override public JsonToken nextToken() throws IOException; @Override public String nextFieldName() throws IOException; @Override public boolean isClosed(); @Override public JsonStreamContext getParsingContext(); @Override public JsonLocation getTokenLocation(); @Override public JsonLocation getCurrentLocation(); @Override public String getCurrentName(); @Override public void overrideCurrentName(String name); @Override public String getText(); @Override public char[] getTextCharacters(); @Override public int getTextLength(); @Override public int getTextOffset(); @Override public boolean hasTextCharacters(); @Override public boolean isNaN(); @Override public BigInteger getBigIntegerValue() throws IOException; @Override public BigDecimal getDecimalValue() throws IOException; @Override public double getDoubleValue() throws IOException; @Override public float getFloatValue() throws IOException; @Override public int getIntValue() throws IOException; @Override public long getLongValue() throws IOException; @Override public NumberType getNumberType() throws IOException; @Override public final Number getNumberValue() throws IOException; private final boolean _smallerThanInt(Number n); private final boolean _smallerThanLong(Number n); protected int _convertNumberToInt(Number n) throws IOException; protected long _convertNumberToLong(Number n) throws IOException; @Override public Object getEmbeddedObject(); @Override @SuppressWarnings("resource") public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; @Override public boolean canReadObjectId(); @Override public boolean canReadTypeId(); @Override public Object getTypeId(); @Override public Object getObjectId(); protected final Object _currentObject(); protected final void _checkIsNumber() throws JsonParseException; @Override protected void _handleEOF() throws JsonParseException; public Segment(); public JsonToken type(int index); public int rawType(int index); public Object get(int index); public Segment next(); public boolean hasIds(); public Segment append(int index, JsonToken tokenType); public Segment append(int index, JsonToken tokenType, Object objectId, Object typeId); public Segment append(int index, JsonToken tokenType, Object value); public Segment append(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private void set(int index, JsonToken tokenType); private void set(int index, JsonToken tokenType, Object objectId, Object typeId); private void set(int index, JsonToken tokenType, Object value); private void set(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private final void assignNativeIds(int index, Object objectId, Object typeId); private Object findObjectId(int index); private Object findTypeId(int index); private final int _typeIdIndex(int i); private final int _objectIdIndex(int i); } // Abstract Java Test Class package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*; public class TestTokenBuffer extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); public void testBasicConfig() throws IOException; public void testSimpleWrites() throws IOException; public void testSimpleNumberWrites() throws IOException; public void testNumberOverflowInt() throws IOException; public void testNumberOverflowLong() throws IOException; public void testParentContext() throws IOException; public void testSimpleArray() throws IOException; public void testSimpleObject() throws IOException; public void testWithJSONSampleDoc() throws Exception; public void testAppend() throws IOException; public void testWithUUID() throws IOException; public void testOutputContext() throws IOException; private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); public void testParentSiblingContext() throws IOException; public void testBasicSerialize() throws IOException; public void testWithJsonParserSequenceSimple() throws IOException; @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException; public void testRawValues() throws Exception; public void testEmbeddedObjectCoerceCheck() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testBasicConfig` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Basic TokenBuffer tests /********************************************************** */
28
// protected final void _appendValue(JsonToken type, Object value); // @Override // protected void _reportUnsupportedOperation(); // @Deprecated // since 2.9 // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds); // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds, // JsonStreamContext parentContext); // public void setLocation(JsonLocation l); // @Override // public ObjectCodec getCodec(); // @Override // public void setCodec(ObjectCodec c); // @Override // public Version version(); // public JsonToken peekNextToken() throws IOException; // @Override // public void close() throws IOException; // @Override // public JsonToken nextToken() throws IOException; // @Override // public String nextFieldName() throws IOException; // @Override // public boolean isClosed(); // @Override // public JsonStreamContext getParsingContext(); // @Override // public JsonLocation getTokenLocation(); // @Override // public JsonLocation getCurrentLocation(); // @Override // public String getCurrentName(); // @Override // public void overrideCurrentName(String name); // @Override // public String getText(); // @Override // public char[] getTextCharacters(); // @Override // public int getTextLength(); // @Override // public int getTextOffset(); // @Override // public boolean hasTextCharacters(); // @Override // public boolean isNaN(); // @Override // public BigInteger getBigIntegerValue() throws IOException; // @Override // public BigDecimal getDecimalValue() throws IOException; // @Override // public double getDoubleValue() throws IOException; // @Override // public float getFloatValue() throws IOException; // @Override // public int getIntValue() throws IOException; // @Override // public long getLongValue() throws IOException; // @Override // public NumberType getNumberType() throws IOException; // @Override // public final Number getNumberValue() throws IOException; // private final boolean _smallerThanInt(Number n); // private final boolean _smallerThanLong(Number n); // protected int _convertNumberToInt(Number n) throws IOException; // protected long _convertNumberToLong(Number n) throws IOException; // @Override // public Object getEmbeddedObject(); // @Override // @SuppressWarnings("resource") // public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; // @Override // public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; // @Override // public boolean canReadObjectId(); // @Override // public boolean canReadTypeId(); // @Override // public Object getTypeId(); // @Override // public Object getObjectId(); // protected final Object _currentObject(); // protected final void _checkIsNumber() throws JsonParseException; // @Override // protected void _handleEOF() throws JsonParseException; // public Segment(); // public JsonToken type(int index); // public int rawType(int index); // public Object get(int index); // public Segment next(); // public boolean hasIds(); // public Segment append(int index, JsonToken tokenType); // public Segment append(int index, JsonToken tokenType, // Object objectId, Object typeId); // public Segment append(int index, JsonToken tokenType, Object value); // public Segment append(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType); // private void set(int index, JsonToken tokenType, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType, Object value); // private void set(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private final void assignNativeIds(int index, Object objectId, Object typeId); // private Object findObjectId(int index); // private Object findTypeId(int index); // private final int _typeIdIndex(int i); // private final int _objectIdIndex(int i); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.util; // // import java.io.*; // import java.math.BigDecimal; // import java.math.BigInteger; // import java.util.UUID; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.JsonParser.NumberType; // import com.fasterxml.jackson.core.io.SerializedString; // import com.fasterxml.jackson.core.util.JsonParserSequence; // import com.fasterxml.jackson.databind.*; // // // // public class TestTokenBuffer extends BaseMapTest // { // private final ObjectMapper MAPPER = objectMapper(); // // public void testBasicConfig() throws IOException; // public void testSimpleWrites() throws IOException; // public void testSimpleNumberWrites() throws IOException; // public void testNumberOverflowInt() throws IOException; // public void testNumberOverflowLong() throws IOException; // public void testParentContext() throws IOException; // public void testSimpleArray() throws IOException; // public void testSimpleObject() throws IOException; // public void testWithJSONSampleDoc() throws Exception; // public void testAppend() throws IOException; // public void testWithUUID() throws IOException; // public void testOutputContext() throws IOException; // private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); // private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); // public void testParentSiblingContext() throws IOException; // public void testBasicSerialize() throws IOException; // public void testWithJsonParserSequenceSimple() throws IOException; // @SuppressWarnings("resource") // public void testWithMultipleJsonParserSequences() throws IOException; // public void testRawValues() throws Exception; // public void testEmbeddedObjectCoerceCheck() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testBasicConfig` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Basic TokenBuffer tests /********************************************************** */ public void testBasicConfig() throws IOException {
/* /********************************************************** /* Basic TokenBuffer tests /********************************************************** */
112
com.fasterxml.jackson.databind.util.TokenBuffer
src/test/java
```java protected final void _appendValue(JsonToken type, Object value); @Override protected void _reportUnsupportedOperation(); @Deprecated // since 2.9 public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds); public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds, JsonStreamContext parentContext); public void setLocation(JsonLocation l); @Override public ObjectCodec getCodec(); @Override public void setCodec(ObjectCodec c); @Override public Version version(); public JsonToken peekNextToken() throws IOException; @Override public void close() throws IOException; @Override public JsonToken nextToken() throws IOException; @Override public String nextFieldName() throws IOException; @Override public boolean isClosed(); @Override public JsonStreamContext getParsingContext(); @Override public JsonLocation getTokenLocation(); @Override public JsonLocation getCurrentLocation(); @Override public String getCurrentName(); @Override public void overrideCurrentName(String name); @Override public String getText(); @Override public char[] getTextCharacters(); @Override public int getTextLength(); @Override public int getTextOffset(); @Override public boolean hasTextCharacters(); @Override public boolean isNaN(); @Override public BigInteger getBigIntegerValue() throws IOException; @Override public BigDecimal getDecimalValue() throws IOException; @Override public double getDoubleValue() throws IOException; @Override public float getFloatValue() throws IOException; @Override public int getIntValue() throws IOException; @Override public long getLongValue() throws IOException; @Override public NumberType getNumberType() throws IOException; @Override public final Number getNumberValue() throws IOException; private final boolean _smallerThanInt(Number n); private final boolean _smallerThanLong(Number n); protected int _convertNumberToInt(Number n) throws IOException; protected long _convertNumberToLong(Number n) throws IOException; @Override public Object getEmbeddedObject(); @Override @SuppressWarnings("resource") public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; @Override public boolean canReadObjectId(); @Override public boolean canReadTypeId(); @Override public Object getTypeId(); @Override public Object getObjectId(); protected final Object _currentObject(); protected final void _checkIsNumber() throws JsonParseException; @Override protected void _handleEOF() throws JsonParseException; public Segment(); public JsonToken type(int index); public int rawType(int index); public Object get(int index); public Segment next(); public boolean hasIds(); public Segment append(int index, JsonToken tokenType); public Segment append(int index, JsonToken tokenType, Object objectId, Object typeId); public Segment append(int index, JsonToken tokenType, Object value); public Segment append(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private void set(int index, JsonToken tokenType); private void set(int index, JsonToken tokenType, Object objectId, Object typeId); private void set(int index, JsonToken tokenType, Object value); private void set(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private final void assignNativeIds(int index, Object objectId, Object typeId); private Object findObjectId(int index); private Object findTypeId(int index); private final int _typeIdIndex(int i); private final int _objectIdIndex(int i); } // Abstract Java Test Class package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*; public class TestTokenBuffer extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); public void testBasicConfig() throws IOException; public void testSimpleWrites() throws IOException; public void testSimpleNumberWrites() throws IOException; public void testNumberOverflowInt() throws IOException; public void testNumberOverflowLong() throws IOException; public void testParentContext() throws IOException; public void testSimpleArray() throws IOException; public void testSimpleObject() throws IOException; public void testWithJSONSampleDoc() throws Exception; public void testAppend() throws IOException; public void testWithUUID() throws IOException; public void testOutputContext() throws IOException; private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); public void testParentSiblingContext() throws IOException; public void testBasicSerialize() throws IOException; public void testWithJsonParserSequenceSimple() throws IOException; @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException; public void testRawValues() throws Exception; public void testEmbeddedObjectCoerceCheck() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testBasicConfig` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Basic TokenBuffer tests /********************************************************** */ public void testBasicConfig() throws IOException { ```
public class TokenBuffer /* Won't use JsonGeneratorBase, to minimize overhead for validity * checking */ extends JsonGenerator
package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*;
public void testBasicConfig() throws IOException; public void testSimpleWrites() throws IOException; public void testSimpleNumberWrites() throws IOException; public void testNumberOverflowInt() throws IOException; public void testNumberOverflowLong() throws IOException; public void testParentContext() throws IOException; public void testSimpleArray() throws IOException; public void testSimpleObject() throws IOException; public void testWithJSONSampleDoc() throws Exception; public void testAppend() throws IOException; public void testWithUUID() throws IOException; public void testOutputContext() throws IOException; private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); public void testParentSiblingContext() throws IOException; public void testBasicSerialize() throws IOException; public void testWithJsonParserSequenceSimple() throws IOException; @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException; public void testRawValues() throws Exception; public void testEmbeddedObjectCoerceCheck() throws Exception;
bff9e71dab4180062df82b63f3f005f8a14128734445083c78f278459b90431a
[ "com.fasterxml.jackson.databind.util.TestTokenBuffer::testBasicConfig" ]
protected final static int DEFAULT_GENERATOR_FEATURES = JsonGenerator.Feature.collectDefaults(); protected ObjectCodec _objectCodec; protected JsonStreamContext _parentContext; protected int _generatorFeatures; protected boolean _closed; protected boolean _hasNativeTypeIds; protected boolean _hasNativeObjectIds; protected boolean _mayHaveNativeIds; protected boolean _forceBigDecimal; protected Segment _first; protected Segment _last; protected int _appendAt; protected Object _typeId; protected Object _objectId; protected boolean _hasNativeId = false; protected JsonWriteContext _writeContext;
public void testBasicConfig() throws IOException
private final ObjectMapper MAPPER = objectMapper();
JacksonDatabind
package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*; public class TestTokenBuffer extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); static class Base1730 { } static class Sub1730 extends Base1730 { } /* /********************************************************** /* Basic TokenBuffer tests /********************************************************** */ public void testBasicConfig() throws IOException { TokenBuffer buf; buf = new TokenBuffer(MAPPER, false); assertEquals(MAPPER.version(), buf.version()); assertSame(MAPPER, buf.getCodec()); assertNotNull(buf.getOutputContext()); assertFalse(buf.isClosed()); buf.setCodec(null); assertNull(buf.getCodec()); assertFalse(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII); assertTrue(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII); assertFalse(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.close(); assertTrue(buf.isClosed()); } /** * Test writing of individual simple values */ public void testSimpleWrites() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec // First, with empty buffer JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); assertNull(p.nextToken()); p.close(); // Then with simple text buf.writeString("abc"); p = buf.asParser(); assertNull(p.getCurrentToken()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("abc", p.getText()); assertNull(p.nextToken()); p.close(); // Then, let's append at root level buf.writeNumber(13); p = buf.asParser(); assertNull(p.getCurrentToken()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(13, p.getIntValue()); assertNull(p.nextToken()); p.close(); buf.close(); } // For 2.9, explicit "isNaN" check public void testSimpleNumberWrites() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); double[] values1 = new double[] { 0.25, Double.NaN, -2.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY }; float[] values2 = new float[] { Float.NEGATIVE_INFINITY, 0.25f, Float.POSITIVE_INFINITY }; for (double v : values1) { buf.writeNumber(v); } for (float v : values2) { buf.writeNumber(v); } JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); for (double v : values1) { assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); double actual = p.getDoubleValue(); boolean expNan = Double.isNaN(v) || Double.isInfinite(v); assertEquals(expNan, p.isNaN()); assertEquals(0, Double.compare(v, actual)); } for (float v : values2) { assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); float actual = p.getFloatValue(); boolean expNan = Float.isNaN(v) || Float.isInfinite(v); assertEquals(expNan, p.isNaN()); assertEquals(0, Float.compare(v, actual)); } p.close(); buf.close(); } // [databind#1729] public void testNumberOverflowInt() throws IOException { try (TokenBuffer buf = new TokenBuffer(null, false)) { long big = 1L + Integer.MAX_VALUE; buf.writeNumber(big); try (JsonParser p = buf.asParser()) { assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(NumberType.LONG, p.getNumberType()); try { p.getIntValue(); fail("Expected failure for `int` overflow"); } catch (JsonParseException e) { verifyException(e, "Numeric value ("+big+") out of range of int"); } } } // and ditto for coercion. try (TokenBuffer buf = new TokenBuffer(null, false)) { long big = 1L + Integer.MAX_VALUE; buf.writeNumber(String.valueOf(big)); try (JsonParser p = buf.asParser()) { // NOTE: oddity of buffering, no inspection of "real" type if given String... assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); try { p.getIntValue(); fail("Expected failure for `int` overflow"); } catch (JsonParseException e) { verifyException(e, "Numeric value ("+big+") out of range of int"); } } } } public void testNumberOverflowLong() throws IOException { try (TokenBuffer buf = new TokenBuffer(null, false)) { BigInteger big = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); buf.writeNumber(big); try (JsonParser p = buf.asParser()) { assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(NumberType.BIG_INTEGER, p.getNumberType()); try { p.getLongValue(); fail("Expected failure for `long` overflow"); } catch (JsonParseException e) { verifyException(e, "Numeric value ("+big+") out of range of long"); } } } } public void testParentContext() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec buf.writeStartObject(); buf.writeFieldName("b"); buf.writeStartObject(); buf.writeFieldName("c"); //This assertion succeeds as expected assertEquals("b", buf.getOutputContext().getParent().getCurrentName()); buf.writeString("cval"); buf.writeEndObject(); buf.writeEndObject(); buf.close(); } public void testSimpleArray() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec // First, empty array assertTrue(buf.getOutputContext().inRoot()); buf.writeStartArray(); assertTrue(buf.getOutputContext().inArray()); buf.writeEndArray(); assertTrue(buf.getOutputContext().inRoot()); JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); assertTrue(p.getParsingContext().inRoot()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertTrue(p.getParsingContext().inArray()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertTrue(p.getParsingContext().inRoot()); assertNull(p.nextToken()); p.close(); buf.close(); // Then one with simple contents buf = new TokenBuffer(null, false); buf.writeStartArray(); buf.writeBoolean(true); buf.writeNull(); buf.writeEndArray(); p = buf.asParser(); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertTrue(p.getBooleanValue()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertNull(p.nextToken()); p.close(); buf.close(); // And finally, with array-in-array buf = new TokenBuffer(null, false); buf.writeStartArray(); buf.writeStartArray(); buf.writeBinary(new byte[3]); buf.writeEndArray(); buf.writeEndArray(); p = buf.asParser(); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.START_ARRAY, p.nextToken()); // TokenBuffer exposes it as embedded object... assertToken(JsonToken.VALUE_EMBEDDED_OBJECT, p.nextToken()); Object ob = p.getEmbeddedObject(); assertNotNull(ob); assertTrue(ob instanceof byte[]); assertEquals(3, ((byte[]) ob).length); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertNull(p.nextToken()); p.close(); buf.close(); } public void testSimpleObject() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // First, empty JSON Object assertTrue(buf.getOutputContext().inRoot()); buf.writeStartObject(); assertTrue(buf.getOutputContext().inObject()); buf.writeEndObject(); assertTrue(buf.getOutputContext().inRoot()); JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); assertTrue(p.getParsingContext().inRoot()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertTrue(p.getParsingContext().inObject()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertTrue(p.getParsingContext().inRoot()); assertNull(p.nextToken()); p.close(); buf.close(); // Then one with simple contents buf = new TokenBuffer(null, false); buf.writeStartObject(); buf.writeNumberField("num", 1.25); buf.writeEndObject(); p = buf.asParser(); assertNull(p.getCurrentToken()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertNull(p.getCurrentName()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); // and override should also work: p.overrideCurrentName("bah"); assertEquals("bah", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); assertEquals(1.25, p.getDoubleValue()); // should still have access to (overridden) name assertEquals("bah", p.getCurrentName()); assertToken(JsonToken.END_OBJECT, p.nextToken()); // but not any more assertNull(p.getCurrentName()); assertNull(p.nextToken()); p.close(); buf.close(); } /** * Verify handling of that "standard" test document (from JSON * specification) */ public void testWithJSONSampleDoc() throws Exception { // First, copy events from known good source (StringReader) JsonParser p = createParserUsingReader(SAMPLE_DOC_JSON_SPEC); TokenBuffer tb = new TokenBuffer(null, false); while (p.nextToken() != null) { tb.copyCurrentEvent(p); } // And then request verification; first structure only: verifyJsonSpecSampleDoc(tb.asParser(), false); // then content check too: verifyJsonSpecSampleDoc(tb.asParser(), true); tb.close(); p.close(); // 19-Oct-2016, tatu: Just for fun, trigger `toString()` for code coverage String desc = tb.toString(); assertNotNull(desc); } public void testAppend() throws IOException { TokenBuffer buf1 = new TokenBuffer(null, false); buf1.writeStartObject(); buf1.writeFieldName("a"); buf1.writeBoolean(true); TokenBuffer buf2 = new TokenBuffer(null, false); buf2.writeFieldName("b"); buf2.writeNumber(13); buf2.writeEndObject(); buf1.append(buf2); // and verify that we got it all... JsonParser p = buf1.asParser(); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("a", p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("b", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(13, p.getIntValue()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); buf1.close(); buf2.close(); } // Since 2.3 had big changes to UUID handling, let's verify we can // deal with public void testWithUUID() throws IOException { for (String value : new String[] { "00000007-0000-0000-0000-000000000000", "76e6d183-5f68-4afa-b94a-922c1fdb83f8", "540a88d1-e2d8-4fb1-9396-9212280d0a7f", "2c9e441d-1cd0-472d-9bab-69838f877574", "591b2869-146e-41d7-8048-e8131f1fdec5", "82994ac2-7b23-49f2-8cc5-e24cf6ed77be", }) { TokenBuffer buf = new TokenBuffer(MAPPER, false); // no ObjectCodec UUID uuid = UUID.fromString(value); MAPPER.writeValue(buf, uuid); buf.close(); // and bring it back UUID out = MAPPER.readValue(buf.asParser(), UUID.class); assertEquals(uuid.toString(), out.toString()); // second part: As per [databind#362], should NOT use binary with TokenBuffer JsonParser p = buf.asParser(); assertEquals(JsonToken.VALUE_STRING, p.nextToken()); String str = p.getText(); assertEquals(value, str); p.close(); } } /* /********************************************************** /* Tests for read/output contexts /********************************************************** */ // for [databind#984]: ensure output context handling identical public void testOutputContext() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec StringWriter w = new StringWriter(); JsonGenerator gen = MAPPER.getFactory().createGenerator(w); // test content: [{"a":1,"b":{"c":2}},{"a":2,"b":{"c":3}}] buf.writeStartArray(); gen.writeStartArray(); _verifyOutputContext(buf, gen); buf.writeStartObject(); gen.writeStartObject(); _verifyOutputContext(buf, gen); buf.writeFieldName("a"); gen.writeFieldName("a"); _verifyOutputContext(buf, gen); buf.writeNumber(1); gen.writeNumber(1); _verifyOutputContext(buf, gen); buf.writeFieldName("b"); gen.writeFieldName("b"); _verifyOutputContext(buf, gen); buf.writeStartObject(); gen.writeStartObject(); _verifyOutputContext(buf, gen); buf.writeFieldName("c"); gen.writeFieldName("c"); _verifyOutputContext(buf, gen); buf.writeNumber(2); gen.writeNumber(2); _verifyOutputContext(buf, gen); buf.writeEndObject(); gen.writeEndObject(); _verifyOutputContext(buf, gen); buf.writeEndObject(); gen.writeEndObject(); _verifyOutputContext(buf, gen); buf.writeEndArray(); gen.writeEndArray(); _verifyOutputContext(buf, gen); buf.close(); gen.close(); } private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2) { _verifyOutputContext(gen1.getOutputContext(), gen2.getOutputContext()); } private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2) { if (ctxt1 == null) { if (ctxt2 == null) { return; } fail("Context 1 null, context 2 not null: "+ctxt2); } else if (ctxt2 == null) { fail("Context 2 null, context 1 not null: "+ctxt1); } if (!ctxt1.toString().equals(ctxt2.toString())) { fail("Different output context: token-buffer's = "+ctxt1+", json-generator's: "+ctxt2); } if (ctxt1.inObject()) { assertTrue(ctxt2.inObject()); String str1 = ctxt1.getCurrentName(); String str2 = ctxt2.getCurrentName(); if ((str1 != str2) && !str1.equals(str2)) { fail("Expected name '"+str2+"' (JsonParser), TokenBuffer had '"+str1+"'"); } } else if (ctxt1.inArray()) { assertTrue(ctxt2.inArray()); assertEquals(ctxt1.getCurrentIndex(), ctxt2.getCurrentIndex()); } _verifyOutputContext(ctxt1.getParent(), ctxt2.getParent()); } // [databind#1253] public void testParentSiblingContext() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec // {"a":{},"b":{"c":"cval"}} buf.writeStartObject(); buf.writeFieldName("a"); buf.writeStartObject(); buf.writeEndObject(); buf.writeFieldName("b"); buf.writeStartObject(); buf.writeFieldName("c"); //This assertion fails (because of 'a') assertEquals("b", buf.getOutputContext().getParent().getCurrentName()); buf.writeString("cval"); buf.writeEndObject(); buf.writeEndObject(); buf.close(); } public void testBasicSerialize() throws IOException { TokenBuffer buf; // let's see how empty works... buf = new TokenBuffer(MAPPER, false); assertEquals("", MAPPER.writeValueAsString(buf)); buf.close(); buf = new TokenBuffer(MAPPER, false); buf.writeStartArray(); buf.writeBoolean(true); buf.writeBoolean(false); long l = 1L + Integer.MAX_VALUE; buf.writeNumber(l); buf.writeNumber((short) 4); buf.writeNumber(0.5); buf.writeEndArray(); assertEquals(aposToQuotes("[true,false,"+l+",4,0.5]"), MAPPER.writeValueAsString(buf)); buf.close(); buf = new TokenBuffer(MAPPER, false); buf.writeStartObject(); buf.writeFieldName(new SerializedString("foo")); buf.writeNull(); buf.writeFieldName("bar"); buf.writeNumber(BigInteger.valueOf(123)); buf.writeFieldName("dec"); buf.writeNumber(BigDecimal.valueOf(5).movePointLeft(2)); assertEquals(aposToQuotes("{'foo':null,'bar':123,'dec':0.05}"), MAPPER.writeValueAsString(buf)); buf.close(); } /* /********************************************************** /* Tests to verify interaction of TokenBuffer and JsonParserSequence /********************************************************** */ public void testWithJsonParserSequenceSimple() throws IOException { // Let's join a TokenBuffer with JsonParser first TokenBuffer buf = new TokenBuffer(null, false); buf.writeStartArray(); buf.writeString("test"); JsonParser p = createParserUsingReader("[ true, null ]"); JsonParserSequence seq = JsonParserSequence.createFlattened(false, buf.asParser(), p); assertEquals(2, seq.containedParsersCount()); assertFalse(p.isClosed()); assertFalse(seq.hasCurrentToken()); assertNull(seq.getCurrentToken()); assertNull(seq.getCurrentName()); assertToken(JsonToken.START_ARRAY, seq.nextToken()); assertToken(JsonToken.VALUE_STRING, seq.nextToken()); assertEquals("test", seq.getText()); // end of first parser input, should switch over: assertToken(JsonToken.START_ARRAY, seq.nextToken()); assertToken(JsonToken.VALUE_TRUE, seq.nextToken()); assertToken(JsonToken.VALUE_NULL, seq.nextToken()); assertToken(JsonToken.END_ARRAY, seq.nextToken()); /* 17-Jan-2009, tatus: At this point, we may or may not get an * exception, depending on how underlying parsers work. * Ideally this should be fixed, probably by asking underlying * parsers to disable checking for balanced start/end markers. */ // for this particular case, we won't get an exception tho... assertNull(seq.nextToken()); // not an error to call again... assertNull(seq.nextToken()); // also: original parsers should be closed assertTrue(p.isClosed()); p.close(); buf.close(); seq.close(); } /** * Test to verify that TokenBuffer and JsonParserSequence work together * as expected. */ @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException { TokenBuffer buf1 = new TokenBuffer(null, false); buf1.writeStartArray(); TokenBuffer buf2 = new TokenBuffer(null, false); buf2.writeString("a"); TokenBuffer buf3 = new TokenBuffer(null, false); buf3.writeNumber(13); TokenBuffer buf4 = new TokenBuffer(null, false); buf4.writeEndArray(); JsonParserSequence seq1 = JsonParserSequence.createFlattened(false, buf1.asParser(), buf2.asParser()); assertEquals(2, seq1.containedParsersCount()); JsonParserSequence seq2 = JsonParserSequence.createFlattened(false, buf3.asParser(), buf4.asParser()); assertEquals(2, seq2.containedParsersCount()); JsonParserSequence combo = JsonParserSequence.createFlattened(false, seq1, seq2); // should flatten it to have 4 underlying parsers assertEquals(4, combo.containedParsersCount()); assertToken(JsonToken.START_ARRAY, combo.nextToken()); assertToken(JsonToken.VALUE_STRING, combo.nextToken()); assertEquals("a", combo.getText()); assertToken(JsonToken.VALUE_NUMBER_INT, combo.nextToken()); assertEquals(13, combo.getIntValue()); assertToken(JsonToken.END_ARRAY, combo.nextToken()); assertNull(combo.nextToken()); buf1.close(); buf2.close(); buf3.close(); buf4.close(); } // [databind#743] public void testRawValues() throws Exception { final String RAW = "{\"a\":1}"; TokenBuffer buf = new TokenBuffer(null, false); buf.writeRawValue(RAW); // first: raw value won't be transformed in any way: JsonParser p = buf.asParser(); assertToken(JsonToken.VALUE_EMBEDDED_OBJECT, p.nextToken()); assertEquals(RawValue.class, p.getEmbeddedObject().getClass()); assertNull(p.nextToken()); p.close(); buf.close(); // then verify it would be serialized just fine assertEquals(RAW, MAPPER.writeValueAsString(buf)); } // [databind#1730] public void testEmbeddedObjectCoerceCheck() throws Exception { TokenBuffer buf = new TokenBuffer(null, false); Object inputPojo = new Sub1730(); buf.writeEmbeddedObject(inputPojo); // first: raw value won't be transformed in any way: JsonParser p = buf.asParser(); Base1730 out = MAPPER.readValue(p, Base1730.class); assertSame(inputPojo, out); p.close(); buf.close(); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "close", "be_test_function_signature": "()V", "line_numbers": [ "654", "655" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "disable", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonGenerator$Feature;)Lcom/fasterxml/jackson/core/JsonGenerator;", "line_numbers": [ "581", "582" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "enable", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonGenerator$Feature;)Lcom/fasterxml/jackson/core/JsonGenerator;", "line_numbers": [ "575", "576" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "getCodec", "be_test_function_signature": "()Lcom/fasterxml/jackson/core/ObjectCodec;", "line_numbers": [ "624" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "getOutputContext", "be_test_function_signature": "()Lcom/fasterxml/jackson/core/json/JsonWriteContext;", "line_numbers": [ "627" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "isClosed", "be_test_function_signature": "()Z", "line_numbers": [ "658" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "isEnabled", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonGenerator$Feature;)Z", "line_numbers": [ "589" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "setCodec", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/ObjectCodec;)Lcom/fasterxml/jackson/core/JsonGenerator;", "line_numbers": [ "619", "620" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "version", "be_test_function_signature": "()Lcom/fasterxml/jackson/core/Version;", "line_numbers": [ "228" ], "method_line_rate": 1 } ]
public class MeterPlotTests extends TestCase
public void testEquals() { MeterPlot plot1 = new MeterPlot(); MeterPlot plot2 = new MeterPlot(); assertTrue(plot1.equals(plot2)); // units plot1.setUnits("mph"); assertFalse(plot1.equals(plot2)); plot2.setUnits("mph"); assertTrue(plot1.equals(plot2)); // range plot1.setRange(new Range(50.0, 70.0)); assertFalse(plot1.equals(plot2)); plot2.setRange(new Range(50.0, 70.0)); assertTrue(plot1.equals(plot2)); // interval plot1.addInterval(new MeterInterval("Normal", new Range(55.0, 60.0))); assertFalse(plot1.equals(plot2)); plot2.addInterval(new MeterInterval("Normal", new Range(55.0, 60.0))); assertTrue(plot1.equals(plot2)); // dial outline paint plot1.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertTrue(plot1.equals(plot2)); // dial shape plot1.setDialShape(DialShape.CHORD); assertFalse(plot1.equals(plot2)); plot2.setDialShape(DialShape.CHORD); assertTrue(plot1.equals(plot2)); // dial background paint plot1.setDialBackgroundPaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setDialBackgroundPaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertTrue(plot1.equals(plot2)); // dial outline paint plot1.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.green, 3.0f, 4.0f, Color.red)); assertFalse(plot1.equals(plot2)); plot2.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.green, 3.0f, 4.0f, Color.red)); assertTrue(plot1.equals(plot2)); // needle paint plot1.setNeedlePaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setNeedlePaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertTrue(plot1.equals(plot2)); // value font plot1.setValueFont(new Font("Serif", Font.PLAIN, 6)); assertFalse(plot1.equals(plot2)); plot2.setValueFont(new Font("Serif", Font.PLAIN, 6)); assertTrue(plot1.equals(plot2)); // value paint plot1.setValuePaint(new GradientPaint(1.0f, 2.0f, Color.black, 3.0f, 4.0f, Color.white)); assertFalse(plot1.equals(plot2)); plot2.setValuePaint(new GradientPaint(1.0f, 2.0f, Color.black, 3.0f, 4.0f, Color.white)); assertTrue(plot1.equals(plot2)); // tick labels visible plot1.setTickLabelsVisible(false); assertFalse(plot1.equals(plot2)); plot2.setTickLabelsVisible(false); assertTrue(plot1.equals(plot2)); // tick label font plot1.setTickLabelFont(new Font("Serif", Font.PLAIN, 6)); assertFalse(plot1.equals(plot2)); plot2.setTickLabelFont(new Font("Serif", Font.PLAIN, 6)); assertTrue(plot1.equals(plot2)); // tick label paint plot1.setTickLabelPaint(Color.red); assertFalse(plot1.equals(plot2)); plot2.setTickLabelPaint(Color.red); assertTrue(plot1.equals(plot2)); // tick label format plot1.setTickLabelFormat(new DecimalFormat("0")); assertFalse(plot1.equals(plot2)); plot2.setTickLabelFormat(new DecimalFormat("0")); assertTrue(plot1.equals(plot2)); // tick paint plot1.setTickPaint(Color.green); assertFalse(plot1.equals(plot2)); plot2.setTickPaint(Color.green); assertTrue(plot1.equals(plot2)); // tick size plot1.setTickSize(1.23); assertFalse(plot1.equals(plot2)); plot2.setTickSize(1.23); assertTrue(plot1.equals(plot2)); // draw border plot1.setDrawBorder(!plot1.getDrawBorder()); assertFalse(plot1.equals(plot2)); plot2.setDrawBorder(plot1.getDrawBorder()); assertTrue(plot1.equals(plot2)); // meter angle plot1.setMeterAngle(22); assertFalse(plot1.equals(plot2)); plot2.setMeterAngle(22); assertTrue(plot1.equals(plot2)); }
// import org.jfree.chart.text.TextUtilities; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PaintUtilities; // import org.jfree.chart.util.RectangleInsets; // import org.jfree.chart.util.ResourceBundleWrapper; // import org.jfree.chart.util.SerialUtilities; // import org.jfree.data.Range; // import org.jfree.data.event.DatasetChangeEvent; // import org.jfree.data.general.ValueDataset; // // // // public class MeterPlot extends Plot implements Serializable, Cloneable { // private static final long serialVersionUID = 2987472457734470962L; // static final Paint DEFAULT_DIAL_BACKGROUND_PAINT = Color.black; // static final Paint DEFAULT_NEEDLE_PAINT = Color.green; // static final Font DEFAULT_VALUE_FONT = new Font("Tahoma", Font.BOLD, 12); // static final Paint DEFAULT_VALUE_PAINT = Color.yellow; // public static final int DEFAULT_METER_ANGLE = 270; // public static final float DEFAULT_BORDER_SIZE = 3f; // public static final float DEFAULT_CIRCLE_SIZE = 10f; // public static final Font DEFAULT_LABEL_FONT = new Font("Tahoma", // Font.BOLD, 10); // private ValueDataset dataset; // private DialShape shape; // private int meterAngle; // private Range range; // private double tickSize; // private transient Paint tickPaint; // private String units; // private Font valueFont; // private transient Paint valuePaint; // private boolean drawBorder; // private transient Paint dialOutlinePaint; // private transient Paint dialBackgroundPaint; // private transient Paint needlePaint; // private boolean tickLabelsVisible; // private Font tickLabelFont; // private transient Paint tickLabelPaint; // private NumberFormat tickLabelFormat; // protected static ResourceBundle localizationResources = // ResourceBundleWrapper.getBundle( // "org.jfree.chart.plot.LocalizationBundle"); // private List intervals; // // public MeterPlot(); // public MeterPlot(ValueDataset dataset); // public DialShape getDialShape(); // public void setDialShape(DialShape shape); // public int getMeterAngle(); // public void setMeterAngle(int angle); // public Range getRange(); // public void setRange(Range range); // public double getTickSize(); // public void setTickSize(double size); // public Paint getTickPaint(); // public void setTickPaint(Paint paint); // public String getUnits(); // public void setUnits(String units); // public Paint getNeedlePaint(); // public void setNeedlePaint(Paint paint); // public boolean getTickLabelsVisible(); // public void setTickLabelsVisible(boolean visible); // public Font getTickLabelFont(); // public void setTickLabelFont(Font font); // public Paint getTickLabelPaint(); // public void setTickLabelPaint(Paint paint); // public NumberFormat getTickLabelFormat(); // public void setTickLabelFormat(NumberFormat format); // public Font getValueFont(); // public void setValueFont(Font font); // public Paint getValuePaint(); // public void setValuePaint(Paint paint); // public Paint getDialBackgroundPaint(); // public void setDialBackgroundPaint(Paint paint); // public boolean getDrawBorder(); // public void setDrawBorder(boolean draw); // public Paint getDialOutlinePaint(); // public void setDialOutlinePaint(Paint paint); // public ValueDataset getDataset(); // public void setDataset(ValueDataset dataset); // public List getIntervals(); // public void addInterval(MeterInterval interval); // public void clearIntervals(); // public LegendItemCollection getLegendItems(); // public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, // PlotState parentState, // PlotRenderingInfo info); // protected void drawArcForInterval(Graphics2D g2, Rectangle2D meterArea, // MeterInterval interval); // protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue, // double maxValue, Paint paint, Stroke stroke); // protected void fillArc(Graphics2D g2, Rectangle2D area, // double minValue, double maxValue, Paint paint, // boolean dial); // public double valueToAngle(double value); // protected void drawTicks(Graphics2D g2, Rectangle2D meterArea, // double minValue, double maxValue); // protected void drawTick(Graphics2D g2, Rectangle2D meterArea, // double value); // protected void drawTick(Graphics2D g2, Rectangle2D meterArea, // double value, boolean label); // protected void drawValueLabel(Graphics2D g2, Rectangle2D area); // public String getPlotType(); // public void zoom(double percent); // public boolean equals(Object obj); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.chart.plot.junit; // // import java.awt.Color; // import java.awt.Font; // import java.awt.GradientPaint; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import java.text.DecimalFormat; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.plot.DialShape; // import org.jfree.chart.plot.MeterInterval; // import org.jfree.chart.plot.MeterPlot; // import org.jfree.data.Range; // import org.jfree.data.general.DefaultValueDataset; // // // // public class MeterPlotTests extends TestCase { // // // public static Test suite(); // public MeterPlotTests(String name); // public void testEquals(); // public void testCloning(); // public void testSerialization1(); // public void testSerialization2(); // } // You are a professional Java test case writer, please create a test case named `testEquals` for the `MeterPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the equals method to ensure that it can distinguish the required * fields. Note that the dataset is NOT considered in the equals test. */
tests/org/jfree/chart/plot/junit/MeterPlotTests.java
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.NumberFormat; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.text.TextAnchor; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.RectangleInsets; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.general.ValueDataset;
public MeterPlot(); public MeterPlot(ValueDataset dataset); public DialShape getDialShape(); public void setDialShape(DialShape shape); public int getMeterAngle(); public void setMeterAngle(int angle); public Range getRange(); public void setRange(Range range); public double getTickSize(); public void setTickSize(double size); public Paint getTickPaint(); public void setTickPaint(Paint paint); public String getUnits(); public void setUnits(String units); public Paint getNeedlePaint(); public void setNeedlePaint(Paint paint); public boolean getTickLabelsVisible(); public void setTickLabelsVisible(boolean visible); public Font getTickLabelFont(); public void setTickLabelFont(Font font); public Paint getTickLabelPaint(); public void setTickLabelPaint(Paint paint); public NumberFormat getTickLabelFormat(); public void setTickLabelFormat(NumberFormat format); public Font getValueFont(); public void setValueFont(Font font); public Paint getValuePaint(); public void setValuePaint(Paint paint); public Paint getDialBackgroundPaint(); public void setDialBackgroundPaint(Paint paint); public boolean getDrawBorder(); public void setDrawBorder(boolean draw); public Paint getDialOutlinePaint(); public void setDialOutlinePaint(Paint paint); public ValueDataset getDataset(); public void setDataset(ValueDataset dataset); public List getIntervals(); public void addInterval(MeterInterval interval); public void clearIntervals(); public LegendItemCollection getLegendItems(); public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); protected void drawArcForInterval(Graphics2D g2, Rectangle2D meterArea, MeterInterval interval); protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, Stroke stroke); protected void fillArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, boolean dial); public double valueToAngle(double value); protected void drawTicks(Graphics2D g2, Rectangle2D meterArea, double minValue, double maxValue); protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value); protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value, boolean label); protected void drawValueLabel(Graphics2D g2, Rectangle2D area); public String getPlotType(); public void zoom(double percent); public boolean equals(Object obj); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public Object clone() throws CloneNotSupportedException;
216
testEquals
```java import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.RectangleInsets; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.general.ValueDataset; public class MeterPlot extends Plot implements Serializable, Cloneable { private static final long serialVersionUID = 2987472457734470962L; static final Paint DEFAULT_DIAL_BACKGROUND_PAINT = Color.black; static final Paint DEFAULT_NEEDLE_PAINT = Color.green; static final Font DEFAULT_VALUE_FONT = new Font("Tahoma", Font.BOLD, 12); static final Paint DEFAULT_VALUE_PAINT = Color.yellow; public static final int DEFAULT_METER_ANGLE = 270; public static final float DEFAULT_BORDER_SIZE = 3f; public static final float DEFAULT_CIRCLE_SIZE = 10f; public static final Font DEFAULT_LABEL_FONT = new Font("Tahoma", Font.BOLD, 10); private ValueDataset dataset; private DialShape shape; private int meterAngle; private Range range; private double tickSize; private transient Paint tickPaint; private String units; private Font valueFont; private transient Paint valuePaint; private boolean drawBorder; private transient Paint dialOutlinePaint; private transient Paint dialBackgroundPaint; private transient Paint needlePaint; private boolean tickLabelsVisible; private Font tickLabelFont; private transient Paint tickLabelPaint; private NumberFormat tickLabelFormat; protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); private List intervals; public MeterPlot(); public MeterPlot(ValueDataset dataset); public DialShape getDialShape(); public void setDialShape(DialShape shape); public int getMeterAngle(); public void setMeterAngle(int angle); public Range getRange(); public void setRange(Range range); public double getTickSize(); public void setTickSize(double size); public Paint getTickPaint(); public void setTickPaint(Paint paint); public String getUnits(); public void setUnits(String units); public Paint getNeedlePaint(); public void setNeedlePaint(Paint paint); public boolean getTickLabelsVisible(); public void setTickLabelsVisible(boolean visible); public Font getTickLabelFont(); public void setTickLabelFont(Font font); public Paint getTickLabelPaint(); public void setTickLabelPaint(Paint paint); public NumberFormat getTickLabelFormat(); public void setTickLabelFormat(NumberFormat format); public Font getValueFont(); public void setValueFont(Font font); public Paint getValuePaint(); public void setValuePaint(Paint paint); public Paint getDialBackgroundPaint(); public void setDialBackgroundPaint(Paint paint); public boolean getDrawBorder(); public void setDrawBorder(boolean draw); public Paint getDialOutlinePaint(); public void setDialOutlinePaint(Paint paint); public ValueDataset getDataset(); public void setDataset(ValueDataset dataset); public List getIntervals(); public void addInterval(MeterInterval interval); public void clearIntervals(); public LegendItemCollection getLegendItems(); public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); protected void drawArcForInterval(Graphics2D g2, Rectangle2D meterArea, MeterInterval interval); protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, Stroke stroke); protected void fillArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, boolean dial); public double valueToAngle(double value); protected void drawTicks(Graphics2D g2, Rectangle2D meterArea, double minValue, double maxValue); protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value); protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value, boolean label); protected void drawValueLabel(Graphics2D g2, Rectangle2D area); public String getPlotType(); public void zoom(double percent); public boolean equals(Object obj); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.chart.plot.junit; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.plot.DialShape; import org.jfree.chart.plot.MeterInterval; import org.jfree.chart.plot.MeterPlot; import org.jfree.data.Range; import org.jfree.data.general.DefaultValueDataset; public class MeterPlotTests extends TestCase { public static Test suite(); public MeterPlotTests(String name); public void testEquals(); public void testCloning(); public void testSerialization1(); public void testSerialization2(); } ``` You are a professional Java test case writer, please create a test case named `testEquals` for the `MeterPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the equals method to ensure that it can distinguish the required * fields. Note that the dataset is NOT considered in the equals test. */
93
// import org.jfree.chart.text.TextUtilities; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PaintUtilities; // import org.jfree.chart.util.RectangleInsets; // import org.jfree.chart.util.ResourceBundleWrapper; // import org.jfree.chart.util.SerialUtilities; // import org.jfree.data.Range; // import org.jfree.data.event.DatasetChangeEvent; // import org.jfree.data.general.ValueDataset; // // // // public class MeterPlot extends Plot implements Serializable, Cloneable { // private static final long serialVersionUID = 2987472457734470962L; // static final Paint DEFAULT_DIAL_BACKGROUND_PAINT = Color.black; // static final Paint DEFAULT_NEEDLE_PAINT = Color.green; // static final Font DEFAULT_VALUE_FONT = new Font("Tahoma", Font.BOLD, 12); // static final Paint DEFAULT_VALUE_PAINT = Color.yellow; // public static final int DEFAULT_METER_ANGLE = 270; // public static final float DEFAULT_BORDER_SIZE = 3f; // public static final float DEFAULT_CIRCLE_SIZE = 10f; // public static final Font DEFAULT_LABEL_FONT = new Font("Tahoma", // Font.BOLD, 10); // private ValueDataset dataset; // private DialShape shape; // private int meterAngle; // private Range range; // private double tickSize; // private transient Paint tickPaint; // private String units; // private Font valueFont; // private transient Paint valuePaint; // private boolean drawBorder; // private transient Paint dialOutlinePaint; // private transient Paint dialBackgroundPaint; // private transient Paint needlePaint; // private boolean tickLabelsVisible; // private Font tickLabelFont; // private transient Paint tickLabelPaint; // private NumberFormat tickLabelFormat; // protected static ResourceBundle localizationResources = // ResourceBundleWrapper.getBundle( // "org.jfree.chart.plot.LocalizationBundle"); // private List intervals; // // public MeterPlot(); // public MeterPlot(ValueDataset dataset); // public DialShape getDialShape(); // public void setDialShape(DialShape shape); // public int getMeterAngle(); // public void setMeterAngle(int angle); // public Range getRange(); // public void setRange(Range range); // public double getTickSize(); // public void setTickSize(double size); // public Paint getTickPaint(); // public void setTickPaint(Paint paint); // public String getUnits(); // public void setUnits(String units); // public Paint getNeedlePaint(); // public void setNeedlePaint(Paint paint); // public boolean getTickLabelsVisible(); // public void setTickLabelsVisible(boolean visible); // public Font getTickLabelFont(); // public void setTickLabelFont(Font font); // public Paint getTickLabelPaint(); // public void setTickLabelPaint(Paint paint); // public NumberFormat getTickLabelFormat(); // public void setTickLabelFormat(NumberFormat format); // public Font getValueFont(); // public void setValueFont(Font font); // public Paint getValuePaint(); // public void setValuePaint(Paint paint); // public Paint getDialBackgroundPaint(); // public void setDialBackgroundPaint(Paint paint); // public boolean getDrawBorder(); // public void setDrawBorder(boolean draw); // public Paint getDialOutlinePaint(); // public void setDialOutlinePaint(Paint paint); // public ValueDataset getDataset(); // public void setDataset(ValueDataset dataset); // public List getIntervals(); // public void addInterval(MeterInterval interval); // public void clearIntervals(); // public LegendItemCollection getLegendItems(); // public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, // PlotState parentState, // PlotRenderingInfo info); // protected void drawArcForInterval(Graphics2D g2, Rectangle2D meterArea, // MeterInterval interval); // protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue, // double maxValue, Paint paint, Stroke stroke); // protected void fillArc(Graphics2D g2, Rectangle2D area, // double minValue, double maxValue, Paint paint, // boolean dial); // public double valueToAngle(double value); // protected void drawTicks(Graphics2D g2, Rectangle2D meterArea, // double minValue, double maxValue); // protected void drawTick(Graphics2D g2, Rectangle2D meterArea, // double value); // protected void drawTick(Graphics2D g2, Rectangle2D meterArea, // double value, boolean label); // protected void drawValueLabel(Graphics2D g2, Rectangle2D area); // public String getPlotType(); // public void zoom(double percent); // public boolean equals(Object obj); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.chart.plot.junit; // // import java.awt.Color; // import java.awt.Font; // import java.awt.GradientPaint; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import java.text.DecimalFormat; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.plot.DialShape; // import org.jfree.chart.plot.MeterInterval; // import org.jfree.chart.plot.MeterPlot; // import org.jfree.data.Range; // import org.jfree.data.general.DefaultValueDataset; // // // // public class MeterPlotTests extends TestCase { // // // public static Test suite(); // public MeterPlotTests(String name); // public void testEquals(); // public void testCloning(); // public void testSerialization1(); // public void testSerialization2(); // } // You are a professional Java test case writer, please create a test case named `testEquals` for the `MeterPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the equals method to ensure that it can distinguish the required * fields. Note that the dataset is NOT considered in the equals test. */ public void testEquals() {
/** * Test the equals method to ensure that it can distinguish the required * fields. Note that the dataset is NOT considered in the equals test. */
1
org.jfree.chart.plot.MeterPlot
tests
```java import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.RectangleInsets; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.general.ValueDataset; public class MeterPlot extends Plot implements Serializable, Cloneable { private static final long serialVersionUID = 2987472457734470962L; static final Paint DEFAULT_DIAL_BACKGROUND_PAINT = Color.black; static final Paint DEFAULT_NEEDLE_PAINT = Color.green; static final Font DEFAULT_VALUE_FONT = new Font("Tahoma", Font.BOLD, 12); static final Paint DEFAULT_VALUE_PAINT = Color.yellow; public static final int DEFAULT_METER_ANGLE = 270; public static final float DEFAULT_BORDER_SIZE = 3f; public static final float DEFAULT_CIRCLE_SIZE = 10f; public static final Font DEFAULT_LABEL_FONT = new Font("Tahoma", Font.BOLD, 10); private ValueDataset dataset; private DialShape shape; private int meterAngle; private Range range; private double tickSize; private transient Paint tickPaint; private String units; private Font valueFont; private transient Paint valuePaint; private boolean drawBorder; private transient Paint dialOutlinePaint; private transient Paint dialBackgroundPaint; private transient Paint needlePaint; private boolean tickLabelsVisible; private Font tickLabelFont; private transient Paint tickLabelPaint; private NumberFormat tickLabelFormat; protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); private List intervals; public MeterPlot(); public MeterPlot(ValueDataset dataset); public DialShape getDialShape(); public void setDialShape(DialShape shape); public int getMeterAngle(); public void setMeterAngle(int angle); public Range getRange(); public void setRange(Range range); public double getTickSize(); public void setTickSize(double size); public Paint getTickPaint(); public void setTickPaint(Paint paint); public String getUnits(); public void setUnits(String units); public Paint getNeedlePaint(); public void setNeedlePaint(Paint paint); public boolean getTickLabelsVisible(); public void setTickLabelsVisible(boolean visible); public Font getTickLabelFont(); public void setTickLabelFont(Font font); public Paint getTickLabelPaint(); public void setTickLabelPaint(Paint paint); public NumberFormat getTickLabelFormat(); public void setTickLabelFormat(NumberFormat format); public Font getValueFont(); public void setValueFont(Font font); public Paint getValuePaint(); public void setValuePaint(Paint paint); public Paint getDialBackgroundPaint(); public void setDialBackgroundPaint(Paint paint); public boolean getDrawBorder(); public void setDrawBorder(boolean draw); public Paint getDialOutlinePaint(); public void setDialOutlinePaint(Paint paint); public ValueDataset getDataset(); public void setDataset(ValueDataset dataset); public List getIntervals(); public void addInterval(MeterInterval interval); public void clearIntervals(); public LegendItemCollection getLegendItems(); public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); protected void drawArcForInterval(Graphics2D g2, Rectangle2D meterArea, MeterInterval interval); protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, Stroke stroke); protected void fillArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, boolean dial); public double valueToAngle(double value); protected void drawTicks(Graphics2D g2, Rectangle2D meterArea, double minValue, double maxValue); protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value); protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value, boolean label); protected void drawValueLabel(Graphics2D g2, Rectangle2D area); public String getPlotType(); public void zoom(double percent); public boolean equals(Object obj); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.chart.plot.junit; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.plot.DialShape; import org.jfree.chart.plot.MeterInterval; import org.jfree.chart.plot.MeterPlot; import org.jfree.data.Range; import org.jfree.data.general.DefaultValueDataset; public class MeterPlotTests extends TestCase { public static Test suite(); public MeterPlotTests(String name); public void testEquals(); public void testCloning(); public void testSerialization1(); public void testSerialization2(); } ``` You are a professional Java test case writer, please create a test case named `testEquals` for the `MeterPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the equals method to ensure that it can distinguish the required * fields. Note that the dataset is NOT considered in the equals test. */ public void testEquals() { ```
public class MeterPlot extends Plot implements Serializable, Cloneable
package org.jfree.chart.plot.junit; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.plot.DialShape; import org.jfree.chart.plot.MeterInterval; import org.jfree.chart.plot.MeterPlot; import org.jfree.data.Range; import org.jfree.data.general.DefaultValueDataset;
public static Test suite(); public MeterPlotTests(String name); public void testEquals(); public void testCloning(); public void testSerialization1(); public void testSerialization2();
c0f2fbe1094bdf6726dfa25d8ec699d3e09ad7c7dc3ec30461b348879900d02a
[ "org.jfree.chart.plot.junit.MeterPlotTests::testEquals" ]
private static final long serialVersionUID = 2987472457734470962L; static final Paint DEFAULT_DIAL_BACKGROUND_PAINT = Color.black; static final Paint DEFAULT_NEEDLE_PAINT = Color.green; static final Font DEFAULT_VALUE_FONT = new Font("Tahoma", Font.BOLD, 12); static final Paint DEFAULT_VALUE_PAINT = Color.yellow; public static final int DEFAULT_METER_ANGLE = 270; public static final float DEFAULT_BORDER_SIZE = 3f; public static final float DEFAULT_CIRCLE_SIZE = 10f; public static final Font DEFAULT_LABEL_FONT = new Font("Tahoma", Font.BOLD, 10); private ValueDataset dataset; private DialShape shape; private int meterAngle; private Range range; private double tickSize; private transient Paint tickPaint; private String units; private Font valueFont; private transient Paint valuePaint; private boolean drawBorder; private transient Paint dialOutlinePaint; private transient Paint dialBackgroundPaint; private transient Paint needlePaint; private boolean tickLabelsVisible; private Font tickLabelFont; private transient Paint tickLabelPaint; private NumberFormat tickLabelFormat; protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); private List intervals;
public void testEquals()
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * MeterPlotTests.java * ------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 27-Mar-2003 : Version 1 (DG); * 12-May-2004 : Updated testEquals() (DG); * 29-Nov-2007 : Updated testEquals() and testSerialization1() for * dialOutlinePaint (DG) * */ package org.jfree.chart.plot.junit; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.plot.DialShape; import org.jfree.chart.plot.MeterInterval; import org.jfree.chart.plot.MeterPlot; import org.jfree.data.Range; import org.jfree.data.general.DefaultValueDataset; /** * Tests for the {@link MeterPlot} class. */ public class MeterPlotTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(MeterPlotTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public MeterPlotTests(String name) { super(name); } /** * Test the equals method to ensure that it can distinguish the required * fields. Note that the dataset is NOT considered in the equals test. */ public void testEquals() { MeterPlot plot1 = new MeterPlot(); MeterPlot plot2 = new MeterPlot(); assertTrue(plot1.equals(plot2)); // units plot1.setUnits("mph"); assertFalse(plot1.equals(plot2)); plot2.setUnits("mph"); assertTrue(plot1.equals(plot2)); // range plot1.setRange(new Range(50.0, 70.0)); assertFalse(plot1.equals(plot2)); plot2.setRange(new Range(50.0, 70.0)); assertTrue(plot1.equals(plot2)); // interval plot1.addInterval(new MeterInterval("Normal", new Range(55.0, 60.0))); assertFalse(plot1.equals(plot2)); plot2.addInterval(new MeterInterval("Normal", new Range(55.0, 60.0))); assertTrue(plot1.equals(plot2)); // dial outline paint plot1.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertTrue(plot1.equals(plot2)); // dial shape plot1.setDialShape(DialShape.CHORD); assertFalse(plot1.equals(plot2)); plot2.setDialShape(DialShape.CHORD); assertTrue(plot1.equals(plot2)); // dial background paint plot1.setDialBackgroundPaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setDialBackgroundPaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertTrue(plot1.equals(plot2)); // dial outline paint plot1.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.green, 3.0f, 4.0f, Color.red)); assertFalse(plot1.equals(plot2)); plot2.setDialOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.green, 3.0f, 4.0f, Color.red)); assertTrue(plot1.equals(plot2)); // needle paint plot1.setNeedlePaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setNeedlePaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertTrue(plot1.equals(plot2)); // value font plot1.setValueFont(new Font("Serif", Font.PLAIN, 6)); assertFalse(plot1.equals(plot2)); plot2.setValueFont(new Font("Serif", Font.PLAIN, 6)); assertTrue(plot1.equals(plot2)); // value paint plot1.setValuePaint(new GradientPaint(1.0f, 2.0f, Color.black, 3.0f, 4.0f, Color.white)); assertFalse(plot1.equals(plot2)); plot2.setValuePaint(new GradientPaint(1.0f, 2.0f, Color.black, 3.0f, 4.0f, Color.white)); assertTrue(plot1.equals(plot2)); // tick labels visible plot1.setTickLabelsVisible(false); assertFalse(plot1.equals(plot2)); plot2.setTickLabelsVisible(false); assertTrue(plot1.equals(plot2)); // tick label font plot1.setTickLabelFont(new Font("Serif", Font.PLAIN, 6)); assertFalse(plot1.equals(plot2)); plot2.setTickLabelFont(new Font("Serif", Font.PLAIN, 6)); assertTrue(plot1.equals(plot2)); // tick label paint plot1.setTickLabelPaint(Color.red); assertFalse(plot1.equals(plot2)); plot2.setTickLabelPaint(Color.red); assertTrue(plot1.equals(plot2)); // tick label format plot1.setTickLabelFormat(new DecimalFormat("0")); assertFalse(plot1.equals(plot2)); plot2.setTickLabelFormat(new DecimalFormat("0")); assertTrue(plot1.equals(plot2)); // tick paint plot1.setTickPaint(Color.green); assertFalse(plot1.equals(plot2)); plot2.setTickPaint(Color.green); assertTrue(plot1.equals(plot2)); // tick size plot1.setTickSize(1.23); assertFalse(plot1.equals(plot2)); plot2.setTickSize(1.23); assertTrue(plot1.equals(plot2)); // draw border plot1.setDrawBorder(!plot1.getDrawBorder()); assertFalse(plot1.equals(plot2)); plot2.setDrawBorder(plot1.getDrawBorder()); assertTrue(plot1.equals(plot2)); // meter angle plot1.setMeterAngle(22); assertFalse(plot1.equals(plot2)); plot2.setMeterAngle(22); assertTrue(plot1.equals(plot2)); } /** * Confirm that cloning works. */ public void testCloning() { MeterPlot p1 = new MeterPlot(); MeterPlot p2 = null; try { p2 = (MeterPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); // the clone and the original share a reference to the SAME dataset assertTrue(p1.getDataset() == p2.getDataset()); // try a few checks to ensure that the clone is independent of the // original p1.getTickLabelFormat().setMinimumIntegerDigits(99); assertFalse(p1.equals(p2)); p2.getTickLabelFormat().setMinimumIntegerDigits(99); assertTrue(p1.equals(p2)); p1.addInterval(new MeterInterval("Test", new Range(1.234, 5.678))); assertFalse(p1.equals(p2)); p2.addInterval(new MeterInterval("Test", new Range(1.234, 5.678))); assertTrue(p1.equals(p2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization1() { MeterPlot p1 = new MeterPlot(null); p1.setDialBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); p1.setDialOutlinePaint(new GradientPaint(4.0f, 3.0f, Color.red, 2.0f, 1.0f, Color.blue)); p1.setNeedlePaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); p1.setTickLabelPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); p1.setTickPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); MeterPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); p2 = (MeterPlot) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(p1, p2); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization2() { MeterPlot p1 = new MeterPlot(new DefaultValueDataset(1.23)); MeterPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); p2 = (MeterPlot) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(p1, p2); } }
[ { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "addInterval", "be_test_function_signature": "(Lorg/jfree/chart/plot/MeterInterval;)V", "line_numbers": [ "757", "758", "760", "761", "762" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "equals", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "1212", "1213", "1215", "1216", "1218", "1219", "1221", "1222", "1223", "1225", "1226", "1228", "1229", "1231", "1233", "1235", "1236", "1238", "1240", "1242", "1243", "1245", "1246", "1248", "1249", "1251", "1252", "1254", "1255", "1257", "1258", "1260", "1261", "1263", "1264", "1266", "1268", "1270", "1271", "1273", "1274", "1276" ], "method_line_rate": 0.9285714285714286 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "getDrawBorder", "be_test_function_signature": "()Z", "line_numbers": [ "651" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setDataset", "be_test_function_signature": "(Lorg/jfree/data/general/ValueDataset;)V", "line_numbers": [ "716", "717", "718", "722", "723", "724", "725", "729", "732", "734" ], "method_line_rate": 0.7 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setDialBackgroundPaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "638", "639", "640" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setDialOutlinePaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "689", "690", "691" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setDialShape", "be_test_function_signature": "(Lorg/jfree/chart/plot/DialShape;)V", "line_numbers": [ "279", "280", "282", "283", "284" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setDrawBorder", "be_test_function_signature": "(Z)V", "line_numbers": [ "665", "666", "667" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setMeterAngle", "be_test_function_signature": "(I)V", "line_numbers": [ "307", "308", "311", "312", "313" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setNeedlePaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "446", "447", "449", "450", "451" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setRange", "be_test_function_signature": "(Lorg/jfree/data/Range;)V", "line_numbers": [ "336", "337", "339", "340", "343", "344", "345" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setTickLabelFont", "be_test_function_signature": "(Ljava/awt/Font;)V", "line_numbers": [ "499", "500", "502", "503", "504", "506" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setTickLabelFormat", "be_test_function_signature": "(Ljava/text/NumberFormat;)V", "line_numbers": [ "557", "558", "560", "561", "562" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setTickLabelPaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "528", "529", "531", "532", "533", "535" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setTickLabelsVisible", "be_test_function_signature": "(Z)V", "line_numbers": [ "473", "474", "475", "477" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setTickPaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "395", "396", "398", "399", "400" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setTickSize", "be_test_function_signature": "(D)V", "line_numbers": [ "367", "368", "370", "371", "372" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setUnits", "be_test_function_signature": "(Ljava/lang/String;)V", "line_numbers": [ "422", "423", "424" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setValueFont", "be_test_function_signature": "(Ljava/awt/Font;)V", "line_numbers": [ "584", "585", "587", "588", "589" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/MeterPlot.java", "be_test_class_name": "org.jfree.chart.plot.MeterPlot", "be_test_function_name": "setValuePaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "611", "612", "614", "615", "616" ], "method_line_rate": 0.8 } ]
public class FilterIteratorTest<E> extends AbstractIteratorTest<E>
@SuppressWarnings("unchecked") public void testSetIterator() { final Iterator<E> iter1 = Collections.singleton((E) new Object()).iterator(); final Iterator<E> iter2 = Collections.<E>emptyList().iterator(); final FilterIterator<E> filterIterator = new FilterIterator<E>(iter1); filterIterator.setPredicate(truePredicate()); // this iterator has elements assertEquals(true, filterIterator.hasNext()); // this iterator has no elements filterIterator.setIterator(iter2); assertEquals(false, filterIterator.hasNext()); }
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // import org.apache.commons.collections4.Predicate; // // // // public class FilterIterator<E> implements Iterator<E> { // private Iterator<? extends E> iterator; // private Predicate<? super E> predicate; // private E nextObject; // private boolean nextObjectSet = false; // // public FilterIterator(); // public FilterIterator(final Iterator<? extends E> iterator); // public FilterIterator(final Iterator<? extends E> iterator, final Predicate<? super E> predicate); // @Override // public boolean hasNext(); // @Override // public E next(); // @Override // public void remove(); // public Iterator<? extends E> getIterator(); // public void setIterator(final Iterator<? extends E> iterator); // public Predicate<? super E> getPredicate(); // public void setPredicate(final Predicate<? super E> predicate); // private boolean setNextObject(); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.iterators; // // import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.Iterator; // import java.util.List; // import java.util.NoSuchElementException; // import org.apache.commons.collections4.Predicate; // import org.apache.commons.collections4.functors.NotNullPredicate; // // // // public class FilterIteratorTest<E> extends AbstractIteratorTest<E> { // private String[] array; // private List<E> list; // private FilterIterator<E> iterator; // // public FilterIteratorTest(final String name); // @Override // public void setUp(); // @Override // public void tearDown() throws Exception; // @Override // public FilterIterator<E> makeEmptyIterator(); // @Override // @SuppressWarnings("unchecked") // public FilterIterator<E> makeObject(); // public void testRepeatedHasNext(); // @SuppressWarnings("unused") // public void testRepeatedNext(); // public void testReturnValues(); // @SuppressWarnings("unchecked") // public void testSetIterator(); // public void testSetPredicate(); // private void verifyNoMoreElements(); // private void verifyElementsInPredicate(final String[] elements); // private void initIterator(); // protected FilterIterator<E> makePassThroughFilter(final Iterator<E> i); // protected FilterIterator<E> makeBlockAllFilter(final Iterator<E> i); // @Override // public boolean evaluate(final E x); // @Override // public boolean evaluate(final E x); // @Override // public boolean evaluate(final E x); // } // You are a professional Java test case writer, please create a test case named `testSetIterator` for the `FilterIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test that when the iterator is changed, the hasNext method returns the * correct response for the new iterator. */
src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java
package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate;
public FilterIterator(); public FilterIterator(final Iterator<? extends E> iterator); public FilterIterator(final Iterator<? extends E> iterator, final Predicate<? super E> predicate); @Override public boolean hasNext(); @Override public E next(); @Override public void remove(); public Iterator<? extends E> getIterator(); public void setIterator(final Iterator<? extends E> iterator); public Predicate<? super E> getPredicate(); public void setPredicate(final Predicate<? super E> predicate); private boolean setNextObject();
129
testSetIterator
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate; public class FilterIterator<E> implements Iterator<E> { private Iterator<? extends E> iterator; private Predicate<? super E> predicate; private E nextObject; private boolean nextObjectSet = false; public FilterIterator(); public FilterIterator(final Iterator<? extends E> iterator); public FilterIterator(final Iterator<? extends E> iterator, final Predicate<? super E> predicate); @Override public boolean hasNext(); @Override public E next(); @Override public void remove(); public Iterator<? extends E> getIterator(); public void setIterator(final Iterator<? extends E> iterator); public Predicate<? super E> getPredicate(); public void setPredicate(final Predicate<? super E> predicate); private boolean setNextObject(); } // Abstract Java Test Class package org.apache.commons.collections4.iterators; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.NotNullPredicate; public class FilterIteratorTest<E> extends AbstractIteratorTest<E> { private String[] array; private List<E> list; private FilterIterator<E> iterator; public FilterIteratorTest(final String name); @Override public void setUp(); @Override public void tearDown() throws Exception; @Override public FilterIterator<E> makeEmptyIterator(); @Override @SuppressWarnings("unchecked") public FilterIterator<E> makeObject(); public void testRepeatedHasNext(); @SuppressWarnings("unused") public void testRepeatedNext(); public void testReturnValues(); @SuppressWarnings("unchecked") public void testSetIterator(); public void testSetPredicate(); private void verifyNoMoreElements(); private void verifyElementsInPredicate(final String[] elements); private void initIterator(); protected FilterIterator<E> makePassThroughFilter(final Iterator<E> i); protected FilterIterator<E> makeBlockAllFilter(final Iterator<E> i); @Override public boolean evaluate(final E x); @Override public boolean evaluate(final E x); @Override public boolean evaluate(final E x); } ``` You are a professional Java test case writer, please create a test case named `testSetIterator` for the `FilterIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test that when the iterator is changed, the hasNext method returns the * correct response for the new iterator. */
116
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // import org.apache.commons.collections4.Predicate; // // // // public class FilterIterator<E> implements Iterator<E> { // private Iterator<? extends E> iterator; // private Predicate<? super E> predicate; // private E nextObject; // private boolean nextObjectSet = false; // // public FilterIterator(); // public FilterIterator(final Iterator<? extends E> iterator); // public FilterIterator(final Iterator<? extends E> iterator, final Predicate<? super E> predicate); // @Override // public boolean hasNext(); // @Override // public E next(); // @Override // public void remove(); // public Iterator<? extends E> getIterator(); // public void setIterator(final Iterator<? extends E> iterator); // public Predicate<? super E> getPredicate(); // public void setPredicate(final Predicate<? super E> predicate); // private boolean setNextObject(); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.iterators; // // import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.Iterator; // import java.util.List; // import java.util.NoSuchElementException; // import org.apache.commons.collections4.Predicate; // import org.apache.commons.collections4.functors.NotNullPredicate; // // // // public class FilterIteratorTest<E> extends AbstractIteratorTest<E> { // private String[] array; // private List<E> list; // private FilterIterator<E> iterator; // // public FilterIteratorTest(final String name); // @Override // public void setUp(); // @Override // public void tearDown() throws Exception; // @Override // public FilterIterator<E> makeEmptyIterator(); // @Override // @SuppressWarnings("unchecked") // public FilterIterator<E> makeObject(); // public void testRepeatedHasNext(); // @SuppressWarnings("unused") // public void testRepeatedNext(); // public void testReturnValues(); // @SuppressWarnings("unchecked") // public void testSetIterator(); // public void testSetPredicate(); // private void verifyNoMoreElements(); // private void verifyElementsInPredicate(final String[] elements); // private void initIterator(); // protected FilterIterator<E> makePassThroughFilter(final Iterator<E> i); // protected FilterIterator<E> makeBlockAllFilter(final Iterator<E> i); // @Override // public boolean evaluate(final E x); // @Override // public boolean evaluate(final E x); // @Override // public boolean evaluate(final E x); // } // You are a professional Java test case writer, please create a test case named `testSetIterator` for the `FilterIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test that when the iterator is changed, the hasNext method returns the * correct response for the new iterator. */ @SuppressWarnings("unchecked") public void testSetIterator() {
/** * Test that when the iterator is changed, the hasNext method returns the * correct response for the new iterator. */
28
org.apache.commons.collections4.iterators.FilterIterator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate; public class FilterIterator<E> implements Iterator<E> { private Iterator<? extends E> iterator; private Predicate<? super E> predicate; private E nextObject; private boolean nextObjectSet = false; public FilterIterator(); public FilterIterator(final Iterator<? extends E> iterator); public FilterIterator(final Iterator<? extends E> iterator, final Predicate<? super E> predicate); @Override public boolean hasNext(); @Override public E next(); @Override public void remove(); public Iterator<? extends E> getIterator(); public void setIterator(final Iterator<? extends E> iterator); public Predicate<? super E> getPredicate(); public void setPredicate(final Predicate<? super E> predicate); private boolean setNextObject(); } // Abstract Java Test Class package org.apache.commons.collections4.iterators; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.NotNullPredicate; public class FilterIteratorTest<E> extends AbstractIteratorTest<E> { private String[] array; private List<E> list; private FilterIterator<E> iterator; public FilterIteratorTest(final String name); @Override public void setUp(); @Override public void tearDown() throws Exception; @Override public FilterIterator<E> makeEmptyIterator(); @Override @SuppressWarnings("unchecked") public FilterIterator<E> makeObject(); public void testRepeatedHasNext(); @SuppressWarnings("unused") public void testRepeatedNext(); public void testReturnValues(); @SuppressWarnings("unchecked") public void testSetIterator(); public void testSetPredicate(); private void verifyNoMoreElements(); private void verifyElementsInPredicate(final String[] elements); private void initIterator(); protected FilterIterator<E> makePassThroughFilter(final Iterator<E> i); protected FilterIterator<E> makeBlockAllFilter(final Iterator<E> i); @Override public boolean evaluate(final E x); @Override public boolean evaluate(final E x); @Override public boolean evaluate(final E x); } ``` You are a professional Java test case writer, please create a test case named `testSetIterator` for the `FilterIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test that when the iterator is changed, the hasNext method returns the * correct response for the new iterator. */ @SuppressWarnings("unchecked") public void testSetIterator() { ```
public class FilterIterator<E> implements Iterator<E>
package org.apache.commons.collections4.iterators; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.NotNullPredicate;
public FilterIteratorTest(final String name); @Override public void setUp(); @Override public void tearDown() throws Exception; @Override public FilterIterator<E> makeEmptyIterator(); @Override @SuppressWarnings("unchecked") public FilterIterator<E> makeObject(); public void testRepeatedHasNext(); @SuppressWarnings("unused") public void testRepeatedNext(); public void testReturnValues(); @SuppressWarnings("unchecked") public void testSetIterator(); public void testSetPredicate(); private void verifyNoMoreElements(); private void verifyElementsInPredicate(final String[] elements); private void initIterator(); protected FilterIterator<E> makePassThroughFilter(final Iterator<E> i); protected FilterIterator<E> makeBlockAllFilter(final Iterator<E> i); @Override public boolean evaluate(final E x); @Override public boolean evaluate(final E x); @Override public boolean evaluate(final E x);
c1a50a1e01f6672852fe3bc7eeae7a11381888e75be3a9b9b14cf080ec0df517
[ "org.apache.commons.collections4.iterators.FilterIteratorTest::testSetIterator" ]
private Iterator<? extends E> iterator; private Predicate<? super E> predicate; private E nextObject; private boolean nextObjectSet = false;
@SuppressWarnings("unchecked") public void testSetIterator()
private String[] array; private List<E> list; private FilterIterator<E> iterator;
Collections
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.NotNullPredicate; /** * Test the filter iterator. * * @version $Id$ */ public class FilterIteratorTest<E> extends AbstractIteratorTest<E> { /** Creates new TestFilterIterator */ public FilterIteratorTest(final String name) { super(name); } private String[] array; private List<E> list; private FilterIterator<E> iterator; /** * Set up instance variables required by this test case. */ @Override public void setUp() { array = new String[] { "a", "b", "c" }; initIterator(); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() throws Exception { iterator = null; } /** * Returns an full iterator wrapped in a * FilterIterator that blocks all the elements * * @return "empty" FilterIterator */ @Override public FilterIterator<E> makeEmptyIterator() { return makeBlockAllFilter(new ArrayIterator<E>(array)); } /** * Returns an array with elements wrapped in a pass-through * FilterIterator * * @return a filtered iterator */ @Override @SuppressWarnings("unchecked") public FilterIterator<E> makeObject() { list = new ArrayList<E>(Arrays.asList((E[]) array)); return makePassThroughFilter(list.iterator()); } public void testRepeatedHasNext() { for (int i = 0; i <= array.length; i++) { assertTrue(iterator.hasNext()); } } @SuppressWarnings("unused") public void testRepeatedNext() { for (final String element : array) { iterator.next(); } verifyNoMoreElements(); } public void testReturnValues() { verifyElementsInPredicate(new String[0]); verifyElementsInPredicate(new String[] { "a" }); verifyElementsInPredicate(new String[] { "b" }); verifyElementsInPredicate(new String[] { "c" }); verifyElementsInPredicate(new String[] { "a", "b" }); verifyElementsInPredicate(new String[] { "a", "c" }); verifyElementsInPredicate(new String[] { "b", "c" }); verifyElementsInPredicate(new String[] { "a", "b", "c" }); } /** * Test that when the iterator is changed, the hasNext method returns the * correct response for the new iterator. */ @SuppressWarnings("unchecked") public void testSetIterator() { final Iterator<E> iter1 = Collections.singleton((E) new Object()).iterator(); final Iterator<E> iter2 = Collections.<E>emptyList().iterator(); final FilterIterator<E> filterIterator = new FilterIterator<E>(iter1); filterIterator.setPredicate(truePredicate()); // this iterator has elements assertEquals(true, filterIterator.hasNext()); // this iterator has no elements filterIterator.setIterator(iter2); assertEquals(false, filterIterator.hasNext()); } /** * Test that when the predicate is changed, the hasNext method returns the * correct response for the new predicate. */ public void testSetPredicate() { final Iterator<E> iter = Collections.singleton((E) null).iterator(); final FilterIterator<E> filterIterator = new FilterIterator<E>(iter); filterIterator.setPredicate(truePredicate()); // this predicate matches assertEquals(true, filterIterator.hasNext()); // this predicate doesn't match filterIterator.setPredicate(NotNullPredicate.notNullPredicate()); assertEquals(false, filterIterator.hasNext()); } private void verifyNoMoreElements() { assertTrue(!iterator.hasNext()); try { iterator.next(); fail("NoSuchElementException expected"); } catch (final NoSuchElementException e) { // success } } private void verifyElementsInPredicate(final String[] elements) { final Predicate<E> pred = new Predicate<E>() { @Override public boolean evaluate(final E x) { for (final String element : elements) { if (element.equals(x)) { return true; } } return false; } }; initIterator(); iterator.setPredicate(pred); for (int i = 0; i < elements.length; i++) { final String s = (String)iterator.next(); assertEquals(elements[i], s); assertTrue(i == elements.length - 1 ? !iterator.hasNext() : iterator.hasNext()); } verifyNoMoreElements(); // test removal initIterator(); iterator.setPredicate(pred); if (iterator.hasNext()) { final Object last = iterator.next(); iterator.remove(); assertTrue("Base of FilterIterator still contains removed element.", !list.contains(last)); } } private void initIterator() { iterator = makeObject(); } /** * Returns a FilterIterator that does not filter * any of its elements * * @param i the Iterator to "filter" * @return "filtered" iterator */ protected FilterIterator<E> makePassThroughFilter(final Iterator<E> i) { final Predicate<E> pred = new Predicate<E>() { @Override public boolean evaluate(final E x) { return true; } }; return new FilterIterator<E>(i, pred); } /** * Returns a FilterIterator that blocks * all of its elements * * @param i the Iterator to "filter" * @return "filtered" iterator */ protected FilterIterator<E> makeBlockAllFilter(final Iterator<E> i) { final Predicate<E> pred = new Predicate<E>() { @Override public boolean evaluate(final E x) { return false; } }; return new FilterIterator<E>(i, pred); } }
[ { "be_test_class_file": "org/apache/commons/collections4/iterators/FilterIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.FilterIterator", "be_test_function_name": "hasNext", "be_test_function_signature": "()Z", "line_numbers": [ "87" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/FilterIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.FilterIterator", "be_test_function_name": "setIterator", "be_test_function_signature": "(Ljava/util/Iterator;)V", "line_numbers": [ "145", "146", "147", "148" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/FilterIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.FilterIterator", "be_test_function_name": "setNextObject", "be_test_function_signature": "()Z", "line_numbers": [ "177", "178", "179", "180", "181", "182", "184", "185" ], "method_line_rate": 0.875 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/FilterIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.FilterIterator", "be_test_function_name": "setPredicate", "be_test_function_signature": "(Lorg/apache/commons/collections4/Predicate;)V", "line_numbers": [ "166", "167", "168", "169" ], "method_line_rate": 1 } ]
public class ExternExportsPassTest extends TestCase
public void testUseExportsAsExterns() { String librarySource = "/**\n" + " * @param {number} a\n" + " * @constructor\n" + " */\n" + "var InternalName = function(a) {" + "};" + "goog.exportSymbol('ExternalName', InternalName)"; String clientSource = "var a = new ExternalName(6);\n" + "/**\n" + " * @param {ExternalName} x\n" + " */\n" + "var b = function(x) {};"; Result libraryCompileResult = compileAndExportExterns(librarySource); assertEquals(0, libraryCompileResult.warnings.length); assertEquals(0, libraryCompileResult.errors.length); String generatedExterns = libraryCompileResult.externExport; Result clientCompileResult = compileAndExportExterns(clientSource, generatedExterns); assertEquals(0, clientCompileResult.warnings.length); assertEquals(0, clientCompileResult.errors.length); }
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Joiner; // import com.google.common.base.Preconditions; // import com.google.common.collect.Iterables; // import com.google.common.collect.Lists; // import com.google.common.collect.Maps; // import com.google.common.collect.Sets; // import com.google.javascript.rhino.IR; // import com.google.javascript.rhino.JSDocInfo; // import com.google.javascript.rhino.Node; // import com.google.javascript.rhino.Token; // import java.util.Comparator; // import java.util.List; // import java.util.Map; // import java.util.Set; // import java.util.TreeSet; // // // // final class ExternExportsPass extends NodeTraversal.AbstractPostOrderCallback // implements CompilerPass { // private final List<Export> exports; // private final Map<String, Node> definitionMap; // private final AbstractCompiler compiler; // private final Node externsRoot; // private final Map<String, String> mappedPaths; // private final Set<String> alreadyExportedPaths; // private List<String> exportSymbolFunctionNames; // private List<String> exportPropertyFunctionNames; // // ExternExportsPass(AbstractCompiler compiler); // private void initExportMethods(); // @Override // public void process(Node externs, Node root); // public String getGeneratedExterns(); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private void handleSymbolExport(Node parent); // private void handlePropertyExport(Node parent); // Export(String symbolName, Node value); // void generateExterns(); // abstract String getExportedPath(); // void appendExtern(String path, Node valueToExport); // private List<String> computePathPrefixes(String path); // private void appendPathDefinition(String path, Node initializer); // private Node createExternFunction(Node exportedFunction); // private Node createExternObjectLit(Node exportedObjectLit); // protected Node getValue(Node qualifiedNameNode); // public SymbolExport(String symbolName, Node value); // @Override // String getExportedPath(); // public PropertyExport(String exportPath, String symbolName, Node value); // @Override // String getExportedPath(); // @Override // public int compare(Export e1, Export e2); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // import com.google.common.base.Joiner; // import com.google.common.collect.Lists; // import junit.framework.TestCase; // import java.util.List; // // // // public class ExternExportsPassTest extends TestCase { // private boolean runCheckTypes = true; // // private void setRunCheckTypes(boolean shouldRunCheckTypes); // @Override // public void setUp() throws Exception; // public void testExportSymbol() throws Exception; // public void testExportSymbolDefinedInVar() throws Exception; // public void testExportProperty() throws Exception; // public void testExportMultiple() throws Exception; // public void testExportMultiple2() throws Exception; // public void testExportMultiple3() throws Exception; // public void testExportNonStaticSymbol() throws Exception; // public void testExportNonStaticSymbol2() throws Exception; // public void testExportNonexistentProperty() throws Exception; // public void testExportSymbolWithTypeAnnotation(); // public void testExportSymbolWithTemplateAnnotation(); // public void testExportSymbolWithMultipleTemplateAnnotation(); // public void testExportSymbolWithoutTypeCheck(); // public void testExportSymbolWithConstructor(); // public void testExportSymbolWithConstructorWithoutTypeCheck(); // public void testExportFunctionWithOptionalArguments1(); // public void testExportFunctionWithOptionalArguments2(); // public void testExportFunctionWithOptionalArguments3(); // public void testExportFunctionWithVariableArguments(); // public void testExportEnum(); // public void testExportDontEmitPrototypePathPrefix(); // public void testUseExportsAsExterns(); // public void testDontWarnOnExportFunctionWithUnknownReturnType(); // public void testDontWarnOnExportConstructorWithUnknownReturnType(); // public void testTypedef(); // public void testExportParamWithNull() throws Exception; // public void testExportConstructor() throws Exception; // public void testExportParamWithSymbolDefinedInFunction() throws Exception; // public void testExportSymbolWithFunctionDefinedAsFunction(); // public void testExportSymbolWithFunctionAlias(); // private void compileAndCheck(String js, String expected); // public void testDontWarnOnExportFunctionWithUnknownParameterTypes(); // private Result compileAndExportExterns(String js); // private Result compileAndExportExterns(String js, String externs); // } // You are a professional Java test case writer, please create a test case named `testUseExportsAsExterns` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the workflow of creating an externs file for a library * via the export pass and then using that externs file in a client. * * There should be no warnings in the client if the library includes * type information for the exported functions and the client uses them * correctly. */
test/com/google/javascript/jscomp/ExternExportsPassTest.java
package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet;
ExternExportsPass(AbstractCompiler compiler); private void initExportMethods(); @Override public void process(Node externs, Node root); public String getGeneratedExterns(); @Override public void visit(NodeTraversal t, Node n, Node parent); private void handleSymbolExport(Node parent); private void handlePropertyExport(Node parent); Export(String symbolName, Node value); void generateExterns(); abstract String getExportedPath(); void appendExtern(String path, Node valueToExport); private List<String> computePathPrefixes(String path); private void appendPathDefinition(String path, Node initializer); private Node createExternFunction(Node exportedFunction); private Node createExternObjectLit(Node exportedObjectLit); protected Node getValue(Node qualifiedNameNode); public SymbolExport(String symbolName, Node value); @Override String getExportedPath(); public PropertyExport(String exportPath, String symbolName, Node value); @Override String getExportedPath(); @Override public int compare(Export e1, Export e2);
440
testUseExportsAsExterns
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; final class ExternExportsPass extends NodeTraversal.AbstractPostOrderCallback implements CompilerPass { private final List<Export> exports; private final Map<String, Node> definitionMap; private final AbstractCompiler compiler; private final Node externsRoot; private final Map<String, String> mappedPaths; private final Set<String> alreadyExportedPaths; private List<String> exportSymbolFunctionNames; private List<String> exportPropertyFunctionNames; ExternExportsPass(AbstractCompiler compiler); private void initExportMethods(); @Override public void process(Node externs, Node root); public String getGeneratedExterns(); @Override public void visit(NodeTraversal t, Node n, Node parent); private void handleSymbolExport(Node parent); private void handlePropertyExport(Node parent); Export(String symbolName, Node value); void generateExterns(); abstract String getExportedPath(); void appendExtern(String path, Node valueToExport); private List<String> computePathPrefixes(String path); private void appendPathDefinition(String path, Node initializer); private Node createExternFunction(Node exportedFunction); private Node createExternObjectLit(Node exportedObjectLit); protected Node getValue(Node qualifiedNameNode); public SymbolExport(String symbolName, Node value); @Override String getExportedPath(); public PropertyExport(String exportPath, String symbolName, Node value); @Override String getExportedPath(); @Override public int compare(Export e1, Export e2); } // Abstract Java Test Class package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.util.List; public class ExternExportsPassTest extends TestCase { private boolean runCheckTypes = true; private void setRunCheckTypes(boolean shouldRunCheckTypes); @Override public void setUp() throws Exception; public void testExportSymbol() throws Exception; public void testExportSymbolDefinedInVar() throws Exception; public void testExportProperty() throws Exception; public void testExportMultiple() throws Exception; public void testExportMultiple2() throws Exception; public void testExportMultiple3() throws Exception; public void testExportNonStaticSymbol() throws Exception; public void testExportNonStaticSymbol2() throws Exception; public void testExportNonexistentProperty() throws Exception; public void testExportSymbolWithTypeAnnotation(); public void testExportSymbolWithTemplateAnnotation(); public void testExportSymbolWithMultipleTemplateAnnotation(); public void testExportSymbolWithoutTypeCheck(); public void testExportSymbolWithConstructor(); public void testExportSymbolWithConstructorWithoutTypeCheck(); public void testExportFunctionWithOptionalArguments1(); public void testExportFunctionWithOptionalArguments2(); public void testExportFunctionWithOptionalArguments3(); public void testExportFunctionWithVariableArguments(); public void testExportEnum(); public void testExportDontEmitPrototypePathPrefix(); public void testUseExportsAsExterns(); public void testDontWarnOnExportFunctionWithUnknownReturnType(); public void testDontWarnOnExportConstructorWithUnknownReturnType(); public void testTypedef(); public void testExportParamWithNull() throws Exception; public void testExportConstructor() throws Exception; public void testExportParamWithSymbolDefinedInFunction() throws Exception; public void testExportSymbolWithFunctionDefinedAsFunction(); public void testExportSymbolWithFunctionAlias(); private void compileAndCheck(String js, String expected); public void testDontWarnOnExportFunctionWithUnknownParameterTypes(); private Result compileAndExportExterns(String js); private Result compileAndExportExterns(String js, String externs); } ``` You are a professional Java test case writer, please create a test case named `testUseExportsAsExterns` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the workflow of creating an externs file for a library * via the export pass and then using that externs file in a client. * * There should be no warnings in the client if the library includes * type information for the exported functions and the client uses them * correctly. */
411
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Joiner; // import com.google.common.base.Preconditions; // import com.google.common.collect.Iterables; // import com.google.common.collect.Lists; // import com.google.common.collect.Maps; // import com.google.common.collect.Sets; // import com.google.javascript.rhino.IR; // import com.google.javascript.rhino.JSDocInfo; // import com.google.javascript.rhino.Node; // import com.google.javascript.rhino.Token; // import java.util.Comparator; // import java.util.List; // import java.util.Map; // import java.util.Set; // import java.util.TreeSet; // // // // final class ExternExportsPass extends NodeTraversal.AbstractPostOrderCallback // implements CompilerPass { // private final List<Export> exports; // private final Map<String, Node> definitionMap; // private final AbstractCompiler compiler; // private final Node externsRoot; // private final Map<String, String> mappedPaths; // private final Set<String> alreadyExportedPaths; // private List<String> exportSymbolFunctionNames; // private List<String> exportPropertyFunctionNames; // // ExternExportsPass(AbstractCompiler compiler); // private void initExportMethods(); // @Override // public void process(Node externs, Node root); // public String getGeneratedExterns(); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private void handleSymbolExport(Node parent); // private void handlePropertyExport(Node parent); // Export(String symbolName, Node value); // void generateExterns(); // abstract String getExportedPath(); // void appendExtern(String path, Node valueToExport); // private List<String> computePathPrefixes(String path); // private void appendPathDefinition(String path, Node initializer); // private Node createExternFunction(Node exportedFunction); // private Node createExternObjectLit(Node exportedObjectLit); // protected Node getValue(Node qualifiedNameNode); // public SymbolExport(String symbolName, Node value); // @Override // String getExportedPath(); // public PropertyExport(String exportPath, String symbolName, Node value); // @Override // String getExportedPath(); // @Override // public int compare(Export e1, Export e2); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // import com.google.common.base.Joiner; // import com.google.common.collect.Lists; // import junit.framework.TestCase; // import java.util.List; // // // // public class ExternExportsPassTest extends TestCase { // private boolean runCheckTypes = true; // // private void setRunCheckTypes(boolean shouldRunCheckTypes); // @Override // public void setUp() throws Exception; // public void testExportSymbol() throws Exception; // public void testExportSymbolDefinedInVar() throws Exception; // public void testExportProperty() throws Exception; // public void testExportMultiple() throws Exception; // public void testExportMultiple2() throws Exception; // public void testExportMultiple3() throws Exception; // public void testExportNonStaticSymbol() throws Exception; // public void testExportNonStaticSymbol2() throws Exception; // public void testExportNonexistentProperty() throws Exception; // public void testExportSymbolWithTypeAnnotation(); // public void testExportSymbolWithTemplateAnnotation(); // public void testExportSymbolWithMultipleTemplateAnnotation(); // public void testExportSymbolWithoutTypeCheck(); // public void testExportSymbolWithConstructor(); // public void testExportSymbolWithConstructorWithoutTypeCheck(); // public void testExportFunctionWithOptionalArguments1(); // public void testExportFunctionWithOptionalArguments2(); // public void testExportFunctionWithOptionalArguments3(); // public void testExportFunctionWithVariableArguments(); // public void testExportEnum(); // public void testExportDontEmitPrototypePathPrefix(); // public void testUseExportsAsExterns(); // public void testDontWarnOnExportFunctionWithUnknownReturnType(); // public void testDontWarnOnExportConstructorWithUnknownReturnType(); // public void testTypedef(); // public void testExportParamWithNull() throws Exception; // public void testExportConstructor() throws Exception; // public void testExportParamWithSymbolDefinedInFunction() throws Exception; // public void testExportSymbolWithFunctionDefinedAsFunction(); // public void testExportSymbolWithFunctionAlias(); // private void compileAndCheck(String js, String expected); // public void testDontWarnOnExportFunctionWithUnknownParameterTypes(); // private Result compileAndExportExterns(String js); // private Result compileAndExportExterns(String js, String externs); // } // You are a professional Java test case writer, please create a test case named `testUseExportsAsExterns` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the workflow of creating an externs file for a library * via the export pass and then using that externs file in a client. * * There should be no warnings in the client if the library includes * type information for the exported functions and the client uses them * correctly. */ public void testUseExportsAsExterns() {
/** * Test the workflow of creating an externs file for a library * via the export pass and then using that externs file in a client. * * There should be no warnings in the client if the library includes * type information for the exported functions and the client uses them * correctly. */
107
com.google.javascript.jscomp.ExternExportsPass
test
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; final class ExternExportsPass extends NodeTraversal.AbstractPostOrderCallback implements CompilerPass { private final List<Export> exports; private final Map<String, Node> definitionMap; private final AbstractCompiler compiler; private final Node externsRoot; private final Map<String, String> mappedPaths; private final Set<String> alreadyExportedPaths; private List<String> exportSymbolFunctionNames; private List<String> exportPropertyFunctionNames; ExternExportsPass(AbstractCompiler compiler); private void initExportMethods(); @Override public void process(Node externs, Node root); public String getGeneratedExterns(); @Override public void visit(NodeTraversal t, Node n, Node parent); private void handleSymbolExport(Node parent); private void handlePropertyExport(Node parent); Export(String symbolName, Node value); void generateExterns(); abstract String getExportedPath(); void appendExtern(String path, Node valueToExport); private List<String> computePathPrefixes(String path); private void appendPathDefinition(String path, Node initializer); private Node createExternFunction(Node exportedFunction); private Node createExternObjectLit(Node exportedObjectLit); protected Node getValue(Node qualifiedNameNode); public SymbolExport(String symbolName, Node value); @Override String getExportedPath(); public PropertyExport(String exportPath, String symbolName, Node value); @Override String getExportedPath(); @Override public int compare(Export e1, Export e2); } // Abstract Java Test Class package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.util.List; public class ExternExportsPassTest extends TestCase { private boolean runCheckTypes = true; private void setRunCheckTypes(boolean shouldRunCheckTypes); @Override public void setUp() throws Exception; public void testExportSymbol() throws Exception; public void testExportSymbolDefinedInVar() throws Exception; public void testExportProperty() throws Exception; public void testExportMultiple() throws Exception; public void testExportMultiple2() throws Exception; public void testExportMultiple3() throws Exception; public void testExportNonStaticSymbol() throws Exception; public void testExportNonStaticSymbol2() throws Exception; public void testExportNonexistentProperty() throws Exception; public void testExportSymbolWithTypeAnnotation(); public void testExportSymbolWithTemplateAnnotation(); public void testExportSymbolWithMultipleTemplateAnnotation(); public void testExportSymbolWithoutTypeCheck(); public void testExportSymbolWithConstructor(); public void testExportSymbolWithConstructorWithoutTypeCheck(); public void testExportFunctionWithOptionalArguments1(); public void testExportFunctionWithOptionalArguments2(); public void testExportFunctionWithOptionalArguments3(); public void testExportFunctionWithVariableArguments(); public void testExportEnum(); public void testExportDontEmitPrototypePathPrefix(); public void testUseExportsAsExterns(); public void testDontWarnOnExportFunctionWithUnknownReturnType(); public void testDontWarnOnExportConstructorWithUnknownReturnType(); public void testTypedef(); public void testExportParamWithNull() throws Exception; public void testExportConstructor() throws Exception; public void testExportParamWithSymbolDefinedInFunction() throws Exception; public void testExportSymbolWithFunctionDefinedAsFunction(); public void testExportSymbolWithFunctionAlias(); private void compileAndCheck(String js, String expected); public void testDontWarnOnExportFunctionWithUnknownParameterTypes(); private Result compileAndExportExterns(String js); private Result compileAndExportExterns(String js, String externs); } ``` You are a professional Java test case writer, please create a test case named `testUseExportsAsExterns` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the workflow of creating an externs file for a library * via the export pass and then using that externs file in a client. * * There should be no warnings in the client if the library includes * type information for the exported functions and the client uses them * correctly. */ public void testUseExportsAsExterns() { ```
final class ExternExportsPass extends NodeTraversal.AbstractPostOrderCallback implements CompilerPass
package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.util.List;
private void setRunCheckTypes(boolean shouldRunCheckTypes); @Override public void setUp() throws Exception; public void testExportSymbol() throws Exception; public void testExportSymbolDefinedInVar() throws Exception; public void testExportProperty() throws Exception; public void testExportMultiple() throws Exception; public void testExportMultiple2() throws Exception; public void testExportMultiple3() throws Exception; public void testExportNonStaticSymbol() throws Exception; public void testExportNonStaticSymbol2() throws Exception; public void testExportNonexistentProperty() throws Exception; public void testExportSymbolWithTypeAnnotation(); public void testExportSymbolWithTemplateAnnotation(); public void testExportSymbolWithMultipleTemplateAnnotation(); public void testExportSymbolWithoutTypeCheck(); public void testExportSymbolWithConstructor(); public void testExportSymbolWithConstructorWithoutTypeCheck(); public void testExportFunctionWithOptionalArguments1(); public void testExportFunctionWithOptionalArguments2(); public void testExportFunctionWithOptionalArguments3(); public void testExportFunctionWithVariableArguments(); public void testExportEnum(); public void testExportDontEmitPrototypePathPrefix(); public void testUseExportsAsExterns(); public void testDontWarnOnExportFunctionWithUnknownReturnType(); public void testDontWarnOnExportConstructorWithUnknownReturnType(); public void testTypedef(); public void testExportParamWithNull() throws Exception; public void testExportConstructor() throws Exception; public void testExportParamWithSymbolDefinedInFunction() throws Exception; public void testExportSymbolWithFunctionDefinedAsFunction(); public void testExportSymbolWithFunctionAlias(); private void compileAndCheck(String js, String expected); public void testDontWarnOnExportFunctionWithUnknownParameterTypes(); private Result compileAndExportExterns(String js); private Result compileAndExportExterns(String js, String externs);
c4fa9e8cccf7494931675159632328ce29da6a3fa587b94abfd2e808a9c031d9
[ "com.google.javascript.jscomp.ExternExportsPassTest::testUseExportsAsExterns" ]
private final List<Export> exports; private final Map<String, Node> definitionMap; private final AbstractCompiler compiler; private final Node externsRoot; private final Map<String, String> mappedPaths; private final Set<String> alreadyExportedPaths; private List<String> exportSymbolFunctionNames; private List<String> exportPropertyFunctionNames;
public void testUseExportsAsExterns()
private boolean runCheckTypes = true;
Closure
/* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.util.List; /** * Tests for {@link ExternExportsPass}. * */ public class ExternExportsPassTest extends TestCase { private boolean runCheckTypes = true; /** * ExternExportsPass relies on type information to emit JSDoc annotations for * exported externs. However, the user can disable type checking and still * ask for externs to be exported. Set this flag to enable or disable checking * of types during a test. */ private void setRunCheckTypes(boolean shouldRunCheckTypes) { runCheckTypes = shouldRunCheckTypes; } @Override public void setUp() throws Exception { super.setUp(); setRunCheckTypes(true); } public void testExportSymbol() throws Exception { compileAndCheck("var a = {}; a.b = {}; a.b.c = function(d, e, f) {};" + "goog.exportSymbol('foobar', a.b.c)", "/**\n" + " * @param {?} d\n" + " * @param {?} e\n" + " * @param {?} f\n" + " * @return {undefined}\n" + " */\n" + "var foobar = function(d, e, f) {\n};\n"); } public void testExportSymbolDefinedInVar() throws Exception { compileAndCheck("var a = function(d, e, f) {};" + "goog.exportSymbol('foobar', a)", "/**\n" + " * @param {?} d\n" + " * @param {?} e\n" + " * @param {?} f\n" + " * @return {undefined}\n" + " */\n" + "var foobar = function(d, e, f) {\n};\n"); } public void testExportProperty() throws Exception { compileAndCheck("var a = {}; a.b = {}; a.b.c = function(d, e, f) {};" + "goog.exportProperty(a.b, 'cprop', a.b.c)", "var a;\n" + "a.b;\n" + "/**\n" + " * @param {?} d\n" + " * @param {?} e\n" + " * @param {?} f\n" + " * @return {undefined}\n" + " */\n" + "a.b.cprop = function(d, e, f) {\n};\n"); } public void testExportMultiple() throws Exception { compileAndCheck("var a = {}; a.b = function(p1) {}; " + "a.b.c = function(d, e, f) {};" + "a.b.prototype.c = function(g, h, i) {};" + "goog.exportSymbol('a.b', a.b);" + "goog.exportProperty(a.b, 'c', a.b.c);" + "goog.exportProperty(a.b.prototype, 'c', a.b.prototype.c);", "var a;\n" + "/**\n" + " * @param {?} p1\n" + " * @return {undefined}\n" + " */\n" + "a.b = function(p1) {\n};\n" + "/**\n" + " * @param {?} d\n" + " * @param {?} e\n" + " * @param {?} f\n" + " * @return {undefined}\n" + " */\n" + "a.b.c = function(d, e, f) {\n};\n" + "/**\n" + " * @param {?} g\n" + " * @param {?} h\n" + " * @param {?} i\n" + " * @return {undefined}\n" + " */\n" + "a.b.prototype.c = function(g, h, i) {\n};\n"); } public void testExportMultiple2() throws Exception { compileAndCheck("var a = {}; a.b = function(p1) {}; " + "a.b.c = function(d, e, f) {};" + "a.b.prototype.c = function(g, h, i) {};" + "goog.exportSymbol('hello', a);" + "goog.exportProperty(a.b, 'c', a.b.c);" + "goog.exportProperty(a.b.prototype, 'c', a.b.prototype.c);", "/** @type {{b: function (?): undefined}} */\n" + "var hello = {};\n" + "hello.b;\n" + "/**\n" + " * @param {?} d\n" + " * @param {?} e\n" + " * @param {?} f\n" + " * @return {undefined}\n" + " */\n" + "hello.b.c = function(d, e, f) {\n};\n" + "/**\n" + " * @param {?} g\n" + " * @param {?} h\n" + " * @param {?} i\n" + " * @return {undefined}\n" + " */\n" + "hello.b.prototype.c = function(g, h, i) {\n};\n"); } public void testExportMultiple3() throws Exception { compileAndCheck("var a = {}; a.b = function(p1) {}; " + "a.b.c = function(d, e, f) {};" + "a.b.prototype.c = function(g, h, i) {};" + "goog.exportSymbol('prefix', a.b);" + "goog.exportProperty(a.b, 'c', a.b.c);", "/**\n" + " * @param {?} p1\n" + " * @return {undefined}\n" + " */\n" + "var prefix = function(p1) {\n};\n" + "/**\n" + " * @param {?} d\n" + " * @param {?} e\n" + " * @param {?} f\n" + " * @return {undefined}\n" + " */\n" + "prefix.c = function(d, e, f) {\n};\n"); } public void testExportNonStaticSymbol() throws Exception { compileAndCheck("var a = {}; a.b = {}; var d = {}; a.b.c = d;" + "goog.exportSymbol('foobar', a.b.c)", "var foobar;\n"); } public void testExportNonStaticSymbol2() throws Exception { compileAndCheck("var a = {}; a.b = {}; var d = null; a.b.c = d;" + "goog.exportSymbol('foobar', a.b.c())", "var foobar;\n"); } public void testExportNonexistentProperty() throws Exception { compileAndCheck("var a = {}; a.b = {}; a.b.c = function(d, e, f) {};" + "goog.exportProperty(a.b, 'none', a.b.none)", "var a;\n" + "a.b;\n" + "a.b.none;\n"); } public void testExportSymbolWithTypeAnnotation() { compileAndCheck("var internalName;\n" + "/**\n" + " * @param {string} param1\n" + " * @param {number} param2\n" + " * @return {string}\n" + " */\n" + "internalName = function(param1, param2) {" + "return param1 + param2;" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {string} param1\n" + " * @param {number} param2\n" + " * @return {string}\n" + " */\n" + "var externalName = function(param1, param2) {\n};\n"); } public void testExportSymbolWithTemplateAnnotation() { compileAndCheck("var internalName;\n" + "/**\n" + " * @param {T} param1\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "internalName = function(param1) {" + "return param1;" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {T} param1\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var externalName = function(param1) {\n};\n"); } public void testExportSymbolWithMultipleTemplateAnnotation() { compileAndCheck("var internalName;\n" + "/**\n" + " * @param {K} param1\n" + " * @return {V}\n" + " * @template K,V\n" + " */\n" + "internalName = function(param1) {" + "return /** @type {V} */ (param1);" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {K} param1\n" + " * @return {V}\n" + " * @template K,V\n" + " */\n" + "var externalName = function(param1) {\n};\n"); } public void testExportSymbolWithoutTypeCheck() { // ExternExportsPass should not emit annotations // if there is no type information available. setRunCheckTypes(false); compileAndCheck("var internalName;\n" + "/**\n" + " * @param {string} param1\n" + " * @param {number} param2\n" + " * @return {string}\n" + " */\n" + "internalName = function(param1, param2) {" + "return param1 + param2;" + "};" + "goog.exportSymbol('externalName', internalName)", "var externalName = function(param1, param2) {\n};\n"); } public void testExportSymbolWithConstructor() { compileAndCheck("var internalName;\n" + "/**\n" + " * @constructor\n" + " */\n" + "internalName = function() {" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @constructor\n" + " */\n" + "var externalName = function() {\n};\n"); } public void testExportSymbolWithConstructorWithoutTypeCheck() { // For now, skipping type checking should prevent generating // annotations of any kind, so, e.g., @constructor is not preserved. // This is probably not ideal, but since JSDocInfo for functions is attached // to JSTypes and not Nodes (and no JSTypes are created when checkTypes // is false), we don't really have a choice. setRunCheckTypes(false); compileAndCheck("var internalName;\n" + "/**\n" + " * @constructor\n" + " */\n" + "internalName = function() {" + "};" + "goog.exportSymbol('externalName', internalName)", "var externalName = function() {\n};\n"); } public void testExportFunctionWithOptionalArguments1() { compileAndCheck("var internalName;\n" + "/**\n" + " * @param {number=} a\n" + " */\n" + "internalName = function(a) {" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {number=} a\n" + " * @return {undefined}\n" + " */\n" + "var externalName = function(a) {\n};\n"); } public void testExportFunctionWithOptionalArguments2() { compileAndCheck("var internalName;\n" + "/**\n" + " * @param {number=} a\n" + " */\n" + "internalName = function(a) {" + " return 6;\n" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {number=} a\n" + " * @return {?}\n" + " */\n" + "var externalName = function(a) {\n};\n"); } public void testExportFunctionWithOptionalArguments3() { compileAndCheck("var internalName;\n" + "/**\n" + " * @param {number=} a\n" + " */\n" + "internalName = function(a) {" + " return a;\n" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {number=} a\n" + " * @return {?}\n" + " */\n" + "var externalName = function(a) {\n};\n"); } public void testExportFunctionWithVariableArguments() { compileAndCheck("var internalName;\n" + "/**\n" + " * @param {...number} a\n" + " * @return {number}\n" + " */\n" + "internalName = function(a) {" + " return 6;\n" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {...number} a\n" + " * @return {number}\n" + " */\n" + "var externalName = function(a) {\n};\n"); } /** * Enums are not currently handled. */ public void testExportEnum() { // We don't care what the values of the object properties are. // They're ignored by the type checker, and even if they weren't, it'd // be incomputable to get them correct in all cases // (think complex objects). compileAndCheck( "/** @enum {string}\n @export */ var E = {A:8, B:9};" + "goog.exportSymbol('E', E);", "/** @enum {string} */\n" + "var E = {A:1, B:2};\n"); } /** If we export a property with "prototype" as a path component, there * is no need to emit the initializer for prototype because every namespace * has one automatically. */ public void testExportDontEmitPrototypePathPrefix() { compileAndCheck( "/**\n" + " * @constructor\n" + " */\n" + "var Foo = function() {};" + "/**\n" + " * @return {number}\n" + " */\n" + "Foo.prototype.m = function() {return 6;};\n" + "goog.exportSymbol('Foo', Foo);\n" + "goog.exportProperty(Foo.prototype, 'm', Foo.prototype.m);", "/**\n" + " * @constructor\n" + " */\n" + "var Foo = function() {\n};\n" + "/**\n" + " * @return {number}\n" + " */\n" + "Foo.prototype.m = function() {\n};\n" ); } /** * Test the workflow of creating an externs file for a library * via the export pass and then using that externs file in a client. * * There should be no warnings in the client if the library includes * type information for the exported functions and the client uses them * correctly. */ public void testUseExportsAsExterns() { String librarySource = "/**\n" + " * @param {number} a\n" + " * @constructor\n" + " */\n" + "var InternalName = function(a) {" + "};" + "goog.exportSymbol('ExternalName', InternalName)"; String clientSource = "var a = new ExternalName(6);\n" + "/**\n" + " * @param {ExternalName} x\n" + " */\n" + "var b = function(x) {};"; Result libraryCompileResult = compileAndExportExterns(librarySource); assertEquals(0, libraryCompileResult.warnings.length); assertEquals(0, libraryCompileResult.errors.length); String generatedExterns = libraryCompileResult.externExport; Result clientCompileResult = compileAndExportExterns(clientSource, generatedExterns); assertEquals(0, clientCompileResult.warnings.length); assertEquals(0, clientCompileResult.errors.length); } public void testDontWarnOnExportFunctionWithUnknownReturnType() { String librarySource = "var InternalName = function() {" + " return 6;" + "};" + "goog.exportSymbol('ExternalName', InternalName)"; Result libraryCompileResult = compileAndExportExterns(librarySource); assertEquals(0, libraryCompileResult.warnings.length); assertEquals(0, libraryCompileResult.errors.length); } public void testDontWarnOnExportConstructorWithUnknownReturnType() { String librarySource = "/**\n" + " * @constructor\n" + " */\n " + "var InternalName = function() {" + "};" + "goog.exportSymbol('ExternalName', InternalName)"; Result libraryCompileResult = compileAndExportExterns(librarySource); assertEquals(0, libraryCompileResult.warnings.length); assertEquals(0, libraryCompileResult.errors.length); } public void testTypedef() { compileAndCheck( "/** @typedef {{x: number, y: number}} */ var Coord;\n" + "/**\n" + " * @param {Coord} a\n" + " * @export\n" + " */\n" + "var fn = function(a) {};" + "goog.exportSymbol('fn', fn);", "/**\n" + " * @param {{x: number, y: number}} a\n" + " * @return {undefined}\n" + " */\n" + "var fn = function(a) {\n};\n"); } public void testExportParamWithNull() throws Exception { compileAndCheck( "/** @param {string|null=} d */\n" + "var f = function(d) {};\n" + "goog.exportSymbol('foobar', f)\n", "/**\n" + " * @param {(null|string)=} d\n" + " * @return {undefined}\n" + " */\n" + "var foobar = function(d) {\n" + "};\n"); } public void testExportConstructor() throws Exception { compileAndCheck("/** @constructor */ var a = function() {};" + "goog.exportSymbol('foobar', a)", "/**\n" + " * @constructor\n" + " */\n" + "var foobar = function() {\n};\n"); } public void testExportParamWithSymbolDefinedInFunction() throws Exception { compileAndCheck( "var id = function() {return 'id'};\n" + "var ft = function() {\n" + " var id;\n" + " return 1;\n" + "};\n" + "goog.exportSymbol('id', id);\n", "/**\n" + " * @return {?}\n" + " */\n" + "var id = function() {\n" + "};\n"); } public void testExportSymbolWithFunctionDefinedAsFunction() { compileAndCheck("/**\n" + " * @param {string} param1\n" + " * @return {string}\n" + " */\n" + "function internalName(param1) {" + "return param1" + "};" + "goog.exportSymbol('externalName', internalName)", "/**\n" + " * @param {string} param1\n" + " * @return {string}\n" + " */\n" + "var externalName = function(param1) {\n};\n"); } public void testExportSymbolWithFunctionAlias() { compileAndCheck("/**\n" + " * @param {string} param1\n" + " */\n" + "var y = function(param1) {" + "};" + "/**\n" + " * @param {string} param1\n" + " * @param {string} param2\n" + " */\n" + "var x = function y(param1, param2) {" + "};" + "goog.exportSymbol('externalName', y)", "/**\n" + " * @param {string} param1\n" + " * @return {undefined}\n" + " */\n" + "var externalName = function(param1) {\n};\n"); } private void compileAndCheck(String js, String expected) { Result result = compileAndExportExterns(js); assertEquals(expected, result.externExport); } public void testDontWarnOnExportFunctionWithUnknownParameterTypes() { /* This source is missing types for the b and c parameters */ String librarySource = "/**\n" + " * @param {number} a\n" + " * @return {number}" + " */\n " + "var InternalName = function(a,b,c) {" + " return 6;" + "};" + "goog.exportSymbol('ExternalName', InternalName)"; Result libraryCompileResult = compileAndExportExterns(librarySource); assertEquals(0, libraryCompileResult.warnings.length); assertEquals(0, libraryCompileResult.errors.length); } private Result compileAndExportExterns(String js) { return compileAndExportExterns(js, ""); } /** * Compiles the passed in JavaScript with the passed in externs and returns * the new externs exported by the this pass. * * @param js the source to be compiled * @param externs the externs the {@code js} source needs * @return the externs generated from {@code js} */ private Result compileAndExportExterns(String js, String externs) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); options.externExportsPath = "externs.js"; // Turn off IDE mode. options.ideMode = false; /* Check types so we can make sure our exported externs have * type information. */ options.checkSymbols = true; options.checkTypes = runCheckTypes; List<SourceFile> inputs = Lists.newArrayList( SourceFile.fromCode("testcode", "var goog = {};" + "goog.exportSymbol = function(a, b) {}; " + "goog.exportProperty = function(a, b, c) {}; " + js)); List<SourceFile> externFiles = Lists.newArrayList( SourceFile.fromCode("externs", externs)); Result result = compiler.compile(externFiles, inputs, options); if (!result.success) { String msg = "Errors:"; msg += Joiner.on("\n").join(result.errors); assertTrue(msg, result.success); } return result; } }
[ { "be_test_class_file": "com/google/javascript/jscomp/ExternExportsPass.java", "be_test_class_name": "com.google.javascript.jscomp.ExternExportsPass", "be_test_function_name": "access$400", "be_test_function_signature": "(Lcom/google/javascript/jscomp/ExternExportsPass;)Ljava/util/Map;", "line_numbers": [ "41" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/ExternExportsPass.java", "be_test_class_name": "com.google.javascript.jscomp.ExternExportsPass", "be_test_function_name": "getGeneratedExterns", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "412", "417" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/ExternExportsPass.java", "be_test_class_name": "com.google.javascript.jscomp.ExternExportsPass", "be_test_function_name": "handleSymbolExport", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "454", "455", "458", "459", "460", "464", "465", "469", "470" ], "method_line_rate": 0.7777777777777778 }, { "be_test_class_file": "com/google/javascript/jscomp/ExternExportsPass.java", "be_test_class_name": "com.google.javascript.jscomp.ExternExportsPass", "be_test_function_name": "initExportMethods", "be_test_function_signature": "()V", "line_numbers": [ "371", "372", "377", "378", "379", "382", "383", "384" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/ExternExportsPass.java", "be_test_class_name": "com.google.javascript.jscomp.ExternExportsPass", "be_test_function_name": "process", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "388", "393", "401", "403", "404", "405", "406" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/ExternExportsPass.java", "be_test_class_name": "com.google.javascript.jscomp.ExternExportsPass", "be_test_function_name": "visit", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "422", "426", "427", "428", "431", "432", "437", "438", "441", "442", "445", "446", "449" ], "method_line_rate": 0.9230769230769231 } ]
public class TestUnsupportedDateTimeField extends TestCase
public void testDelegatedMethods() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); PreciseDurationField hoursDuration = new PreciseDurationField( DurationFieldType.hours(), 10L); DateTimeField fieldTwo = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, hoursDuration); // UnsupportedDateTimeField.add(long instant, int value) should // throw an UnsupportedOperationException when the duration does // not support the operation, otherwise it delegates to the duration. // First // try it with an UnsupportedDurationField, then a PreciseDurationField. try { fieldOne.add(System.currentTimeMillis(), 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long currentTime = System.currentTimeMillis(); long firstComputation = hoursDuration.add(currentTime, 100); long secondComputation = fieldTwo.add(currentTime, 100); assertEquals(firstComputation,secondComputation); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.add(long instant, long value) should // throw an UnsupportedOperationException when the duration does // not support the operation, otherwise it delegates to the duration. // First // try it with an UnsupportedDurationField, then a PreciseDurationField. try { fieldOne.add(System.currentTimeMillis(), 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long currentTime = System.currentTimeMillis(); long firstComputation = hoursDuration.add(currentTime, 1000L); long secondComputation = fieldTwo.add(currentTime, 1000L); assertTrue(firstComputation == secondComputation); assertEquals(firstComputation,secondComputation); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.getDifference(long minuendInstant, // long subtrahendInstant) // should throw an UnsupportedOperationException when the duration does // not support the operation, otherwise return the result from the // delegated call. try { fieldOne.getDifference(100000L, 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { int firstDifference = hoursDuration.getDifference(100000L, 1000L); int secondDifference = fieldTwo.getDifference(100000L, 1000L); assertEquals(firstDifference,secondDifference); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.getDifferenceAsLong(long minuendInstant, // long subtrahendInstant) // should throw an UnsupportedOperationException when the duration does // not support the operation, otherwise return the result from the // delegated call. try { fieldOne.getDifferenceAsLong(100000L, 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long firstDifference = hoursDuration.getDifference(100000L, 1000L); long secondDifference = fieldTwo.getDifference(100000L, 1000L); assertEquals(firstDifference,secondDifference); } catch (UnsupportedOperationException e) { assertTrue(false); } }
// // Abstract Java Tested Class // package org.joda.time.field; // // import java.io.Serializable; // import java.util.HashMap; // import java.util.Locale; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeFieldType; // import org.joda.time.DurationField; // import org.joda.time.ReadablePartial; // // // // public final class UnsupportedDateTimeField extends DateTimeField implements Serializable { // private static final long serialVersionUID = -1934618396111902255L; // private static HashMap<DateTimeFieldType, UnsupportedDateTimeField> cCache; // private final DateTimeFieldType iType; // private final DurationField iDurationField; // // public static synchronized UnsupportedDateTimeField getInstance( // DateTimeFieldType type, DurationField durationField); // private UnsupportedDateTimeField(DateTimeFieldType type, DurationField durationField); // public DateTimeFieldType getType(); // public String getName(); // public boolean isSupported(); // public boolean isLenient(); // public int get(long instant); // public String getAsText(long instant, Locale locale); // public String getAsText(long instant); // public String getAsText(ReadablePartial partial, int fieldValue, Locale locale); // public String getAsText(ReadablePartial partial, Locale locale); // public String getAsText(int fieldValue, Locale locale); // public String getAsShortText(long instant, Locale locale); // public String getAsShortText(long instant); // public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale); // public String getAsShortText(ReadablePartial partial, Locale locale); // public String getAsShortText(int fieldValue, Locale locale); // public long add(long instant, int value); // public long add(long instant, long value); // public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); // public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); // public long addWrapField(long instant, int value); // public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); // public int getDifference(long minuendInstant, long subtrahendInstant); // public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); // public long set(long instant, int value); // public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue); // public long set(long instant, String text, Locale locale); // public long set(long instant, String text); // public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale); // public DurationField getDurationField(); // public DurationField getRangeDurationField(); // public boolean isLeap(long instant); // public int getLeapAmount(long instant); // public DurationField getLeapDurationField(); // public int getMinimumValue(); // public int getMinimumValue(long instant); // public int getMinimumValue(ReadablePartial instant); // public int getMinimumValue(ReadablePartial instant, int[] values); // public int getMaximumValue(); // public int getMaximumValue(long instant); // public int getMaximumValue(ReadablePartial instant); // public int getMaximumValue(ReadablePartial instant, int[] values); // public int getMaximumTextLength(Locale locale); // public int getMaximumShortTextLength(Locale locale); // public long roundFloor(long instant); // public long roundCeiling(long instant); // public long roundHalfFloor(long instant); // public long roundHalfCeiling(long instant); // public long roundHalfEven(long instant); // public long remainder(long instant); // public String toString(); // private Object readResolve(); // private UnsupportedOperationException unsupported(); // } // // // Abstract Java Test Class // package org.joda.time.field; // // import java.util.Locale; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeFieldType; // import org.joda.time.DurationFieldType; // import org.joda.time.LocalTime; // import org.joda.time.ReadablePartial; // // // // public class TestUnsupportedDateTimeField extends TestCase { // private DurationFieldType weeks; // private DurationFieldType months; // private DateTimeFieldType dateTimeFieldTypeOne; // private ReadablePartial localTime; // // public static TestSuite suite(); // protected void setUp() throws Exception; // public void testNullValuesToGetInstanceThrowsException(); // public void testDifferentDurationReturnDifferentObjects(); // public void testPublicGetNameMethod(); // public void testAlwaysFalseReturnTypes(); // public void testMethodsThatShouldAlwaysReturnNull(); // public void testUnsupportedMethods(); // public void testDelegatedMethods(); // public void testToString(); // } // You are a professional Java test case writer, please create a test case named `testDelegatedMethods` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * As this is an unsupported date/time field, many normal methods are * unsupported. Some delegate and can possibly throw an * UnsupportedOperationException or have a valid return. Verify that each * method correctly throws this exception when appropriate and delegates * correctly based on the Duration used to get the instance. */
src/test/java/org/joda/time/field/TestUnsupportedDateTimeField.java
package org.joda.time.field; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial;
public static synchronized UnsupportedDateTimeField getInstance( DateTimeFieldType type, DurationField durationField); private UnsupportedDateTimeField(DateTimeFieldType type, DurationField durationField); public DateTimeFieldType getType(); public String getName(); public boolean isSupported(); public boolean isLenient(); public int get(long instant); public String getAsText(long instant, Locale locale); public String getAsText(long instant); public String getAsText(ReadablePartial partial, int fieldValue, Locale locale); public String getAsText(ReadablePartial partial, Locale locale); public String getAsText(int fieldValue, Locale locale); public String getAsShortText(long instant, Locale locale); public String getAsShortText(long instant); public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale); public String getAsShortText(ReadablePartial partial, Locale locale); public String getAsShortText(int fieldValue, Locale locale); public long add(long instant, int value); public long add(long instant, long value); public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public long addWrapField(long instant, int value); public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public int getDifference(long minuendInstant, long subtrahendInstant); public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); public long set(long instant, int value); public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue); public long set(long instant, String text, Locale locale); public long set(long instant, String text); public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale); public DurationField getDurationField(); public DurationField getRangeDurationField(); public boolean isLeap(long instant); public int getLeapAmount(long instant); public DurationField getLeapDurationField(); public int getMinimumValue(); public int getMinimumValue(long instant); public int getMinimumValue(ReadablePartial instant); public int getMinimumValue(ReadablePartial instant, int[] values); public int getMaximumValue(); public int getMaximumValue(long instant); public int getMaximumValue(ReadablePartial instant); public int getMaximumValue(ReadablePartial instant, int[] values); public int getMaximumTextLength(Locale locale); public int getMaximumShortTextLength(Locale locale); public long roundFloor(long instant); public long roundCeiling(long instant); public long roundHalfFloor(long instant); public long roundHalfCeiling(long instant); public long roundHalfEven(long instant); public long remainder(long instant); public String toString(); private Object readResolve(); private UnsupportedOperationException unsupported();
639
testDelegatedMethods
```java // Abstract Java Tested Class package org.joda.time.field; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; public final class UnsupportedDateTimeField extends DateTimeField implements Serializable { private static final long serialVersionUID = -1934618396111902255L; private static HashMap<DateTimeFieldType, UnsupportedDateTimeField> cCache; private final DateTimeFieldType iType; private final DurationField iDurationField; public static synchronized UnsupportedDateTimeField getInstance( DateTimeFieldType type, DurationField durationField); private UnsupportedDateTimeField(DateTimeFieldType type, DurationField durationField); public DateTimeFieldType getType(); public String getName(); public boolean isSupported(); public boolean isLenient(); public int get(long instant); public String getAsText(long instant, Locale locale); public String getAsText(long instant); public String getAsText(ReadablePartial partial, int fieldValue, Locale locale); public String getAsText(ReadablePartial partial, Locale locale); public String getAsText(int fieldValue, Locale locale); public String getAsShortText(long instant, Locale locale); public String getAsShortText(long instant); public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale); public String getAsShortText(ReadablePartial partial, Locale locale); public String getAsShortText(int fieldValue, Locale locale); public long add(long instant, int value); public long add(long instant, long value); public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public long addWrapField(long instant, int value); public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public int getDifference(long minuendInstant, long subtrahendInstant); public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); public long set(long instant, int value); public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue); public long set(long instant, String text, Locale locale); public long set(long instant, String text); public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale); public DurationField getDurationField(); public DurationField getRangeDurationField(); public boolean isLeap(long instant); public int getLeapAmount(long instant); public DurationField getLeapDurationField(); public int getMinimumValue(); public int getMinimumValue(long instant); public int getMinimumValue(ReadablePartial instant); public int getMinimumValue(ReadablePartial instant, int[] values); public int getMaximumValue(); public int getMaximumValue(long instant); public int getMaximumValue(ReadablePartial instant); public int getMaximumValue(ReadablePartial instant, int[] values); public int getMaximumTextLength(Locale locale); public int getMaximumShortTextLength(Locale locale); public long roundFloor(long instant); public long roundCeiling(long instant); public long roundHalfFloor(long instant); public long roundHalfCeiling(long instant); public long roundHalfEven(long instant); public long remainder(long instant); public String toString(); private Object readResolve(); private UnsupportedOperationException unsupported(); } // Abstract Java Test Class package org.joda.time.field; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationFieldType; import org.joda.time.LocalTime; import org.joda.time.ReadablePartial; public class TestUnsupportedDateTimeField extends TestCase { private DurationFieldType weeks; private DurationFieldType months; private DateTimeFieldType dateTimeFieldTypeOne; private ReadablePartial localTime; public static TestSuite suite(); protected void setUp() throws Exception; public void testNullValuesToGetInstanceThrowsException(); public void testDifferentDurationReturnDifferentObjects(); public void testPublicGetNameMethod(); public void testAlwaysFalseReturnTypes(); public void testMethodsThatShouldAlwaysReturnNull(); public void testUnsupportedMethods(); public void testDelegatedMethods(); public void testToString(); } ``` You are a professional Java test case writer, please create a test case named `testDelegatedMethods` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * As this is an unsupported date/time field, many normal methods are * unsupported. Some delegate and can possibly throw an * UnsupportedOperationException or have a valid return. Verify that each * method correctly throws this exception when appropriate and delegates * correctly based on the Duration used to get the instance. */
547
// // Abstract Java Tested Class // package org.joda.time.field; // // import java.io.Serializable; // import java.util.HashMap; // import java.util.Locale; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeFieldType; // import org.joda.time.DurationField; // import org.joda.time.ReadablePartial; // // // // public final class UnsupportedDateTimeField extends DateTimeField implements Serializable { // private static final long serialVersionUID = -1934618396111902255L; // private static HashMap<DateTimeFieldType, UnsupportedDateTimeField> cCache; // private final DateTimeFieldType iType; // private final DurationField iDurationField; // // public static synchronized UnsupportedDateTimeField getInstance( // DateTimeFieldType type, DurationField durationField); // private UnsupportedDateTimeField(DateTimeFieldType type, DurationField durationField); // public DateTimeFieldType getType(); // public String getName(); // public boolean isSupported(); // public boolean isLenient(); // public int get(long instant); // public String getAsText(long instant, Locale locale); // public String getAsText(long instant); // public String getAsText(ReadablePartial partial, int fieldValue, Locale locale); // public String getAsText(ReadablePartial partial, Locale locale); // public String getAsText(int fieldValue, Locale locale); // public String getAsShortText(long instant, Locale locale); // public String getAsShortText(long instant); // public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale); // public String getAsShortText(ReadablePartial partial, Locale locale); // public String getAsShortText(int fieldValue, Locale locale); // public long add(long instant, int value); // public long add(long instant, long value); // public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); // public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); // public long addWrapField(long instant, int value); // public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); // public int getDifference(long minuendInstant, long subtrahendInstant); // public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); // public long set(long instant, int value); // public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue); // public long set(long instant, String text, Locale locale); // public long set(long instant, String text); // public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale); // public DurationField getDurationField(); // public DurationField getRangeDurationField(); // public boolean isLeap(long instant); // public int getLeapAmount(long instant); // public DurationField getLeapDurationField(); // public int getMinimumValue(); // public int getMinimumValue(long instant); // public int getMinimumValue(ReadablePartial instant); // public int getMinimumValue(ReadablePartial instant, int[] values); // public int getMaximumValue(); // public int getMaximumValue(long instant); // public int getMaximumValue(ReadablePartial instant); // public int getMaximumValue(ReadablePartial instant, int[] values); // public int getMaximumTextLength(Locale locale); // public int getMaximumShortTextLength(Locale locale); // public long roundFloor(long instant); // public long roundCeiling(long instant); // public long roundHalfFloor(long instant); // public long roundHalfCeiling(long instant); // public long roundHalfEven(long instant); // public long remainder(long instant); // public String toString(); // private Object readResolve(); // private UnsupportedOperationException unsupported(); // } // // // Abstract Java Test Class // package org.joda.time.field; // // import java.util.Locale; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeFieldType; // import org.joda.time.DurationFieldType; // import org.joda.time.LocalTime; // import org.joda.time.ReadablePartial; // // // // public class TestUnsupportedDateTimeField extends TestCase { // private DurationFieldType weeks; // private DurationFieldType months; // private DateTimeFieldType dateTimeFieldTypeOne; // private ReadablePartial localTime; // // public static TestSuite suite(); // protected void setUp() throws Exception; // public void testNullValuesToGetInstanceThrowsException(); // public void testDifferentDurationReturnDifferentObjects(); // public void testPublicGetNameMethod(); // public void testAlwaysFalseReturnTypes(); // public void testMethodsThatShouldAlwaysReturnNull(); // public void testUnsupportedMethods(); // public void testDelegatedMethods(); // public void testToString(); // } // You are a professional Java test case writer, please create a test case named `testDelegatedMethods` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * As this is an unsupported date/time field, many normal methods are * unsupported. Some delegate and can possibly throw an * UnsupportedOperationException or have a valid return. Verify that each * method correctly throws this exception when appropriate and delegates * correctly based on the Duration used to get the instance. */ public void testDelegatedMethods() {
/** * As this is an unsupported date/time field, many normal methods are * unsupported. Some delegate and can possibly throw an * UnsupportedOperationException or have a valid return. Verify that each * method correctly throws this exception when appropriate and delegates * correctly based on the Duration used to get the instance. */
1
org.joda.time.field.UnsupportedDateTimeField
src/test/java
```java // Abstract Java Tested Class package org.joda.time.field; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; public final class UnsupportedDateTimeField extends DateTimeField implements Serializable { private static final long serialVersionUID = -1934618396111902255L; private static HashMap<DateTimeFieldType, UnsupportedDateTimeField> cCache; private final DateTimeFieldType iType; private final DurationField iDurationField; public static synchronized UnsupportedDateTimeField getInstance( DateTimeFieldType type, DurationField durationField); private UnsupportedDateTimeField(DateTimeFieldType type, DurationField durationField); public DateTimeFieldType getType(); public String getName(); public boolean isSupported(); public boolean isLenient(); public int get(long instant); public String getAsText(long instant, Locale locale); public String getAsText(long instant); public String getAsText(ReadablePartial partial, int fieldValue, Locale locale); public String getAsText(ReadablePartial partial, Locale locale); public String getAsText(int fieldValue, Locale locale); public String getAsShortText(long instant, Locale locale); public String getAsShortText(long instant); public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale); public String getAsShortText(ReadablePartial partial, Locale locale); public String getAsShortText(int fieldValue, Locale locale); public long add(long instant, int value); public long add(long instant, long value); public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public long addWrapField(long instant, int value); public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); public int getDifference(long minuendInstant, long subtrahendInstant); public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); public long set(long instant, int value); public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue); public long set(long instant, String text, Locale locale); public long set(long instant, String text); public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale); public DurationField getDurationField(); public DurationField getRangeDurationField(); public boolean isLeap(long instant); public int getLeapAmount(long instant); public DurationField getLeapDurationField(); public int getMinimumValue(); public int getMinimumValue(long instant); public int getMinimumValue(ReadablePartial instant); public int getMinimumValue(ReadablePartial instant, int[] values); public int getMaximumValue(); public int getMaximumValue(long instant); public int getMaximumValue(ReadablePartial instant); public int getMaximumValue(ReadablePartial instant, int[] values); public int getMaximumTextLength(Locale locale); public int getMaximumShortTextLength(Locale locale); public long roundFloor(long instant); public long roundCeiling(long instant); public long roundHalfFloor(long instant); public long roundHalfCeiling(long instant); public long roundHalfEven(long instant); public long remainder(long instant); public String toString(); private Object readResolve(); private UnsupportedOperationException unsupported(); } // Abstract Java Test Class package org.joda.time.field; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationFieldType; import org.joda.time.LocalTime; import org.joda.time.ReadablePartial; public class TestUnsupportedDateTimeField extends TestCase { private DurationFieldType weeks; private DurationFieldType months; private DateTimeFieldType dateTimeFieldTypeOne; private ReadablePartial localTime; public static TestSuite suite(); protected void setUp() throws Exception; public void testNullValuesToGetInstanceThrowsException(); public void testDifferentDurationReturnDifferentObjects(); public void testPublicGetNameMethod(); public void testAlwaysFalseReturnTypes(); public void testMethodsThatShouldAlwaysReturnNull(); public void testUnsupportedMethods(); public void testDelegatedMethods(); public void testToString(); } ``` You are a professional Java test case writer, please create a test case named `testDelegatedMethods` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * As this is an unsupported date/time field, many normal methods are * unsupported. Some delegate and can possibly throw an * UnsupportedOperationException or have a valid return. Verify that each * method correctly throws this exception when appropriate and delegates * correctly based on the Duration used to get the instance. */ public void testDelegatedMethods() { ```
public final class UnsupportedDateTimeField extends DateTimeField implements Serializable
package org.joda.time.field; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationFieldType; import org.joda.time.LocalTime; import org.joda.time.ReadablePartial;
public static TestSuite suite(); protected void setUp() throws Exception; public void testNullValuesToGetInstanceThrowsException(); public void testDifferentDurationReturnDifferentObjects(); public void testPublicGetNameMethod(); public void testAlwaysFalseReturnTypes(); public void testMethodsThatShouldAlwaysReturnNull(); public void testUnsupportedMethods(); public void testDelegatedMethods(); public void testToString();
c7da8cbb21a6fc26fff6e49c50d07a49dd01b9b516e048808eb5022b40c79ee0
[ "org.joda.time.field.TestUnsupportedDateTimeField::testDelegatedMethods" ]
private static final long serialVersionUID = -1934618396111902255L; private static HashMap<DateTimeFieldType, UnsupportedDateTimeField> cCache; private final DateTimeFieldType iType; private final DurationField iDurationField;
public void testDelegatedMethods()
private DurationFieldType weeks; private DurationFieldType months; private DateTimeFieldType dateTimeFieldTypeOne; private ReadablePartial localTime;
Time
/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationFieldType; import org.joda.time.LocalTime; import org.joda.time.ReadablePartial; /** * This class is a JUnit test to test only the UnsupportedDateTimeField class. * This set of test cases exercises everything described in the Javadoc for this * class. * * @author Jeremy R. Rickard */ public class TestUnsupportedDateTimeField extends TestCase { private DurationFieldType weeks; private DurationFieldType months; private DateTimeFieldType dateTimeFieldTypeOne; private ReadablePartial localTime; public static TestSuite suite() { return new TestSuite(TestUnsupportedDateTimeField.class); } protected void setUp() throws Exception { weeks = DurationFieldType.weeks(); months = DurationFieldType.months(); dateTimeFieldTypeOne = DateTimeFieldType.centuryOfEra(); localTime = new LocalTime(); } /** * Passing null values into UnsupportedDateTimeField.getInstance() should * throw an IllegalArguementsException */ public void testNullValuesToGetInstanceThrowsException() { try { UnsupportedDateTimeField.getInstance(null, null); assertTrue(false); } catch (IllegalArgumentException e) { assertTrue(true); } } /** * * This test exercises the logic in UnsupportedDateTimeField.getInstance. If * getInstance() is invoked twice with: - the same DateTimeFieldType - * different duration fields * * Then the field returned in the first invocation should not be equal to * the field returned by the second invocation. In otherwords, the generated * instance should be the same for a unique pairing of * DateTimeFieldType/DurationField */ public void testDifferentDurationReturnDifferentObjects() { /** * The fields returned by getInstance should be the same when the * duration is the same for both method calls. */ DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); DateTimeField fieldTwo = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertSame(fieldOne, fieldTwo); /** * The fields returned by getInstance should NOT be the same when the * duration is the same for both method calls. */ DateTimeField fieldThree = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(months)); assertNotSame(fieldOne, fieldThree); } /** * The getName() method should return the same value as the getName() method * of the DateTimeFieldType that was used to create the instance. * */ public void testPublicGetNameMethod() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertSame(fieldOne.getName(), dateTimeFieldTypeOne.getName()); } /** * As this is an unsupported date/time field, some normal methods will * always return false, as they are not supported. Verify that each method * correctly returns null. */ public void testAlwaysFalseReturnTypes() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertFalse(fieldOne.isLenient()); assertFalse(fieldOne.isSupported()); } /** * According to the JavaDocs, there are two methods that should always * return null. * getRangeDurationField() * getLeapDurationField() * * Ensure that these are in fact null. */ public void testMethodsThatShouldAlwaysReturnNull() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertNull(fieldOne.getLeapDurationField()); assertNull(fieldOne.getRangeDurationField()); } /** * As this is an unsupported date/time field, many normal methods are * unsupported and throw an UnsupportedOperationException. Verify that each * method correctly throws this exception. * add(ReadablePartial instant, * int fieldIndex, int[] values, int valueToAdd) * addWrapField(long * instant, int value) * addWrapField(ReadablePartial instant, int * fieldIndex, int[] values, int valueToAdd) * * addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int * valueToAdd) * get(long instant) * getAsShortText(int fieldValue, Locale * locale) * getAsShortText(long instant) * getAsShortText(long instant, * Locale locale) * getAsShortText(ReadablePartial partial, int fieldValue, * Locale locale) * getAsShortText(ReadablePartial partial, Locale locale) * * getAsText(int fieldValue, Locale locale) * getAsText(long instant) * * getAsText(long instant, Locale locale) * getAsText(ReadablePartial * partial, int fieldValue, Locale locale) * getAsText(ReadablePartial * partial, Locale locale) * getLeapAmount(long instant) * * getMaximumShortTextLength(Locale locale) * getMaximumTextLength(Locale * locale) * getMaximumValue() * getMaximumValue(long instant) * * getMaximumValue(ReadablePartial instant) * * getMaximumValue(ReadablePartial instant, int[] values) * * getMinimumValue() * getMinimumValue(long instant) * * getMinimumValue(ReadablePartial instant) * * getMinimumValue(ReadablePartial instant, int[] values) * isLeap(long * instant) * remainder(long instant) * roundCeiling(long instant) * * roundFloor(long instant) * roundHalfCeiling(long instant) * * roundHalfEven(long instant) * roundHalfFloor(long instant) * set(long * instant, int value) * set(long instant, String text) * set(long instant, * String text, Locale locale) * set(ReadablePartial instant, int * fieldIndex, int[] values, int newValue) * set(ReadablePartial instant, * int fieldIndex, int[] values, String text, Locale locale) */ public void testUnsupportedMethods() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); // add(ReadablePartial instant, int fieldIndex, int[] values, int // valueToAdd) try { fieldOne.add(localTime, 0, new int[] { 0, 100 }, 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // addWrapField(long instant, int value) try { fieldOne.addWrapField(100000L, 250); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // addWrapField(ReadablePartial instant, int fieldIndex, int[] values, // int valueToAdd) try { fieldOne.addWrapField(localTime, 0, new int[] { 0, 100 }, 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, // int valueToAdd) try { fieldOne.addWrapPartial(localTime, 0, new int[] { 0, 100 }, 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.get(long instant) try { fieldOne.get(1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(int fieldValue, // Locale locale) try { fieldOne.getAsShortText(0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(long instant) try { fieldOne.getAsShortText(100000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(long instant, Locale locale) try { fieldOne.getAsShortText(100000L, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(ReadablePartial partial, // int fieldValue, // Locale locale) try { fieldOne.getAsShortText(localTime, 0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(ReadablePartial partial, // Locale locale) try { fieldOne.getAsShortText(localTime, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(int fieldValue, // Locale locale) try { fieldOne.getAsText(0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(long instant) try { fieldOne.getAsText(1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(long instant, Locale locale) try { fieldOne.getAsText(1000L, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(ReadablePartial partial, // int fieldValue, // Locale locale) try { fieldOne.getAsText(localTime, 0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(ReadablePartial partial, // Locale locale) try { fieldOne.getAsText(localTime, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getLeapAmount(long instant) is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getLeapAmount(System.currentTimeMillis()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumShortTextLength(Locale locale) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumShortTextLength(Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumTextLength(Locale locale) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumTextLength(Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue() is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMaximumValue(); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue(long instant) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumValue(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue(ReadablePartial instant) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumValue(localTime); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue(ReadablePartial instant, // int[] values) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumValue(localTime, new int[] { 0 }); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue() is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMinimumValue(); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue(long instant) is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMinimumValue(10000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue(ReadablePartial instant) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMinimumValue(localTime); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue(ReadablePartial instant, // int[] values) is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMinimumValue(localTime, new int[] { 0 }); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.isLeap(long instant) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.isLeap(System.currentTimeMillis()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.remainder(long instant) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.remainder(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundCeiling(long instant) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.roundCeiling(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundFloor(long instant) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.roundFloor(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundHalfCeiling(long instant) is // unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.roundHalfCeiling(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundHalfEven(long instant) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.roundHalfEven(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundHalfFloor(long instant) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.roundHalfFloor(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(long instant, int value) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.set(1000000L, 1000); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(long instant, String test) is // unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.set(1000000L, "Unsupported Operation"); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(long instant, String text, Locale // locale) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne .set(1000000L, "Unsupported Operation", Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(ReadablePartial instant, // int fieldIndex, // int[] values, // int newValue) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.set(localTime, 0, new int[] { 0 }, 10000); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(ReadablePartial instant, // int fieldIndex, // int[] values, // String text, // Locale locale) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.set(localTime, 0, new int[] { 0 }, "Unsupported Operation", Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } } /** * As this is an unsupported date/time field, many normal methods are * unsupported. Some delegate and can possibly throw an * UnsupportedOperationException or have a valid return. Verify that each * method correctly throws this exception when appropriate and delegates * correctly based on the Duration used to get the instance. */ public void testDelegatedMethods() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); PreciseDurationField hoursDuration = new PreciseDurationField( DurationFieldType.hours(), 10L); DateTimeField fieldTwo = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, hoursDuration); // UnsupportedDateTimeField.add(long instant, int value) should // throw an UnsupportedOperationException when the duration does // not support the operation, otherwise it delegates to the duration. // First // try it with an UnsupportedDurationField, then a PreciseDurationField. try { fieldOne.add(System.currentTimeMillis(), 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long currentTime = System.currentTimeMillis(); long firstComputation = hoursDuration.add(currentTime, 100); long secondComputation = fieldTwo.add(currentTime, 100); assertEquals(firstComputation,secondComputation); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.add(long instant, long value) should // throw an UnsupportedOperationException when the duration does // not support the operation, otherwise it delegates to the duration. // First // try it with an UnsupportedDurationField, then a PreciseDurationField. try { fieldOne.add(System.currentTimeMillis(), 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long currentTime = System.currentTimeMillis(); long firstComputation = hoursDuration.add(currentTime, 1000L); long secondComputation = fieldTwo.add(currentTime, 1000L); assertTrue(firstComputation == secondComputation); assertEquals(firstComputation,secondComputation); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.getDifference(long minuendInstant, // long subtrahendInstant) // should throw an UnsupportedOperationException when the duration does // not support the operation, otherwise return the result from the // delegated call. try { fieldOne.getDifference(100000L, 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { int firstDifference = hoursDuration.getDifference(100000L, 1000L); int secondDifference = fieldTwo.getDifference(100000L, 1000L); assertEquals(firstDifference,secondDifference); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.getDifferenceAsLong(long minuendInstant, // long subtrahendInstant) // should throw an UnsupportedOperationException when the duration does // not support the operation, otherwise return the result from the // delegated call. try { fieldOne.getDifferenceAsLong(100000L, 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long firstDifference = hoursDuration.getDifference(100000L, 1000L); long secondDifference = fieldTwo.getDifference(100000L, 1000L); assertEquals(firstDifference,secondDifference); } catch (UnsupportedOperationException e) { assertTrue(false); } } /** * The toString method should return a suitable debug message (not null). * Ensure that the toString method returns a string with length greater than * 0 (and not null) * */ public void testToString() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); String debugMessage = fieldOne.toString(); assertNotNull(debugMessage); assertTrue(debugMessage.length() > 0); } }
[ { "be_test_class_file": "org/joda/time/field/UnsupportedDateTimeField.java", "be_test_class_name": "org.joda.time.field.UnsupportedDateTimeField", "be_test_function_name": "add", "be_test_function_signature": "(JI)J", "line_numbers": [ "225" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/field/UnsupportedDateTimeField.java", "be_test_class_name": "org.joda.time.field.UnsupportedDateTimeField", "be_test_function_name": "add", "be_test_function_signature": "(JJ)J", "line_numbers": [ "234" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/field/UnsupportedDateTimeField.java", "be_test_class_name": "org.joda.time.field.UnsupportedDateTimeField", "be_test_function_name": "getDifference", "be_test_function_signature": "(JJ)I", "line_numbers": [ "279" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/field/UnsupportedDateTimeField.java", "be_test_class_name": "org.joda.time.field.UnsupportedDateTimeField", "be_test_function_name": "getDifferenceAsLong", "be_test_function_signature": "(JJ)J", "line_numbers": [ "288" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/field/UnsupportedDateTimeField.java", "be_test_class_name": "org.joda.time.field.UnsupportedDateTimeField", "be_test_function_name": "getDurationField", "be_test_function_signature": "()Lorg/joda/time/DurationField;", "line_numbers": [ "343" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/field/UnsupportedDateTimeField.java", "be_test_class_name": "org.joda.time.field.UnsupportedDateTimeField", "be_test_function_name": "getInstance", "be_test_function_signature": "(Lorg/joda/time/DateTimeFieldType;Lorg/joda/time/DurationField;)Lorg/joda/time/field/UnsupportedDateTimeField;", "line_numbers": [ "55", "56", "57", "59", "60", "61", "64", "65", "66", "68" ], "method_line_rate": 1 } ]
public class TestTypeFactory extends BaseMapTest
public void testRawCollections() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawCollectionType(ArrayList.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawCollectionLikeType(CollectionLike.class); // must have type vars assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawCollectionLikeType(String.class); assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); }
// private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) // throws IllegalArgumentException; // private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); // public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); // public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; // public JavaType[] findTypeParameters(JavaType type, Class<?> expType); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); // public JavaType moreSpecificType(JavaType type1, JavaType type2); // public JavaType constructType(Type type); // public JavaType constructType(Type type, TypeBindings bindings); // public JavaType constructType(TypeReference<?> typeRef); // @Deprecated // public JavaType constructType(Type type, Class<?> contextClass); // @Deprecated // public JavaType constructType(Type type, JavaType contextType); // public ArrayType constructArrayType(Class<?> elementType); // public ArrayType constructArrayType(JavaType elementType); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // Class<?> elementClass); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // JavaType elementType); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); // public MapType constructMapType(Class<? extends Map> mapClass, // Class<?> keyClass, Class<?> valueClass); // public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); // public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); // public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); // public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); // @Deprecated // public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, // JavaType[] parameterTypes); // public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); // @Deprecated // since 2.8 // public JavaType uncheckedSimpleType(Class<?> cls); // public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); // public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // Class<?>... parameterClasses); // public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); // public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); // public MapType constructRawMapType(Class<? extends Map> mapClass); // public MapLikeType constructRawMapLikeType(Class<?> mapClass); // private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _unknownType(); // protected JavaType _findWellKnownSimple(Class<?> clz); // protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); // protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); // protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, // TypeBindings parentBindings); // protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); // protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); // protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.type; // // import java.lang.reflect.Field; // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.core.type.TypeReference; // import com.fasterxml.jackson.databind.*; // // // // public class TestTypeFactory // extends BaseMapTest // { // // // public void testSimpleTypes(); // public void testArrays(); // public void testProperties(); // public void testIterator(); // @SuppressWarnings("deprecation") // public void testParametricTypes(); // public void testCanonicalNames(); // @SuppressWarnings("serial") // public void testCanonicalWithSpaces(); // public void testCollections(); // public void testCollectionTypesRefined(); // public void testMaps(); // public void testMapTypesRefined(); // public void testTypeGeneralization(); // public void testMapTypesRaw(); // public void testMapTypesAdvanced(); // public void testMapTypesSneaky(); // public void testSneakyFieldTypes() throws Exception; // public void testSneakyBeanProperties() throws Exception; // public void testSneakySelfRefs() throws Exception; // public void testAtomicArrayRefParameters(); // public void testMapEntryResolution(); // public void testRawCollections(); // public void testRawMaps(); // public void testMoreSpecificType(); // public void testCacheClearing(); // public void testRawMapType(); // public <T extends Comparable<T>> T getFoobar(); // } // You are a professional Java test case writer, please create a test case named `testRawCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/type/TestTypeFactory.java
package com.fasterxml.jackson.databind.type; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.lang.reflect.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.util.ArrayBuilders; import com.fasterxml.jackson.databind.util.ClassUtil; import com.fasterxml.jackson.databind.util.LRUMap;
private TypeFactory(); protected TypeFactory(LRUMap<Object,JavaType> typeCache); protected TypeFactory(LRUMap<Object,JavaType> typeCache, TypeParser p, TypeModifier[] mods, ClassLoader classLoader); public TypeFactory withModifier(TypeModifier mod); public TypeFactory withClassLoader(ClassLoader classLoader); public TypeFactory withCache(LRUMap<Object,JavaType> cache); public static TypeFactory defaultInstance(); public void clearCache(); public ClassLoader getClassLoader(); public static JavaType unknownType(); public static Class<?> rawClass(Type t); public Class<?> findClass(String className) throws ClassNotFoundException; protected Class<?> classForName(String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException; protected Class<?> classForName(String name) throws ClassNotFoundException; protected Class<?> _findPrimitive(String className); public JavaType constructSpecializedType(JavaType baseType, Class<?> subclass); private TypeBindings _bindingsForSubtype(JavaType baseType, int typeParamCount, Class<?> subclass); private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) throws IllegalArgumentException; private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; public JavaType[] findTypeParameters(JavaType type, Class<?> expType); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); public JavaType moreSpecificType(JavaType type1, JavaType type2); public JavaType constructType(Type type); public JavaType constructType(Type type, TypeBindings bindings); public JavaType constructType(TypeReference<?> typeRef); @Deprecated public JavaType constructType(Type type, Class<?> contextClass); @Deprecated public JavaType constructType(Type type, JavaType contextType); public ArrayType constructArrayType(Class<?> elementType); public ArrayType constructArrayType(JavaType elementType); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); public MapType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass); public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); @Deprecated public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, JavaType[] parameterTypes); public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); @Deprecated // since 2.8 public JavaType uncheckedSimpleType(Class<?> cls); public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, Class<?>... parameterClasses); public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); public MapType constructRawMapType(Class<? extends Map> mapClass); public MapLikeType constructRawMapLikeType(Class<?> mapClass); private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _unknownType(); protected JavaType _findWellKnownSimple(Class<?> clz); protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, TypeBindings parentBindings); protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings);
553
testRawCollections
```java private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) throws IllegalArgumentException; private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; public JavaType[] findTypeParameters(JavaType type, Class<?> expType); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); public JavaType moreSpecificType(JavaType type1, JavaType type2); public JavaType constructType(Type type); public JavaType constructType(Type type, TypeBindings bindings); public JavaType constructType(TypeReference<?> typeRef); @Deprecated public JavaType constructType(Type type, Class<?> contextClass); @Deprecated public JavaType constructType(Type type, JavaType contextType); public ArrayType constructArrayType(Class<?> elementType); public ArrayType constructArrayType(JavaType elementType); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); public MapType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass); public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); @Deprecated public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, JavaType[] parameterTypes); public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); @Deprecated // since 2.8 public JavaType uncheckedSimpleType(Class<?> cls); public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, Class<?>... parameterClasses); public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); public MapType constructRawMapType(Class<? extends Map> mapClass); public MapLikeType constructRawMapLikeType(Class<?> mapClass); private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _unknownType(); protected JavaType _findWellKnownSimple(Class<?> clz); protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, TypeBindings parentBindings); protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); } // Abstract Java Test Class package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; public class TestTypeFactory extends BaseMapTest { public void testSimpleTypes(); public void testArrays(); public void testProperties(); public void testIterator(); @SuppressWarnings("deprecation") public void testParametricTypes(); public void testCanonicalNames(); @SuppressWarnings("serial") public void testCanonicalWithSpaces(); public void testCollections(); public void testCollectionTypesRefined(); public void testMaps(); public void testMapTypesRefined(); public void testTypeGeneralization(); public void testMapTypesRaw(); public void testMapTypesAdvanced(); public void testMapTypesSneaky(); public void testSneakyFieldTypes() throws Exception; public void testSneakyBeanProperties() throws Exception; public void testSneakySelfRefs() throws Exception; public void testAtomicArrayRefParameters(); public void testMapEntryResolution(); public void testRawCollections(); public void testRawMaps(); public void testMoreSpecificType(); public void testCacheClearing(); public void testRawMapType(); public <T extends Comparable<T>> T getFoobar(); } ``` You are a professional Java test case writer, please create a test case named `testRawCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */
539
// private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) // throws IllegalArgumentException; // private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); // public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); // public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; // public JavaType[] findTypeParameters(JavaType type, Class<?> expType); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); // public JavaType moreSpecificType(JavaType type1, JavaType type2); // public JavaType constructType(Type type); // public JavaType constructType(Type type, TypeBindings bindings); // public JavaType constructType(TypeReference<?> typeRef); // @Deprecated // public JavaType constructType(Type type, Class<?> contextClass); // @Deprecated // public JavaType constructType(Type type, JavaType contextType); // public ArrayType constructArrayType(Class<?> elementType); // public ArrayType constructArrayType(JavaType elementType); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // Class<?> elementClass); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // JavaType elementType); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); // public MapType constructMapType(Class<? extends Map> mapClass, // Class<?> keyClass, Class<?> valueClass); // public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); // public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); // public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); // public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); // @Deprecated // public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, // JavaType[] parameterTypes); // public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); // @Deprecated // since 2.8 // public JavaType uncheckedSimpleType(Class<?> cls); // public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); // public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // Class<?>... parameterClasses); // public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); // public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); // public MapType constructRawMapType(Class<? extends Map> mapClass); // public MapLikeType constructRawMapLikeType(Class<?> mapClass); // private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _unknownType(); // protected JavaType _findWellKnownSimple(Class<?> clz); // protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); // protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); // protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, // TypeBindings parentBindings); // protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); // protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); // protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.type; // // import java.lang.reflect.Field; // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.core.type.TypeReference; // import com.fasterxml.jackson.databind.*; // // // // public class TestTypeFactory // extends BaseMapTest // { // // // public void testSimpleTypes(); // public void testArrays(); // public void testProperties(); // public void testIterator(); // @SuppressWarnings("deprecation") // public void testParametricTypes(); // public void testCanonicalNames(); // @SuppressWarnings("serial") // public void testCanonicalWithSpaces(); // public void testCollections(); // public void testCollectionTypesRefined(); // public void testMaps(); // public void testMapTypesRefined(); // public void testTypeGeneralization(); // public void testMapTypesRaw(); // public void testMapTypesAdvanced(); // public void testMapTypesSneaky(); // public void testSneakyFieldTypes() throws Exception; // public void testSneakyBeanProperties() throws Exception; // public void testSneakySelfRefs() throws Exception; // public void testAtomicArrayRefParameters(); // public void testMapEntryResolution(); // public void testRawCollections(); // public void testRawMaps(); // public void testMoreSpecificType(); // public void testCacheClearing(); // public void testRawMapType(); // public <T extends Comparable<T>> T getFoobar(); // } // You are a professional Java test case writer, please create a test case named `testRawCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */ public void testRawCollections() {
/* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */
112
com.fasterxml.jackson.databind.type.TypeFactory
src/test/java
```java private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) throws IllegalArgumentException; private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; public JavaType[] findTypeParameters(JavaType type, Class<?> expType); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); public JavaType moreSpecificType(JavaType type1, JavaType type2); public JavaType constructType(Type type); public JavaType constructType(Type type, TypeBindings bindings); public JavaType constructType(TypeReference<?> typeRef); @Deprecated public JavaType constructType(Type type, Class<?> contextClass); @Deprecated public JavaType constructType(Type type, JavaType contextType); public ArrayType constructArrayType(Class<?> elementType); public ArrayType constructArrayType(JavaType elementType); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); public MapType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass); public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); @Deprecated public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, JavaType[] parameterTypes); public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); @Deprecated // since 2.8 public JavaType uncheckedSimpleType(Class<?> cls); public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, Class<?>... parameterClasses); public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); public MapType constructRawMapType(Class<? extends Map> mapClass); public MapLikeType constructRawMapLikeType(Class<?> mapClass); private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _unknownType(); protected JavaType _findWellKnownSimple(Class<?> clz); protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, TypeBindings parentBindings); protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); } // Abstract Java Test Class package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; public class TestTypeFactory extends BaseMapTest { public void testSimpleTypes(); public void testArrays(); public void testProperties(); public void testIterator(); @SuppressWarnings("deprecation") public void testParametricTypes(); public void testCanonicalNames(); @SuppressWarnings("serial") public void testCanonicalWithSpaces(); public void testCollections(); public void testCollectionTypesRefined(); public void testMaps(); public void testMapTypesRefined(); public void testTypeGeneralization(); public void testMapTypesRaw(); public void testMapTypesAdvanced(); public void testMapTypesSneaky(); public void testSneakyFieldTypes() throws Exception; public void testSneakyBeanProperties() throws Exception; public void testSneakySelfRefs() throws Exception; public void testAtomicArrayRefParameters(); public void testMapEntryResolution(); public void testRawCollections(); public void testRawMaps(); public void testMoreSpecificType(); public void testCacheClearing(); public void testRawMapType(); public <T extends Comparable<T>> T getFoobar(); } ``` You are a professional Java test case writer, please create a test case named `testRawCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */ public void testRawCollections() { ```
@SuppressWarnings({"rawtypes" }) public final class TypeFactory implements java.io.Serializable
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*;
public void testSimpleTypes(); public void testArrays(); public void testProperties(); public void testIterator(); @SuppressWarnings("deprecation") public void testParametricTypes(); public void testCanonicalNames(); @SuppressWarnings("serial") public void testCanonicalWithSpaces(); public void testCollections(); public void testCollectionTypesRefined(); public void testMaps(); public void testMapTypesRefined(); public void testTypeGeneralization(); public void testMapTypesRaw(); public void testMapTypesAdvanced(); public void testMapTypesSneaky(); public void testSneakyFieldTypes() throws Exception; public void testSneakyBeanProperties() throws Exception; public void testSneakySelfRefs() throws Exception; public void testAtomicArrayRefParameters(); public void testMapEntryResolution(); public void testRawCollections(); public void testRawMaps(); public void testMoreSpecificType(); public void testCacheClearing(); public void testRawMapType(); public <T extends Comparable<T>> T getFoobar();
c844b9e144d166884d34fe3c1abb3a14f2e339c92e60c63fc984cc07ae7eeb12
[ "com.fasterxml.jackson.databind.type.TestTypeFactory::testRawCollections" ]
private static final long serialVersionUID = 1L; private final static JavaType[] NO_TYPES = new JavaType[0]; protected final static TypeFactory instance = new TypeFactory(); protected final static TypeBindings EMPTY_BINDINGS = TypeBindings.emptyBindings(); private final static Class<?> CLS_STRING = String.class; private final static Class<?> CLS_OBJECT = Object.class; private final static Class<?> CLS_COMPARABLE = Comparable.class; private final static Class<?> CLS_CLASS = Class.class; private final static Class<?> CLS_ENUM = Enum.class; private final static Class<?> CLS_BOOL = Boolean.TYPE; private final static Class<?> CLS_INT = Integer.TYPE; private final static Class<?> CLS_LONG = Long.TYPE; protected final static SimpleType CORE_TYPE_BOOL = new SimpleType(CLS_BOOL); protected final static SimpleType CORE_TYPE_INT = new SimpleType(CLS_INT); protected final static SimpleType CORE_TYPE_LONG = new SimpleType(CLS_LONG); protected final static SimpleType CORE_TYPE_STRING = new SimpleType(CLS_STRING); protected final static SimpleType CORE_TYPE_OBJECT = new SimpleType(CLS_OBJECT); protected final static SimpleType CORE_TYPE_COMPARABLE = new SimpleType(CLS_COMPARABLE); protected final static SimpleType CORE_TYPE_ENUM = new SimpleType(CLS_ENUM); protected final static SimpleType CORE_TYPE_CLASS = new SimpleType(CLS_CLASS); protected final LRUMap<Object,JavaType> _typeCache; protected final TypeModifier[] _modifiers; protected final TypeParser _parser; protected final ClassLoader _classLoader;
public void testRawCollections()
JacksonDatabind
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; /** * Simple tests to verify that the {@link TypeFactory} constructs * type information as expected. */ public class TestTypeFactory extends BaseMapTest { /* /********************************************************** /* Helper types /********************************************************** */ enum EnumForCanonical { YES, NO; } static class SingleArgGeneric<X> { } abstract static class MyMap extends IntermediateMap<String,Long> { } abstract static class IntermediateMap<K,V> implements Map<K,V> { } abstract static class MyList extends IntermediateList<Long> { } abstract static class IntermediateList<E> implements List<E> { } @SuppressWarnings("serial") static class GenericList<T> extends ArrayList<T> { } interface MapInterface extends Cloneable, IntermediateInterfaceMap<String> { } interface IntermediateInterfaceMap<FOO> extends Map<FOO, Integer> { } @SuppressWarnings("serial") static class MyStringIntMap extends MyStringXMap<Integer> { } @SuppressWarnings("serial") static class MyStringXMap<V> extends HashMap<String,V> { } // And one more, now with obfuscated type names; essentially it's just Map<Int,Long> static abstract class IntLongMap extends XLongMap<Integer> { } // trick here is that V now refers to key type, not value type static abstract class XLongMap<V> extends XXMap<V,Long> { } static abstract class XXMap<K,V> implements Map<K,V> { } static class SneakyBean { public IntLongMap intMap; public MyList longList; } static class SneakyBean2 { // self-reference; should be resolved as "Comparable<Object>" public <T extends Comparable<T>> T getFoobar() { return null; } } @SuppressWarnings("serial") public static class LongValuedMap<K> extends HashMap<K, Long> { } static class StringLongMapBean { public LongValuedMap<String> value; } static class StringListBean { public GenericList<String> value; } static class CollectionLike<E> { } static class MapLike<K,V> { } static class Wrapper1297<T> { public T content; } /* /********************************************************** /* Unit tests /********************************************************** */ public void testSimpleTypes() { Class<?>[] classes = new Class<?>[] { boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class, Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, Object.class, Calendar.class, Date.class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); assertSame(clz, tf.constructType(clz).getRawClass()); } } public void testArrays() { Class<?>[] classes = new Class<?>[] { boolean[].class, byte[].class, char[].class, short[].class, int[].class, long[].class, float[].class, double[].class, String[].class, Object[].class, Calendar[].class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); Class<?> elemType = clz.getComponentType(); assertSame(clz, tf.constructArrayType(elemType).getRawClass()); } } // [databind#810]: Fake Map type for Properties as <String,String> public void testProperties() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(Properties.class); assertEquals(MapType.class, t.getClass()); assertSame(Properties.class, t.getRawClass()); MapType mt = (MapType) t; // so far so good. But how about parameterization? assertSame(String.class, mt.getKeyType().getRawClass()); assertSame(String.class, mt.getContentType().getRawClass()); } public void testIterator() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(new TypeReference<Iterator<String>>() { }); assertEquals(SimpleType.class, t.getClass()); assertSame(Iterator.class, t.getRawClass()); assertEquals(1, t.containedTypeCount()); assertEquals(tf.constructType(String.class), t.containedType(0)); assertNull(t.containedType(1)); } /** * Test for verifying that parametric types can be constructed * programmatically */ @SuppressWarnings("deprecation") public void testParametricTypes() { TypeFactory tf = TypeFactory.defaultInstance(); // first, simple class based JavaType t = tf.constructParametrizedType(ArrayList.class, Collection.class, String.class); // ArrayList<String> assertEquals(CollectionType.class, t.getClass()); JavaType strC = tf.constructType(String.class); assertEquals(1, t.containedTypeCount()); assertEquals(strC, t.containedType(0)); assertNull(t.containedType(1)); // Then using JavaType JavaType t2 = tf.constructParametrizedType(Map.class, Map.class, strC, t); // Map<String,ArrayList<String>> // should actually produce a MapType assertEquals(MapType.class, t2.getClass()); assertEquals(2, t2.containedTypeCount()); assertEquals(strC, t2.containedType(0)); assertEquals(t, t2.containedType(1)); assertNull(t2.containedType(2)); // and then custom generic type as well JavaType custom = tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, String.class); assertEquals(SimpleType.class, custom.getClass()); assertEquals(1, custom.containedTypeCount()); assertEquals(strC, custom.containedType(0)); assertNull(custom.containedType(1)); // should also be able to access variable name: assertEquals("X", custom.containedTypeName(0)); // And finally, ensure that we can't create invalid combinations try { // Maps must take 2 type parameters, not just one tf.constructParametrizedType(Map.class, Map.class, strC); } catch (IllegalArgumentException e) { verifyException(e, "Cannot create TypeBindings for class java.util.Map"); } try { // Type only accepts one type param tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, strC, strC); } catch (IllegalArgumentException e) { verifyException(e, "Cannot create TypeBindings for class "); } } /** * Test for checking that canonical name handling works ok */ public void testCanonicalNames() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(java.util.Calendar.class); String can = t.toCanonical(); assertEquals("java.util.Calendar", can); assertEquals(t, tf.constructFromCanonical(can)); // Generic maps and collections will default to Object.class if type-erased t = tf.constructType(java.util.ArrayList.class); can = t.toCanonical(); assertEquals("java.util.ArrayList<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); t = tf.constructType(java.util.TreeMap.class); can = t.toCanonical(); assertEquals("java.util.TreeMap<java.lang.Object,java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); // And then EnumMap (actual use case for us) t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class); can = t.toCanonical(); assertEquals("java.util.EnumMap<com.fasterxml.jackson.databind.type.TestTypeFactory$EnumForCanonical,java.lang.String>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#2109]: also ReferenceTypes t = tf.constructType(new TypeReference<AtomicReference<Long>>() { }); can = t.toCanonical(); assertEquals("java.util.concurrent.atomic.AtomicReference<java.lang.Long>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#1941]: allow "raw" types too t = tf.constructFromCanonical("java.util.List"); assertEquals(List.class, t.getRawClass()); assertEquals(CollectionType.class, t.getClass()); // 01-Mar-2018, tatu: not 100% should we expect type parameters here... // But currently we do NOT get any /* assertEquals(1, t.containedTypeCount()); assertEquals(Object.class, t.containedType(0).getRawClass()); */ assertEquals(Object.class, t.getContentType().getRawClass()); can = t.toCanonical(); assertEquals("java.util.List<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); } // [databind#1768] @SuppressWarnings("serial") public void testCanonicalWithSpaces() { TypeFactory tf = TypeFactory.defaultInstance(); Object objects = new TreeMap<Object, Object>() { }; // to get subtype String reflectTypeName = objects.getClass().getGenericSuperclass().toString(); JavaType t1 = tf.constructType(objects.getClass().getGenericSuperclass()); // This will throw an Exception if you don't remove all white spaces from the String. JavaType t2 = tf.constructFromCanonical(reflectTypeName); assertNotNull(t2); assertEquals(t2, t1); } /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */ public void testCollections() { // Ok, first: let's test what happens when we pass 'raw' Collection: TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(ArrayList.class); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); // And then the proper way t = tf.constructType(new TypeReference<ArrayList<String>>() { }); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); JavaType elemType = ((CollectionType) t).getContentType(); assertNotNull(elemType); assertSame(SimpleType.class, elemType.getClass()); assertSame(String.class, elemType.getRawClass()); // And alternate method too t = tf.constructCollectionType(ArrayList.class, String.class); assertEquals(CollectionType.class, t.getClass()); assertSame(String.class, ((CollectionType) t).getContentType().getRawClass()); } // since 2.7 public void testCollectionTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<List<Long>>() { }); assertEquals(List.class, type.getRawClass()); assertEquals(Long.class, type.getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, ArrayList.class); assertEquals(ArrayList.class, subtype.getRawClass()); assertEquals(Long.class, subtype.getContentType().getRawClass()); // but with refinement, should have non-null super class JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(AbstractList.class, superType.getRawClass()); } /* /********************************************************** /* Unit tests: map type parameter resolution /********************************************************** */ public void testMaps() { TypeFactory tf = newTypeFactory(); // Ok, first: let's test what happens when we pass 'raw' Map: JavaType t = tf.constructType(HashMap.class); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); // Then explicit construction t = tf.constructMapType(TreeMap.class, String.class, Integer.class); assertEquals(MapType.class, t.getClass()); assertSame(String.class, ((MapType) t).getKeyType().getRawClass()); assertSame(Integer.class, ((MapType) t).getContentType().getRawClass()); // And then with TypeReference t = tf.constructType(new TypeReference<HashMap<String,Integer>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); MapType mt = (MapType) t; assertEquals(tf.constructType(String.class), mt.getKeyType()); assertEquals(tf.constructType(Integer.class), mt.getContentType()); t = tf.constructType(new TypeReference<LongValuedMap<Boolean>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(LongValuedMap.class, t.getRawClass()); mt = (MapType) t; assertEquals(tf.constructType(Boolean.class), mt.getKeyType()); assertEquals(tf.constructType(Long.class), mt.getContentType()); JavaType type = tf.constructType(new TypeReference<Map<String,Boolean>>() { }); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Boolean.class), mapType.getContentType()); } // since 2.7 public void testMapTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<Map<String,List<Integer>>>() { }); MapType mapType = (MapType) type; assertEquals(Map.class, mapType.getRawClass()); assertEquals(String.class, mapType.getKeyType().getRawClass()); assertEquals(List.class, mapType.getContentType().getRawClass()); assertEquals(Integer.class, mapType.getContentType().getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, LinkedHashMap.class); assertEquals(LinkedHashMap.class, subtype.getRawClass()); assertEquals(String.class, subtype.getKeyType().getRawClass()); assertEquals(List.class, subtype.getContentType().getRawClass()); assertEquals(Integer.class, subtype.getContentType().getContentType().getRawClass()); // but with refinement, should have non-null super class JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(HashMap.class, superType.getRawClass()); // which also should have proper typing assertEquals(String.class, superType.getKeyType().getRawClass()); assertEquals(List.class, superType.getContentType().getRawClass()); assertEquals(Integer.class, superType.getContentType().getContentType().getRawClass()); } public void testTypeGeneralization() { TypeFactory tf = newTypeFactory(); MapType t = tf.constructMapType(HashMap.class, String.class, Long.class); JavaType superT = tf.constructGeneralizedType(t, Map.class); assertEquals(String.class, superT.getKeyType().getRawClass()); assertEquals(Long.class, superT.getContentType().getRawClass()); assertSame(t, tf.constructGeneralizedType(t, HashMap.class)); // plus check there is super/sub relationship try { tf.constructGeneralizedType(t, TreeMap.class); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "not a super-type of"); } } public void testMapTypesRaw() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(HashMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Object.class), mapType.getKeyType()); assertEquals(tf.constructType(Object.class), mapType.getContentType()); } public void testMapTypesAdvanced() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(MyMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); type = tf.constructType(MapInterface.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); type = tf.constructType(MyStringIntMap.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); } /** * Specific test to verify that complicate name mangling schemes * do not fool type resolver */ public void testMapTypesSneaky() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(IntLongMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); } /** * Plus sneaky types may be found via introspection as well. */ public void testSneakyFieldTypes() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Field field = SneakyBean.class.getDeclaredField("intMap"); JavaType type = tf.constructType(field.getGenericType()); assertTrue(type instanceof MapType); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); field = SneakyBean.class.getDeclaredField("longList"); type = tf.constructType(field.getGenericType()); assertTrue(type instanceof CollectionType); CollectionType collectionType = (CollectionType) type; assertEquals(tf.constructType(Long.class), collectionType.getContentType()); } /** * Looks like type handling actually differs for properties, too. */ public void testSneakyBeanProperties() throws Exception { ObjectMapper mapper = new ObjectMapper(); StringLongMapBean bean = mapper.readValue("{\"value\":{\"a\":123}}", StringLongMapBean.class); assertNotNull(bean); Map<String,Long> map = bean.value; assertEquals(1, map.size()); assertEquals(Long.valueOf(123), map.get("a")); StringListBean bean2 = mapper.readValue("{\"value\":[\"...\"]}", StringListBean.class); assertNotNull(bean2); List<String> list = bean2.value; assertSame(GenericList.class, list.getClass()); assertEquals(1, list.size()); assertEquals("...", list.get(0)); } public void testSneakySelfRefs() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(new SneakyBean2()); assertEquals("{\"foobar\":null}", json); } /* /********************************************************** /* Unit tests: handling of specific JDK types /********************************************************** */ public void testAtomicArrayRefParameters() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(new TypeReference<AtomicReference<long[]>>() { }); JavaType[] params = tf.findTypeParameters(type, AtomicReference.class); assertNotNull(params); assertEquals(1, params.length); assertEquals(tf.constructType(long[].class), params[0]); } static abstract class StringIntMapEntry implements Map.Entry<String,Integer> { } public void testMapEntryResolution() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(StringIntMapEntry.class); JavaType mapEntryType = t.findSuperType(Map.Entry.class); assertNotNull(mapEntryType); assertTrue(mapEntryType.hasGenericTypes()); assertEquals(2, mapEntryType.containedTypeCount()); assertEquals(String.class, mapEntryType.containedType(0).getRawClass()); assertEquals(Integer.class, mapEntryType.containedType(1).getRawClass()); } /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */ public void testRawCollections() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawCollectionType(ArrayList.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawCollectionLikeType(CollectionLike.class); // must have type vars assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawCollectionLikeType(String.class); assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } public void testRawMaps() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawMapType(HashMap.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawMapLikeType(MapLike.class); // must have type vars assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawMapLikeType(String.class); assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } /* /********************************************************** /* Unit tests: other /********************************************************** */ public void testMoreSpecificType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t1 = tf.constructCollectionType(Collection.class, Object.class); JavaType t2 = tf.constructCollectionType(List.class, Object.class); assertSame(t2, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); t1 = tf.constructType(Double.class); t2 = tf.constructType(Number.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t1, tf.moreSpecificType(t2, t1)); // and then unrelated, return first t1 = tf.constructType(Double.class); t2 = tf.constructType(String.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); } // [databind#489] public void testCacheClearing() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); assertEquals(0, tf._typeCache.size()); tf.constructType(getClass()); // 19-Oct-2015, tatu: This is pretty fragile but assertEquals(6, tf._typeCache.size()); tf.clearCache(); assertEquals(0, tf._typeCache.size()); } // for [databind#1297] public void testRawMapType() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); // to get a new copy JavaType type = tf.constructParametricType(Wrapper1297.class, Map.class); assertNotNull(type); assertEquals(Wrapper1297.class, type.getRawClass()); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_collectionType", "be_test_function_signature": "(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;Lcom/fasterxml/jackson/databind/JavaType;[Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1109", "1112", "1113", "1114", "1115", "1117", "1119" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_findWellKnownSimple", "be_test_function_signature": "(Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1188", "1189", "1190", "1191", "1193", "1194", "1196" ], "method_line_rate": 0.5714285714285714 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromAny", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/reflect/Type;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1215", "1217", "1220", "1221", "1223", "1225", "1227", "1228", "1230", "1231", "1233", "1234", "1237", "1242", "1243", "1244", "1245", "1247", "1248", "1249", "1250", "1254", "1257" ], "method_line_rate": 0.43478260869565216 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromClass", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1267", "1268", "1269", "1273", "1274", "1276", "1278", "1279", "1280", "1284", "1285", "1287", "1288", "1290", "1291", "1292", "1295", "1299", "1300", "1308", "1309", "1310", "1313", "1314", "1318", "1319", "1324", "1325", "1328", "1329", "1330", "1331", "1332", "1334", "1339", "1342", "1343", "1345" ], "method_line_rate": 0.868421052631579 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromParamType", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/reflect/ParameterizedType;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1426", "1430", "1431", "1433", "1434", "1436", "1437", "1443", "1444", "1447", "1448", "1450", "1451", "1452", "1454", "1456" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromVariable", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/reflect/TypeVariable;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1468", "1469", "1470", "1472", "1473", "1474", "1478", "1479", "1481", "1492", "1493", "1494", "1495" ], "method_line_rate": 0.38461538461538464 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromWellKnownClass", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;Lcom/fasterxml/jackson/databind/JavaType;[Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1380", "1381", "1385", "1386", "1388", "1389", "1392", "1393", "1399" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromWellKnownInterface", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;Lcom/fasterxml/jackson/databind/JavaType;[Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1407", "1409", "1410", "1411", "1412", "1415" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_newSimpleType", "be_test_function_signature": "(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;Lcom/fasterxml/jackson/databind/JavaType;[Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1168" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_resolveSuperClass", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1350", "1351", "1352", "1354" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_resolveSuperInterfaces", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;)[Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1359", "1360", "1361", "1363", "1364", "1365", "1366", "1367", "1369" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_unknownType", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1177" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "constructCollectionLikeType", "be_test_function_signature": "(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/type/CollectionLikeType;", "line_numbers": [ "781", "783", "784", "786" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "constructCollectionType", "be_test_function_signature": "(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/type/CollectionType;", "line_numbers": [ "747", "748", "751", "752", "753", "754", "755", "760" ], "method_line_rate": 0.5 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "constructRawCollectionLikeType", "be_test_function_signature": "(Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/type/CollectionLikeType;", "line_numbers": [ "1041" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "constructRawCollectionType", "be_test_function_signature": "(Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/type/CollectionType;", "line_numbers": [ "1026" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "defaultInstance", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/type/TypeFactory;", "line_numbers": [ "211" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "unknownType", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "243" ], "method_line_rate": 1 } ]
public class TestValueInstantiator extends BaseMapTest
public void testDelegateBeanInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyBean.class, new MyDelegateBeanInstantiator())); MyBean bean = mapper.readValue("123", MyBean.class); assertNotNull(bean); assertEquals("123", bean._secret); }
// import com.fasterxml.jackson.databind.module.SimpleModule; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // public class TestValueInstantiator extends BaseMapTest // { // private final ObjectMapper MAPPER = objectMapper(); // // public void testCustomBeanInstantiator() throws Exception; // public void testCustomListInstantiator() throws Exception; // public void testCustomMapInstantiator() throws Exception; // public void testDelegateBeanInstantiator() throws Exception; // public void testDelegateListInstantiator() throws Exception; // public void testDelegateMapInstantiator() throws Exception; // public void testCustomDelegateInstantiator() throws Exception; // public void testPropertyBasedBeanInstantiator() throws Exception; // public void testPropertyBasedMapInstantiator() throws Exception; // public void testBeanFromString() throws Exception; // public void testBeanFromInt() throws Exception; // public void testBeanFromLong() throws Exception; // public void testBeanFromDouble() throws Exception; // public void testBeanFromBoolean() throws Exception; // public void testPolymorphicCreatorBean() throws Exception; // public void testEmptyBean() throws Exception; // public void testErrorMessageForMissingCtor() throws Exception; // public void testErrorMessageForMissingStringCtor() throws Exception; // public MyBean(String s, boolean bogus); // public MysteryBean(Object v); // protected CreatorBean(String s); // public InstantiatorBase(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // public MyList(boolean b); // public MyMap(boolean b); // public MyMap(String name); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public MyBean createUsingDefault(DeserializationContext ctxt); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateFromObjectWith(); // @Override // public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); // @Override // public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateFromObjectWith(); // @Override // public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); // @Override // public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); // public MyDelegateBeanInstantiator(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public MyList createUsingDefault(DeserializationContext ctxt); // public MyDelegateListInstantiator(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public MyMap createUsingDefault(DeserializationContext ctxt); // public MyDelegateMapInstantiator(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); // public AnnotatedBean(String a, int b); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public AnnotatedBean createUsingDefault(DeserializationContext ctxt); // public MyModule(Class<?> cls, ValueInstantiator inst); // public AnnotatedBeanDelegating(Object v, boolean bogus); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public AnnotatedWithParams getDelegateCreator(); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException; // @Override // public boolean canCreateFromObjectWith(); // @Override // public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); // @Override // public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); // @Override // public boolean canCreateFromString(); // @Override // public Object createFromString(DeserializationContext ctxt, String value); // @Override // public boolean canCreateFromInt(); // @Override // public Object createFromInt(DeserializationContext ctxt, int value); // @Override // public boolean canCreateFromLong(); // @Override // public Object createFromLong(DeserializationContext ctxt, long value); // @Override // public boolean canCreateFromDouble(); // @Override // public Object createFromDouble(DeserializationContext ctxt, double value); // @Override // public boolean canCreateFromBoolean(); // @Override // public Object createFromBoolean(DeserializationContext ctxt, boolean value); // } // You are a professional Java test case writer, please create a test case named `testDelegateBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests for delegate creators /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/deser/creators/TestValueInstantiator.java
package com.fasterxml.jackson.databind.deser; import java.io.IOException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.impl.PropertyValueBuffer; import com.fasterxml.jackson.databind.introspect.AnnotatedParameter; import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams;
public Class<?> getValueClass(); public String getValueTypeDesc(); public boolean canInstantiate(); public boolean canCreateFromString(); public boolean canCreateFromInt(); public boolean canCreateFromLong(); public boolean canCreateFromDouble(); public boolean canCreateFromBoolean(); public boolean canCreateUsingDefault(); public boolean canCreateUsingDelegate(); public boolean canCreateUsingArrayDelegate(); public boolean canCreateFromObjectWith(); public SettableBeanProperty[] getFromObjectArguments(DeserializationConfig config); public JavaType getDelegateType(DeserializationConfig config); public JavaType getArrayDelegateType(DeserializationConfig config); public Object createUsingDefault(DeserializationContext ctxt) throws IOException; public Object createFromObjectWith(DeserializationContext ctxt, Object[] args) throws IOException; public Object createFromObjectWith(DeserializationContext ctxt, SettableBeanProperty[] props, PropertyValueBuffer buffer) throws IOException; public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException; public Object createUsingArrayDelegate(DeserializationContext ctxt, Object delegate) throws IOException; public Object createFromString(DeserializationContext ctxt, String value) throws IOException; public Object createFromInt(DeserializationContext ctxt, int value) throws IOException; public Object createFromLong(DeserializationContext ctxt, long value) throws IOException; public Object createFromDouble(DeserializationContext ctxt, double value) throws IOException; public Object createFromBoolean(DeserializationContext ctxt, boolean value) throws IOException; public AnnotatedWithParams getDefaultCreator(); public AnnotatedWithParams getDelegateCreator(); public AnnotatedWithParams getArrayDelegateCreator(); public AnnotatedWithParams getWithArgsCreator(); public AnnotatedParameter getIncompleteParameter(); protected Object _createFromStringFallbacks(DeserializationContext ctxt, String value) throws IOException; public Base(Class<?> type); public Base(JavaType type); @Override public String getValueTypeDesc(); @Override public Class<?> getValueClass();
383
testDelegateBeanInstantiator
```java import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.TypeFactory; public class TestValueInstantiator extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); public void testCustomBeanInstantiator() throws Exception; public void testCustomListInstantiator() throws Exception; public void testCustomMapInstantiator() throws Exception; public void testDelegateBeanInstantiator() throws Exception; public void testDelegateListInstantiator() throws Exception; public void testDelegateMapInstantiator() throws Exception; public void testCustomDelegateInstantiator() throws Exception; public void testPropertyBasedBeanInstantiator() throws Exception; public void testPropertyBasedMapInstantiator() throws Exception; public void testBeanFromString() throws Exception; public void testBeanFromInt() throws Exception; public void testBeanFromLong() throws Exception; public void testBeanFromDouble() throws Exception; public void testBeanFromBoolean() throws Exception; public void testPolymorphicCreatorBean() throws Exception; public void testEmptyBean() throws Exception; public void testErrorMessageForMissingCtor() throws Exception; public void testErrorMessageForMissingStringCtor() throws Exception; public MyBean(String s, boolean bogus); public MysteryBean(Object v); protected CreatorBean(String s); public InstantiatorBase(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); public MyList(boolean b); public MyMap(boolean b); public MyMap(String name); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyBean createUsingDefault(DeserializationContext ctxt); @Override public String getValueTypeDesc(); @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); @Override public String getValueTypeDesc(); @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); public MyDelegateBeanInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyList createUsingDefault(DeserializationContext ctxt); public MyDelegateListInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyMap createUsingDefault(DeserializationContext ctxt); public MyDelegateMapInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); public AnnotatedBean(String a, int b); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public AnnotatedBean createUsingDefault(DeserializationContext ctxt); public MyModule(Class<?> cls, ValueInstantiator inst); public AnnotatedBeanDelegating(Object v, boolean bogus); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public AnnotatedWithParams getDelegateCreator(); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException; @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); @Override public boolean canCreateFromString(); @Override public Object createFromString(DeserializationContext ctxt, String value); @Override public boolean canCreateFromInt(); @Override public Object createFromInt(DeserializationContext ctxt, int value); @Override public boolean canCreateFromLong(); @Override public Object createFromLong(DeserializationContext ctxt, long value); @Override public boolean canCreateFromDouble(); @Override public Object createFromDouble(DeserializationContext ctxt, double value); @Override public boolean canCreateFromBoolean(); @Override public Object createFromBoolean(DeserializationContext ctxt, boolean value); } ``` You are a professional Java test case writer, please create a test case named `testDelegateBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests for delegate creators /********************************************************** */
376
// import com.fasterxml.jackson.databind.module.SimpleModule; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // public class TestValueInstantiator extends BaseMapTest // { // private final ObjectMapper MAPPER = objectMapper(); // // public void testCustomBeanInstantiator() throws Exception; // public void testCustomListInstantiator() throws Exception; // public void testCustomMapInstantiator() throws Exception; // public void testDelegateBeanInstantiator() throws Exception; // public void testDelegateListInstantiator() throws Exception; // public void testDelegateMapInstantiator() throws Exception; // public void testCustomDelegateInstantiator() throws Exception; // public void testPropertyBasedBeanInstantiator() throws Exception; // public void testPropertyBasedMapInstantiator() throws Exception; // public void testBeanFromString() throws Exception; // public void testBeanFromInt() throws Exception; // public void testBeanFromLong() throws Exception; // public void testBeanFromDouble() throws Exception; // public void testBeanFromBoolean() throws Exception; // public void testPolymorphicCreatorBean() throws Exception; // public void testEmptyBean() throws Exception; // public void testErrorMessageForMissingCtor() throws Exception; // public void testErrorMessageForMissingStringCtor() throws Exception; // public MyBean(String s, boolean bogus); // public MysteryBean(Object v); // protected CreatorBean(String s); // public InstantiatorBase(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // public MyList(boolean b); // public MyMap(boolean b); // public MyMap(String name); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public MyBean createUsingDefault(DeserializationContext ctxt); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateFromObjectWith(); // @Override // public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); // @Override // public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateFromObjectWith(); // @Override // public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); // @Override // public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); // public MyDelegateBeanInstantiator(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public MyList createUsingDefault(DeserializationContext ctxt); // public MyDelegateListInstantiator(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public MyMap createUsingDefault(DeserializationContext ctxt); // public MyDelegateMapInstantiator(); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); // public AnnotatedBean(String a, int b); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDefault(); // @Override // public AnnotatedBean createUsingDefault(DeserializationContext ctxt); // public MyModule(Class<?> cls, ValueInstantiator inst); // public AnnotatedBeanDelegating(Object v, boolean bogus); // @Override // public String getValueTypeDesc(); // @Override // public boolean canCreateUsingDelegate(); // @Override // public JavaType getDelegateType(DeserializationConfig config); // @Override // public AnnotatedWithParams getDelegateCreator(); // @Override // public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException; // @Override // public boolean canCreateFromObjectWith(); // @Override // public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); // @Override // public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); // @Override // public boolean canCreateFromString(); // @Override // public Object createFromString(DeserializationContext ctxt, String value); // @Override // public boolean canCreateFromInt(); // @Override // public Object createFromInt(DeserializationContext ctxt, int value); // @Override // public boolean canCreateFromLong(); // @Override // public Object createFromLong(DeserializationContext ctxt, long value); // @Override // public boolean canCreateFromDouble(); // @Override // public Object createFromDouble(DeserializationContext ctxt, double value); // @Override // public boolean canCreateFromBoolean(); // @Override // public Object createFromBoolean(DeserializationContext ctxt, boolean value); // } // You are a professional Java test case writer, please create a test case named `testDelegateBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests for delegate creators /********************************************************** */ public void testDelegateBeanInstantiator() throws Exception {
/* /********************************************************** /* Unit tests for delegate creators /********************************************************** */
112
com.fasterxml.jackson.databind.deser.ValueInstantiator
src/test/java
```java import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.TypeFactory; public class TestValueInstantiator extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); public void testCustomBeanInstantiator() throws Exception; public void testCustomListInstantiator() throws Exception; public void testCustomMapInstantiator() throws Exception; public void testDelegateBeanInstantiator() throws Exception; public void testDelegateListInstantiator() throws Exception; public void testDelegateMapInstantiator() throws Exception; public void testCustomDelegateInstantiator() throws Exception; public void testPropertyBasedBeanInstantiator() throws Exception; public void testPropertyBasedMapInstantiator() throws Exception; public void testBeanFromString() throws Exception; public void testBeanFromInt() throws Exception; public void testBeanFromLong() throws Exception; public void testBeanFromDouble() throws Exception; public void testBeanFromBoolean() throws Exception; public void testPolymorphicCreatorBean() throws Exception; public void testEmptyBean() throws Exception; public void testErrorMessageForMissingCtor() throws Exception; public void testErrorMessageForMissingStringCtor() throws Exception; public MyBean(String s, boolean bogus); public MysteryBean(Object v); protected CreatorBean(String s); public InstantiatorBase(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); public MyList(boolean b); public MyMap(boolean b); public MyMap(String name); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyBean createUsingDefault(DeserializationContext ctxt); @Override public String getValueTypeDesc(); @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); @Override public String getValueTypeDesc(); @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); public MyDelegateBeanInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyList createUsingDefault(DeserializationContext ctxt); public MyDelegateListInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyMap createUsingDefault(DeserializationContext ctxt); public MyDelegateMapInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); public AnnotatedBean(String a, int b); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public AnnotatedBean createUsingDefault(DeserializationContext ctxt); public MyModule(Class<?> cls, ValueInstantiator inst); public AnnotatedBeanDelegating(Object v, boolean bogus); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public AnnotatedWithParams getDelegateCreator(); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException; @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); @Override public boolean canCreateFromString(); @Override public Object createFromString(DeserializationContext ctxt, String value); @Override public boolean canCreateFromInt(); @Override public Object createFromInt(DeserializationContext ctxt, int value); @Override public boolean canCreateFromLong(); @Override public Object createFromLong(DeserializationContext ctxt, long value); @Override public boolean canCreateFromDouble(); @Override public Object createFromDouble(DeserializationContext ctxt, double value); @Override public boolean canCreateFromBoolean(); @Override public Object createFromBoolean(DeserializationContext ctxt, boolean value); } ``` You are a professional Java test case writer, please create a test case named `testDelegateBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests for delegate creators /********************************************************** */ public void testDelegateBeanInstantiator() throws Exception { ```
public abstract class ValueInstantiator
package com.fasterxml.jackson.databind.deser.creators; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonValueInstantiator; import com.fasterxml.jackson.databind.deser.*; import com.fasterxml.jackson.databind.exc.InvalidDefinitionException; import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.TypeFactory;
public void testCustomBeanInstantiator() throws Exception; public void testCustomListInstantiator() throws Exception; public void testCustomMapInstantiator() throws Exception; public void testDelegateBeanInstantiator() throws Exception; public void testDelegateListInstantiator() throws Exception; public void testDelegateMapInstantiator() throws Exception; public void testCustomDelegateInstantiator() throws Exception; public void testPropertyBasedBeanInstantiator() throws Exception; public void testPropertyBasedMapInstantiator() throws Exception; public void testBeanFromString() throws Exception; public void testBeanFromInt() throws Exception; public void testBeanFromLong() throws Exception; public void testBeanFromDouble() throws Exception; public void testBeanFromBoolean() throws Exception; public void testPolymorphicCreatorBean() throws Exception; public void testEmptyBean() throws Exception; public void testErrorMessageForMissingCtor() throws Exception; public void testErrorMessageForMissingStringCtor() throws Exception; public MyBean(String s, boolean bogus); public MysteryBean(Object v); protected CreatorBean(String s); public InstantiatorBase(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); public MyList(boolean b); public MyMap(boolean b); public MyMap(String name); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyBean createUsingDefault(DeserializationContext ctxt); @Override public String getValueTypeDesc(); @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); @Override public String getValueTypeDesc(); @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); public MyDelegateBeanInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyList createUsingDefault(DeserializationContext ctxt); public MyDelegateListInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public MyMap createUsingDefault(DeserializationContext ctxt); public MyDelegateMapInstantiator(); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate); public AnnotatedBean(String a, int b); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDefault(); @Override public AnnotatedBean createUsingDefault(DeserializationContext ctxt); public MyModule(Class<?> cls, ValueInstantiator inst); public AnnotatedBeanDelegating(Object v, boolean bogus); @Override public String getValueTypeDesc(); @Override public boolean canCreateUsingDelegate(); @Override public JavaType getDelegateType(DeserializationConfig config); @Override public AnnotatedWithParams getDelegateCreator(); @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException; @Override public boolean canCreateFromObjectWith(); @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config); @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args); @Override public boolean canCreateFromString(); @Override public Object createFromString(DeserializationContext ctxt, String value); @Override public boolean canCreateFromInt(); @Override public Object createFromInt(DeserializationContext ctxt, int value); @Override public boolean canCreateFromLong(); @Override public Object createFromLong(DeserializationContext ctxt, long value); @Override public boolean canCreateFromDouble(); @Override public Object createFromDouble(DeserializationContext ctxt, double value); @Override public boolean canCreateFromBoolean(); @Override public Object createFromBoolean(DeserializationContext ctxt, boolean value);
c892e1de848c9302f438bc1a71b1bb499ee64d54e4276b0294ac4ffdfa4eaf01
[ "com.fasterxml.jackson.databind.deser.creators.TestValueInstantiator::testDelegateBeanInstantiator" ]
public void testDelegateBeanInstantiator() throws Exception
private final ObjectMapper MAPPER = objectMapper();
JacksonDatabind
package com.fasterxml.jackson.databind.deser.creators; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonValueInstantiator; import com.fasterxml.jackson.databind.deser.*; import com.fasterxml.jackson.databind.exc.InvalidDefinitionException; import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.TypeFactory; /** * Test custom instantiators. */ public class TestValueInstantiator extends BaseMapTest { static class MyBean { String _secret; public MyBean(String s, boolean bogus) { _secret = s; } } static class MysteryBean { Object value; public MysteryBean(Object v) { value = v; } } static class CreatorBean { String _secret; public String value; protected CreatorBean(String s) { _secret = s; } } static abstract class InstantiatorBase extends ValueInstantiator.Base { public InstantiatorBase() { super(Object.class); } @Override public String getValueTypeDesc() { return "UNKNOWN"; } @Override public boolean canCreateUsingDelegate() { return false; } } static abstract class PolymorphicBeanBase { } static class PolymorphicBean extends PolymorphicBeanBase { public String name; } @SuppressWarnings("serial") static class MyList extends ArrayList<Object> { public MyList(boolean b) { super(); } } @SuppressWarnings("serial") static class MyMap extends HashMap<String,Object> { public MyMap(boolean b) { super(); } public MyMap(String name) { super(); put(name, name); } } static class MyBeanInstantiator extends InstantiatorBase { @Override public String getValueTypeDesc() { return MyBean.class.getName(); } @Override public boolean canCreateUsingDefault() { return true; } @Override public MyBean createUsingDefault(DeserializationContext ctxt) { return new MyBean("secret!", true); } } /** * Something more ambitious: semi-automated approach to polymorphic * deserialization, using ValueInstantiator; from Object to any * type... */ static class PolymorphicBeanInstantiator extends InstantiatorBase { @Override public String getValueTypeDesc() { return Object.class.getName(); } @Override public boolean canCreateFromObjectWith() { return true; } @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config) { return new CreatorProperty[] { new CreatorProperty(new PropertyName("type"), config.constructType(Class.class), null, null, null, null, 0, null, PropertyMetadata.STD_REQUIRED) }; } @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args) { try { Class<?> cls = (Class<?>) args[0]; return cls.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } } static class CreatorMapInstantiator extends InstantiatorBase { @Override public String getValueTypeDesc() { return MyMap.class.getName(); } @Override public boolean canCreateFromObjectWith() { return true; } @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config) { return new CreatorProperty[] { new CreatorProperty(new PropertyName("name"), config.constructType(String.class), null, null, null, null, 0, null, PropertyMetadata.STD_REQUIRED) }; } @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args) { return new MyMap((String) args[0]); } } static class MyDelegateBeanInstantiator extends ValueInstantiator.Base { public MyDelegateBeanInstantiator() { super(Object.class); } @Override public String getValueTypeDesc() { return "xxx"; } @Override public boolean canCreateUsingDelegate() { return true; } @Override public JavaType getDelegateType(DeserializationConfig config) { return config.constructType(Object.class); } @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) { return new MyBean(""+delegate, true); } } static class MyListInstantiator extends InstantiatorBase { @Override public String getValueTypeDesc() { return MyList.class.getName(); } @Override public boolean canCreateUsingDefault() { return true; } @Override public MyList createUsingDefault(DeserializationContext ctxt) { return new MyList(true); } } static class MyDelegateListInstantiator extends ValueInstantiator.Base { public MyDelegateListInstantiator() { super(Object.class); } @Override public String getValueTypeDesc() { return "xxx"; } @Override public boolean canCreateUsingDelegate() { return true; } @Override public JavaType getDelegateType(DeserializationConfig config) { return config.constructType(Object.class); } @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) { MyList list = new MyList(true); list.add(delegate); return list; } } static class MyMapInstantiator extends InstantiatorBase { @Override public String getValueTypeDesc() { return MyMap.class.getName(); } @Override public boolean canCreateUsingDefault() { return true; } @Override public MyMap createUsingDefault(DeserializationContext ctxt) { return new MyMap(true); } } static class MyDelegateMapInstantiator extends ValueInstantiator.Base { public MyDelegateMapInstantiator() { super(Object.class); } @Override public String getValueTypeDesc() { return "xxx"; } @Override public boolean canCreateUsingDelegate() { return true; } @Override public JavaType getDelegateType(DeserializationConfig config) { return TypeFactory.defaultInstance().constructType(Object.class); } @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) { MyMap map = new MyMap(true); map.put("value", delegate); return map; } } @JsonValueInstantiator(AnnotatedBeanInstantiator.class) static class AnnotatedBean { protected final String a; protected final int b; public AnnotatedBean(String a, int b) { this.a = a; this.b = b; } } static class AnnotatedBeanInstantiator extends InstantiatorBase { @Override public String getValueTypeDesc() { return AnnotatedBean.class.getName(); } @Override public boolean canCreateUsingDefault() { return true; } @Override public AnnotatedBean createUsingDefault(DeserializationContext ctxt) { return new AnnotatedBean("foo", 3); } } @SuppressWarnings("serial") static class MyModule extends SimpleModule { public MyModule(Class<?> cls, ValueInstantiator inst) { super("Test", Version.unknownVersion()); this.addValueInstantiator(cls, inst); } } @JsonValueInstantiator(AnnotatedBeanDelegatingInstantiator.class) static class AnnotatedBeanDelegating { protected final Object value; public AnnotatedBeanDelegating(Object v, boolean bogus) { value = v; } } static class AnnotatedBeanDelegatingInstantiator extends InstantiatorBase { @Override public String getValueTypeDesc() { return AnnotatedBeanDelegating.class.getName(); } @Override public boolean canCreateUsingDelegate() { return true; } @Override public JavaType getDelegateType(DeserializationConfig config) { return config.constructType(Map.class); } @Override public AnnotatedWithParams getDelegateCreator() { return null; } @Override public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException { return new AnnotatedBeanDelegating(delegate, false); } } /* /********************************************************** /* Unit tests for default creators /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); public void testCustomBeanInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyBean.class, new MyBeanInstantiator())); MyBean bean = mapper.readValue("{}", MyBean.class); assertNotNull(bean); assertEquals("secret!", bean._secret); } public void testCustomListInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyList.class, new MyListInstantiator())); MyList result = mapper.readValue("[]", MyList.class); assertNotNull(result); assertEquals(MyList.class, result.getClass()); assertEquals(0, result.size()); } public void testCustomMapInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyMap.class, new MyMapInstantiator())); MyMap result = mapper.readValue("{ \"a\":\"b\" }", MyMap.class); assertNotNull(result); assertEquals(MyMap.class, result.getClass()); assertEquals(1, result.size()); } /* /********************************************************** /* Unit tests for delegate creators /********************************************************** */ public void testDelegateBeanInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyBean.class, new MyDelegateBeanInstantiator())); MyBean bean = mapper.readValue("123", MyBean.class); assertNotNull(bean); assertEquals("123", bean._secret); } public void testDelegateListInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyList.class, new MyDelegateListInstantiator())); MyList result = mapper.readValue("123", MyList.class); assertNotNull(result); assertEquals(1, result.size()); assertEquals(Integer.valueOf(123), result.get(0)); } public void testDelegateMapInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyMap.class, new MyDelegateMapInstantiator())); MyMap result = mapper.readValue("123", MyMap.class); assertNotNull(result); assertEquals(1, result.size()); assertEquals(Integer.valueOf(123), result.values().iterator().next()); } public void testCustomDelegateInstantiator() throws Exception { AnnotatedBeanDelegating value = MAPPER.readValue("{\"a\":3}", AnnotatedBeanDelegating.class); assertNotNull(value); Object ob = value.value; assertNotNull(ob); assertTrue(ob instanceof Map); } /* /********************************************************** /* Unit tests for property-based creators /********************************************************** */ public void testPropertyBasedBeanInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(CreatorBean.class, new InstantiatorBase() { @Override public boolean canCreateFromObjectWith() { return true; } @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config) { return new CreatorProperty[] { new CreatorProperty(new PropertyName("secret"), config.constructType(String.class), null, null, null, null, 0, null, PropertyMetadata.STD_REQUIRED) }; } @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args) { return new CreatorBean((String) args[0]); } })); CreatorBean bean = mapper.readValue("{\"secret\":123,\"value\":37}", CreatorBean.class); assertNotNull(bean); assertEquals("123", bean._secret); } public void testPropertyBasedMapInstantiator() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MyMap.class, new CreatorMapInstantiator())); MyMap result = mapper.readValue("{\"name\":\"bob\", \"x\":\"y\"}", MyMap.class); assertNotNull(result); assertEquals(2, result.size()); assertEquals("bob", result.get("bob")); assertEquals("y", result.get("x")); } /* /********************************************************** /* Unit tests for scalar-delegates /********************************************************** */ public void testBeanFromString() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MysteryBean.class, new InstantiatorBase() { @Override public boolean canCreateFromString() { return true; } @Override public Object createFromString(DeserializationContext ctxt, String value) { return new MysteryBean(value); } })); MysteryBean result = mapper.readValue(quote("abc"), MysteryBean.class); assertNotNull(result); assertEquals("abc", result.value); } public void testBeanFromInt() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MysteryBean.class, new InstantiatorBase() { @Override public boolean canCreateFromInt() { return true; } @Override public Object createFromInt(DeserializationContext ctxt, int value) { return new MysteryBean(value+1); } })); MysteryBean result = mapper.readValue("37", MysteryBean.class); assertNotNull(result); assertEquals(Integer.valueOf(38), result.value); } public void testBeanFromLong() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MysteryBean.class, new InstantiatorBase() { @Override public boolean canCreateFromLong() { return true; } @Override public Object createFromLong(DeserializationContext ctxt, long value) { return new MysteryBean(value+1L); } })); MysteryBean result = mapper.readValue("9876543210", MysteryBean.class); assertNotNull(result); assertEquals(Long.valueOf(9876543211L), result.value); } public void testBeanFromDouble() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MysteryBean.class, new InstantiatorBase() { @Override public boolean canCreateFromDouble() { return true; } @Override public Object createFromDouble(DeserializationContext ctxt, double value) { return new MysteryBean(2.0 * value); } })); MysteryBean result = mapper.readValue("0.25", MysteryBean.class); assertNotNull(result); assertEquals(Double.valueOf(0.5), result.value); } public void testBeanFromBoolean() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(MysteryBean.class, new InstantiatorBase() { @Override public boolean canCreateFromBoolean() { return true; } @Override public Object createFromBoolean(DeserializationContext ctxt, boolean value) { return new MysteryBean(Boolean.valueOf(value)); } })); MysteryBean result = mapper.readValue("true", MysteryBean.class); assertNotNull(result); assertEquals(Boolean.TRUE, result.value); } /* /********************************************************** /* Other tests /********************************************************** */ /** * Beyond basic features, it should be possible to even implement * polymorphic handling... */ public void testPolymorphicCreatorBean() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new MyModule(PolymorphicBeanBase.class, new PolymorphicBeanInstantiator())); String JSON = "{\"type\":"+quote(PolymorphicBean.class.getName())+",\"name\":\"Axel\"}"; PolymorphicBeanBase result = mapper.readValue(JSON, PolymorphicBeanBase.class); assertNotNull(result); assertSame(PolymorphicBean.class, result.getClass()); assertEquals("Axel", ((PolymorphicBean) result).name); } public void testEmptyBean() throws Exception { AnnotatedBean bean = MAPPER.readValue("{}", AnnotatedBean.class); assertNotNull(bean); assertEquals("foo", bean.a); assertEquals(3, bean.b); } // @since 2.8 public void testErrorMessageForMissingCtor() throws Exception { // first fail, check message from JSON Object (no default ctor) try { MAPPER.readValue("{ }", MyBean.class); fail("Should not succeed"); } catch (JsonMappingException e) { verifyException(e, "Cannot construct instance of"); verifyException(e, "no Creators"); // as per [databind#1414], is definition problem assertEquals(InvalidDefinitionException.class, e.getClass()); } } // @since 2.8 public void testErrorMessageForMissingStringCtor() throws Exception { // then from JSON String try { MAPPER.readValue("\"foo\"", MyBean.class); fail("Should not succeed"); } catch (JsonMappingException e) { verifyException(e, "Cannot construct instance of"); verifyException(e, "no String-argument constructor/factory"); // as per [databind#1414], is definition problem assertEquals(InvalidDefinitionException.class, e.getClass()); } } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/deser/ValueInstantiator.java", "be_test_class_name": "com.fasterxml.jackson.databind.deser.ValueInstantiator", "be_test_function_name": "canCreateFromInt", "be_test_function_signature": "()Z", "line_numbers": [ "88" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/deser/ValueInstantiator.java", "be_test_class_name": "com.fasterxml.jackson.databind.deser.ValueInstantiator", "be_test_function_name": "canCreateFromObjectWith", "be_test_function_signature": "()Z", "line_numbers": [ "136" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/deser/ValueInstantiator.java", "be_test_class_name": "com.fasterxml.jackson.databind.deser.ValueInstantiator", "be_test_function_name": "canCreateUsingArrayDelegate", "be_test_function_signature": "()Z", "line_numbers": [ "129" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/deser/ValueInstantiator.java", "be_test_class_name": "com.fasterxml.jackson.databind.deser.ValueInstantiator", "be_test_function_name": "getDelegateCreator", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/introspect/AnnotatedWithParams;", "line_numbers": [ "311" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/deser/ValueInstantiator.java", "be_test_class_name": "com.fasterxml.jackson.databind.deser.ValueInstantiator", "be_test_function_name": "getFromObjectArguments", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/DeserializationConfig;)[Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;", "line_numbers": [ "149" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/deser/ValueInstantiator.java", "be_test_class_name": "com.fasterxml.jackson.databind.deser.ValueInstantiator", "be_test_function_name": "getIncompleteParameter", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;", "line_numbers": [ "338" ], "method_line_rate": 1 } ]
public class DefaultKeyedValues2DTests extends TestCase
public void testSparsePopulation() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(new Integer(11), "R1", "C1"); d.addValue(new Integer(22), "R2", "C2"); assertEquals(new Integer(11), d.getValue("R1", "C1")); assertNull(d.getValue("R1", "C2")); assertEquals(new Integer(22), d.getValue("R2", "C2")); assertNull(d.getValue("R2", "C1")); }
// // Abstract Java Tested Class // package org.jfree.data; // // import java.io.Serializable; // import java.util.Collections; // import java.util.Iterator; // import java.util.List; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // // // // public class DefaultKeyedValues2D implements KeyedValues2D, PublicCloneable, // Cloneable, Serializable { // private static final long serialVersionUID = -5514169970951994748L; // private List rowKeys; // private List columnKeys; // private List rows; // private boolean sortRowKeys; // // public DefaultKeyedValues2D(); // public DefaultKeyedValues2D(boolean sortRowKeys); // public int getRowCount(); // public int getColumnCount(); // public Number getValue(int row, int column); // public Comparable getRowKey(int row); // public int getRowIndex(Comparable key); // public List getRowKeys(); // public Comparable getColumnKey(int column); // public int getColumnIndex(Comparable key); // public List getColumnKeys(); // public Number getValue(Comparable rowKey, Comparable columnKey); // public void addValue(Number value, Comparable rowKey, // Comparable columnKey); // public void setValue(Number value, Comparable rowKey, // Comparable columnKey); // public void removeValue(Comparable rowKey, Comparable columnKey); // public void removeRow(int rowIndex); // public void removeRow(Comparable rowKey); // public void removeColumn(int columnIndex); // public void removeColumn(Comparable columnKey); // public void clear(); // public boolean equals(Object o); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.data.junit; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.DefaultKeyedValues2D; // import org.jfree.data.UnknownKeyException; // // // // public class DefaultKeyedValues2DTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DefaultKeyedValues2DTests(String name); // public void testGetValue(); // public void testCloning(); // public void testSerialization(); // public void testEquals(); // public void testSparsePopulation(); // public void testRowCount(); // public void testColumnCount(); // public void testGetValue2(); // public void testGetRowKey(); // public void testGetColumnKey(); // public void testRemoveValue(); // public void testRemoveValueBug1690654(); // public void testRemoveRow(); // public void testRemoveColumnByKey(); // } // You are a professional Java test case writer, please create a test case named `testSparsePopulation` for the `DefaultKeyedValues2D` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Populates a data structure with sparse entries, then checks that * the unspecified entries return null. */
tests/org/jfree/data/junit/DefaultKeyedValues2DTests.java
package org.jfree.data; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable;
public DefaultKeyedValues2D(); public DefaultKeyedValues2D(boolean sortRowKeys); public int getRowCount(); public int getColumnCount(); public Number getValue(int row, int column); public Comparable getRowKey(int row); public int getRowIndex(Comparable key); public List getRowKeys(); public Comparable getColumnKey(int column); public int getColumnIndex(Comparable key); public List getColumnKeys(); public Number getValue(Comparable rowKey, Comparable columnKey); public void addValue(Number value, Comparable rowKey, Comparable columnKey); public void setValue(Number value, Comparable rowKey, Comparable columnKey); public void removeValue(Comparable rowKey, Comparable columnKey); public void removeRow(int rowIndex); public void removeRow(Comparable rowKey); public void removeColumn(int columnIndex); public void removeColumn(Comparable columnKey); public void clear(); public boolean equals(Object o); public int hashCode(); public Object clone() throws CloneNotSupportedException;
194
testSparsePopulation
```java // Abstract Java Tested Class package org.jfree.data; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; public class DefaultKeyedValues2D implements KeyedValues2D, PublicCloneable, Cloneable, Serializable { private static final long serialVersionUID = -5514169970951994748L; private List rowKeys; private List columnKeys; private List rows; private boolean sortRowKeys; public DefaultKeyedValues2D(); public DefaultKeyedValues2D(boolean sortRowKeys); public int getRowCount(); public int getColumnCount(); public Number getValue(int row, int column); public Comparable getRowKey(int row); public int getRowIndex(Comparable key); public List getRowKeys(); public Comparable getColumnKey(int column); public int getColumnIndex(Comparable key); public List getColumnKeys(); public Number getValue(Comparable rowKey, Comparable columnKey); public void addValue(Number value, Comparable rowKey, Comparable columnKey); public void setValue(Number value, Comparable rowKey, Comparable columnKey); public void removeValue(Comparable rowKey, Comparable columnKey); public void removeRow(int rowIndex); public void removeRow(Comparable rowKey); public void removeColumn(int columnIndex); public void removeColumn(Comparable columnKey); public void clear(); public boolean equals(Object o); public int hashCode(); public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.data.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.DefaultKeyedValues2D; import org.jfree.data.UnknownKeyException; public class DefaultKeyedValues2DTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DefaultKeyedValues2DTests(String name); public void testGetValue(); public void testCloning(); public void testSerialization(); public void testEquals(); public void testSparsePopulation(); public void testRowCount(); public void testColumnCount(); public void testGetValue2(); public void testGetRowKey(); public void testGetColumnKey(); public void testRemoveValue(); public void testRemoveValueBug1690654(); public void testRemoveRow(); public void testRemoveColumnByKey(); } ``` You are a professional Java test case writer, please create a test case named `testSparsePopulation` for the `DefaultKeyedValues2D` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Populates a data structure with sparse entries, then checks that * the unspecified entries return null. */
185
// // Abstract Java Tested Class // package org.jfree.data; // // import java.io.Serializable; // import java.util.Collections; // import java.util.Iterator; // import java.util.List; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // // // // public class DefaultKeyedValues2D implements KeyedValues2D, PublicCloneable, // Cloneable, Serializable { // private static final long serialVersionUID = -5514169970951994748L; // private List rowKeys; // private List columnKeys; // private List rows; // private boolean sortRowKeys; // // public DefaultKeyedValues2D(); // public DefaultKeyedValues2D(boolean sortRowKeys); // public int getRowCount(); // public int getColumnCount(); // public Number getValue(int row, int column); // public Comparable getRowKey(int row); // public int getRowIndex(Comparable key); // public List getRowKeys(); // public Comparable getColumnKey(int column); // public int getColumnIndex(Comparable key); // public List getColumnKeys(); // public Number getValue(Comparable rowKey, Comparable columnKey); // public void addValue(Number value, Comparable rowKey, // Comparable columnKey); // public void setValue(Number value, Comparable rowKey, // Comparable columnKey); // public void removeValue(Comparable rowKey, Comparable columnKey); // public void removeRow(int rowIndex); // public void removeRow(Comparable rowKey); // public void removeColumn(int columnIndex); // public void removeColumn(Comparable columnKey); // public void clear(); // public boolean equals(Object o); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.data.junit; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.DefaultKeyedValues2D; // import org.jfree.data.UnknownKeyException; // // // // public class DefaultKeyedValues2DTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DefaultKeyedValues2DTests(String name); // public void testGetValue(); // public void testCloning(); // public void testSerialization(); // public void testEquals(); // public void testSparsePopulation(); // public void testRowCount(); // public void testColumnCount(); // public void testGetValue2(); // public void testGetRowKey(); // public void testGetColumnKey(); // public void testRemoveValue(); // public void testRemoveValueBug1690654(); // public void testRemoveRow(); // public void testRemoveColumnByKey(); // } // You are a professional Java test case writer, please create a test case named `testSparsePopulation` for the `DefaultKeyedValues2D` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Populates a data structure with sparse entries, then checks that * the unspecified entries return null. */ public void testSparsePopulation() {
/** * Populates a data structure with sparse entries, then checks that * the unspecified entries return null. */
1
org.jfree.data.DefaultKeyedValues2D
tests
```java // Abstract Java Tested Class package org.jfree.data; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; public class DefaultKeyedValues2D implements KeyedValues2D, PublicCloneable, Cloneable, Serializable { private static final long serialVersionUID = -5514169970951994748L; private List rowKeys; private List columnKeys; private List rows; private boolean sortRowKeys; public DefaultKeyedValues2D(); public DefaultKeyedValues2D(boolean sortRowKeys); public int getRowCount(); public int getColumnCount(); public Number getValue(int row, int column); public Comparable getRowKey(int row); public int getRowIndex(Comparable key); public List getRowKeys(); public Comparable getColumnKey(int column); public int getColumnIndex(Comparable key); public List getColumnKeys(); public Number getValue(Comparable rowKey, Comparable columnKey); public void addValue(Number value, Comparable rowKey, Comparable columnKey); public void setValue(Number value, Comparable rowKey, Comparable columnKey); public void removeValue(Comparable rowKey, Comparable columnKey); public void removeRow(int rowIndex); public void removeRow(Comparable rowKey); public void removeColumn(int columnIndex); public void removeColumn(Comparable columnKey); public void clear(); public boolean equals(Object o); public int hashCode(); public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.data.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.DefaultKeyedValues2D; import org.jfree.data.UnknownKeyException; public class DefaultKeyedValues2DTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DefaultKeyedValues2DTests(String name); public void testGetValue(); public void testCloning(); public void testSerialization(); public void testEquals(); public void testSparsePopulation(); public void testRowCount(); public void testColumnCount(); public void testGetValue2(); public void testGetRowKey(); public void testGetColumnKey(); public void testRemoveValue(); public void testRemoveValueBug1690654(); public void testRemoveRow(); public void testRemoveColumnByKey(); } ``` You are a professional Java test case writer, please create a test case named `testSparsePopulation` for the `DefaultKeyedValues2D` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Populates a data structure with sparse entries, then checks that * the unspecified entries return null. */ public void testSparsePopulation() { ```
public class DefaultKeyedValues2D implements KeyedValues2D, PublicCloneable, Cloneable, Serializable
package org.jfree.data.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.DefaultKeyedValues2D; import org.jfree.data.UnknownKeyException;
public static Test suite(); public DefaultKeyedValues2DTests(String name); public void testGetValue(); public void testCloning(); public void testSerialization(); public void testEquals(); public void testSparsePopulation(); public void testRowCount(); public void testColumnCount(); public void testGetValue2(); public void testGetRowKey(); public void testGetColumnKey(); public void testRemoveValue(); public void testRemoveValueBug1690654(); public void testRemoveRow(); public void testRemoveColumnByKey();
c8e63e8dffe338f2f05ffaf3f5b701219adfe644a8a7f32fd319e77b1dfc3476
[ "org.jfree.data.junit.DefaultKeyedValues2DTests::testSparsePopulation" ]
private static final long serialVersionUID = -5514169970951994748L; private List rowKeys; private List columnKeys; private List rows; private boolean sortRowKeys;
public void testSparsePopulation()
private static final double EPSILON = 0.0000000001;
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * DefaultKeyedValues2DTests.java * ------------------------------ * (C) Copyright 2003-2007 by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Mar-2003 : Version 1 (DG); * 15-Sep-2004 : Updated cloning test (DG); * 06-Oct-2005 : Added testEquals() (DG); * 18-Jan-2007 : Added testSparsePopulation() (DG); * 26-Feb-2007 : Added some basic tests (DG); * 30-Mar-2007 : Added a test for bug 1690654 (DG); * 21-Nov-2007 : Added testRemoveColumnByKey() method (DG); * */ package org.jfree.data.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.DefaultKeyedValues2D; import org.jfree.data.UnknownKeyException; /** * Tests for the {@link DefaultKeyedValues2D} class. */ public class DefaultKeyedValues2DTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DefaultKeyedValues2DTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DefaultKeyedValues2DTests(String name) { super(name); } /** * Some checks for the getValue() method. */ public void testGetValue() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(new Double(1.0), "R1", "C1"); assertEquals(new Double(1.0), d.getValue("R1", "C1")); boolean pass = false; try { d.getValue("XX", "C1"); } catch (UnknownKeyException e) { pass = true; } assertTrue(pass); pass = false; try { d.getValue("R1", "XX"); } catch (UnknownKeyException e) { pass = true; } assertTrue(pass); } /** * Some checks for the clone() method. */ public void testCloning() { DefaultKeyedValues2D v1 = new DefaultKeyedValues2D(); v1.setValue(new Integer(1), "V1", "C1"); v1.setValue(null, "V2", "C1"); v1.setValue(new Integer(3), "V3", "C2"); DefaultKeyedValues2D v2 = null; try { v2 = (DefaultKeyedValues2D) v1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(v1 != v2); assertTrue(v1.getClass() == v2.getClass()); assertTrue(v1.equals(v2)); // check that clone is independent of the original v2.setValue(new Integer(2), "V2", "C1"); assertFalse(v1.equals(v2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { DefaultKeyedValues2D kv2D1 = new DefaultKeyedValues2D(); kv2D1.addValue(new Double(234.2), "Row1", "Col1"); kv2D1.addValue(null, "Row1", "Col2"); kv2D1.addValue(new Double(345.9), "Row2", "Col1"); kv2D1.addValue(new Double(452.7), "Row2", "Col2"); DefaultKeyedValues2D kv2D2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(kv2D1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); kv2D2 = (DefaultKeyedValues2D) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(kv2D1, kv2D2); } /** * Some checks for the equals() method. */ public void testEquals() { DefaultKeyedValues2D d1 = new DefaultKeyedValues2D(); DefaultKeyedValues2D d2 = new DefaultKeyedValues2D(); assertTrue(d1.equals(d2)); assertTrue(d2.equals(d1)); d1.addValue(new Double(1.0), new Double(2.0), "S1"); assertFalse(d1.equals(d2)); d2.addValue(new Double(1.0), new Double(2.0), "S1"); assertTrue(d1.equals(d2)); } /** * Populates a data structure with sparse entries, then checks that * the unspecified entries return null. */ public void testSparsePopulation() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(new Integer(11), "R1", "C1"); d.addValue(new Integer(22), "R2", "C2"); assertEquals(new Integer(11), d.getValue("R1", "C1")); assertNull(d.getValue("R1", "C2")); assertEquals(new Integer(22), d.getValue("R2", "C2")); assertNull(d.getValue("R2", "C1")); } /** * Some basic checks for the getRowCount() method. */ public void testRowCount() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); assertEquals(0, d.getRowCount()); d.addValue(new Double(1.0), "R1", "C1"); assertEquals(1, d.getRowCount()); d.addValue(new Double(2.0), "R2", "C1"); assertEquals(2, d.getRowCount()); } /** * Some basic checks for the getColumnCount() method. */ public void testColumnCount() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); assertEquals(0, d.getColumnCount()); d.addValue(new Double(1.0), "R1", "C1"); assertEquals(1, d.getColumnCount()); d.addValue(new Double(2.0), "R1", "C2"); assertEquals(2, d.getColumnCount()); } private static final double EPSILON = 0.0000000001; /** * Some basic checks for the getValue(int, int) method. */ public void testGetValue2() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); boolean pass = false; try { d.getValue(0, 0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); d.addValue(new Double(1.0), "R1", "C1"); assertEquals(1.0, d.getValue(0, 0).doubleValue(), EPSILON); d.addValue(new Double(2.0), "R2", "C2"); assertEquals(2.0, d.getValue(1, 1).doubleValue(), EPSILON); assertNull(d.getValue(1, 0)); assertNull(d.getValue(0, 1)); pass = false; try { d.getValue(2, 0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some basic checks for the getRowKey() method. */ public void testGetRowKey() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); boolean pass = false; try { d.getRowKey(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); d.addValue(new Double(1.0), "R1", "C1"); d.addValue(new Double(1.0), "R2", "C1"); assertEquals("R1", d.getRowKey(0)); assertEquals("R2", d.getRowKey(1)); // check sorted rows d = new DefaultKeyedValues2D(true); d.addValue(new Double(1.0), "R1", "C1"); assertEquals("R1", d.getRowKey(0)); d.addValue(new Double(0.0), "R0", "C1"); assertEquals("R0", d.getRowKey(0)); assertEquals("R1", d.getRowKey(1)); } /** * Some basic checks for the getColumnKey() method. */ public void testGetColumnKey() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); boolean pass = false; try { d.getColumnKey(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); d.addValue(new Double(1.0), "R1", "C1"); d.addValue(new Double(1.0), "R1", "C2"); assertEquals("C1", d.getColumnKey(0)); assertEquals("C2", d.getColumnKey(1)); } /** * Some basic checks for the removeValue() method. */ public void testRemoveValue() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.removeValue("R1", "C1"); d.addValue(new Double(1.0), "R1", "C1"); d.removeValue("R1", "C1"); assertEquals(0, d.getRowCount()); assertEquals(0, d.getColumnCount()); d.addValue(new Double(1.0), "R1", "C1"); d.addValue(new Double(2.0), "R2", "C1"); d.removeValue("R1", "C1"); assertEquals(new Double(2.0), d.getValue(0, 0)); } /** * A test for bug 1690654. */ public void testRemoveValueBug1690654() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(new Double(1.0), "R1", "C1"); d.addValue(new Double(2.0), "R2", "C2"); assertEquals(2, d.getColumnCount()); assertEquals(2, d.getRowCount()); d.removeValue("R2", "C2"); assertEquals(1, d.getColumnCount()); assertEquals(1, d.getRowCount()); assertEquals(new Double(1.0), d.getValue(0, 0)); } /** * Some basic checks for the removeRow() method. */ public void testRemoveRow() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); boolean pass = false; try { d.removeRow(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some basic checks for the removeColumn(Comparable) method. */ public void testRemoveColumnByKey() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(new Double(1.0), "R1", "C1"); d.addValue(new Double(2.0), "R2", "C2"); d.removeColumn("C2"); d.addValue(new Double(3.0), "R2", "C2"); assertEquals(3.0, d.getValue("R2", "C2").doubleValue(), EPSILON); // check for unknown column boolean pass = false; try { d.removeColumn("XXX"); } catch (UnknownKeyException e) { pass = true; } assertTrue(pass); } }
[ { "be_test_class_file": "org/jfree/data/DefaultKeyedValues2D.java", "be_test_class_name": "org.jfree.data.DefaultKeyedValues2D", "be_test_function_name": "addValue", "be_test_function_signature": "(Ljava/lang/Number;Ljava/lang/Comparable;Ljava/lang/Comparable;)V", "line_numbers": [ "304", "305" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/DefaultKeyedValues2D.java", "be_test_class_name": "org.jfree.data.DefaultKeyedValues2D", "be_test_function_name": "getRowIndex", "be_test_function_signature": "(Ljava/lang/Comparable;)I", "line_numbers": [ "183", "184", "186", "187", "190" ], "method_line_rate": 0.6 }, { "be_test_class_file": "org/jfree/data/DefaultKeyedValues2D.java", "be_test_class_name": "org.jfree.data.DefaultKeyedValues2D", "be_test_function_name": "getValue", "be_test_function_signature": "(Ljava/lang/Comparable;Ljava/lang/Comparable;)Ljava/lang/Number;", "line_numbers": [ "262", "263", "265", "266", "270", "271", "278", "279", "280", "282", "283", "286" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/jfree/data/DefaultKeyedValues2D.java", "be_test_class_name": "org.jfree.data.DefaultKeyedValues2D", "be_test_function_name": "setValue", "be_test_function_signature": "(Ljava/lang/Number;Ljava/lang/Comparable;Ljava/lang/Comparable;)V", "line_numbers": [ "321", "323", "324", "327", "328", "329", "330", "331", "334", "335", "338", "340", "341", "342", "344" ], "method_line_rate": 0.7333333333333333 } ]
public class TimedSemaphoreTest
@Test public void testAcquireMultiplePeriods() throws InterruptedException { final int count = 1000; final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl( PERIOD / 10, TimeUnit.MILLISECONDS, 1); semaphore.setLimit(count / 4); final CountDownLatch latch = new CountDownLatch(count); final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count); t.start(); latch.await(); semaphore.shutdown(); assertTrue("End of period not reached", semaphore.getPeriodEnds() > 0); }
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.concurrent.ScheduledExecutorService; // import java.util.concurrent.ScheduledFuture; // import java.util.concurrent.ScheduledThreadPoolExecutor; // import java.util.concurrent.TimeUnit; // // // // public class TimedSemaphore { // public static final int NO_LIMIT = 0; // private static final int THREAD_POOL_SIZE = 1; // private final ScheduledExecutorService executorService; // private final long period; // private final TimeUnit unit; // private final boolean ownExecutor; // private ScheduledFuture<?> task; // private long totalAcquireCount; // private long periodCount; // private int limit; // private int acquireCount; // private int lastCallsPerPeriod; // private boolean shutdown; // // public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit); // public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod, // final TimeUnit timeUnit, final int limit); // public final synchronized int getLimit(); // public final synchronized void setLimit(final int limit); // public synchronized void shutdown(); // public synchronized boolean isShutdown(); // public synchronized void acquire() throws InterruptedException; // public synchronized int getLastAcquiresPerPeriod(); // public synchronized int getAcquireCount(); // public synchronized int getAvailablePermits(); // public synchronized double getAverageCallsPerPeriod(); // public long getPeriod(); // public TimeUnit getUnit(); // protected ScheduledExecutorService getExecutorService(); // protected ScheduledFuture<?> startTimer(); // synchronized void endOfPeriod(); // @Override // public void run(); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.concurrent; // // 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.util.concurrent.CountDownLatch; // import java.util.concurrent.ScheduledExecutorService; // import java.util.concurrent.ScheduledFuture; // import java.util.concurrent.ScheduledThreadPoolExecutor; // import java.util.concurrent.TimeUnit; // import org.easymock.EasyMock; // import org.junit.Test; // // // // public class TimedSemaphoreTest { // private static final long PERIOD = 500; // private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; // private static final int LIMIT = 10; // // @Test // public void testInit(); // @Test(expected = IllegalArgumentException.class) // public void testInitInvalidPeriod(); // @Test // public void testInitDefaultService(); // @Test // public void testStartTimer() throws InterruptedException; // @Test // public void testShutdownOwnExecutor(); // @Test // public void testShutdownSharedExecutorNoTask(); // private void prepareStartTimer(final ScheduledExecutorService service, // final ScheduledFuture<?> future); // @Test // public void testShutdownSharedExecutorTask() throws InterruptedException; // @Test // public void testShutdownMultipleTimes() throws InterruptedException; // @Test // public void testAcquireLimit() throws InterruptedException; // @Test // public void testAcquireMultipleThreads() throws InterruptedException; // @Test // public void testAcquireNoLimit() throws InterruptedException; // @Test(expected = IllegalStateException.class) // public void testPassAfterShutdown() throws InterruptedException; // @Test // public void testAcquireMultiplePeriods() throws InterruptedException; // @Test // public void testGetAverageCallsPerPeriod() throws InterruptedException; // @Test // public void testGetAvailablePermits() throws InterruptedException; // public TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit, // final int limit); // public TimedSemaphoreTestImpl(final ScheduledExecutorService service, // final long timePeriod, final TimeUnit timeUnit, final int limit); // public int getPeriodEnds(); // @Override // public synchronized void acquire() throws InterruptedException; // @Override // protected synchronized void endOfPeriod(); // @Override // protected ScheduledFuture<?> startTimer(); // public SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc); // @Override // public void run(); // } // You are a professional Java test case writer, please create a test case named `testAcquireMultiplePeriods` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests a bigger number of invocations that span multiple periods. The * period is set to a very short time. A background thread calls the * semaphore a large number of times. While it runs at last one end of a * period should be reached. */
src/test/java/org/apache/commons/lang3/concurrent/TimedSemaphoreTest.java
package org.apache.commons.lang3.concurrent; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit;
public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit); public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit); public final synchronized int getLimit(); public final synchronized void setLimit(final int limit); public synchronized void shutdown(); public synchronized boolean isShutdown(); public synchronized void acquire() throws InterruptedException; public synchronized int getLastAcquiresPerPeriod(); public synchronized int getAcquireCount(); public synchronized int getAvailablePermits(); public synchronized double getAverageCallsPerPeriod(); public long getPeriod(); public TimeUnit getUnit(); protected ScheduledExecutorService getExecutorService(); protected ScheduledFuture<?> startTimer(); synchronized void endOfPeriod(); @Override public void run();
319
testAcquireMultiplePeriods
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TimedSemaphore { public static final int NO_LIMIT = 0; private static final int THREAD_POOL_SIZE = 1; private final ScheduledExecutorService executorService; private final long period; private final TimeUnit unit; private final boolean ownExecutor; private ScheduledFuture<?> task; private long totalAcquireCount; private long periodCount; private int limit; private int acquireCount; private int lastCallsPerPeriod; private boolean shutdown; public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit); public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit); public final synchronized int getLimit(); public final synchronized void setLimit(final int limit); public synchronized void shutdown(); public synchronized boolean isShutdown(); public synchronized void acquire() throws InterruptedException; public synchronized int getLastAcquiresPerPeriod(); public synchronized int getAcquireCount(); public synchronized int getAvailablePermits(); public synchronized double getAverageCallsPerPeriod(); public long getPeriod(); public TimeUnit getUnit(); protected ScheduledExecutorService getExecutorService(); protected ScheduledFuture<?> startTimer(); synchronized void endOfPeriod(); @Override public void run(); } // Abstract Java Test Class package org.apache.commons.lang3.concurrent; 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.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test; public class TimedSemaphoreTest { private static final long PERIOD = 500; private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; private static final int LIMIT = 10; @Test public void testInit(); @Test(expected = IllegalArgumentException.class) public void testInitInvalidPeriod(); @Test public void testInitDefaultService(); @Test public void testStartTimer() throws InterruptedException; @Test public void testShutdownOwnExecutor(); @Test public void testShutdownSharedExecutorNoTask(); private void prepareStartTimer(final ScheduledExecutorService service, final ScheduledFuture<?> future); @Test public void testShutdownSharedExecutorTask() throws InterruptedException; @Test public void testShutdownMultipleTimes() throws InterruptedException; @Test public void testAcquireLimit() throws InterruptedException; @Test public void testAcquireMultipleThreads() throws InterruptedException; @Test public void testAcquireNoLimit() throws InterruptedException; @Test(expected = IllegalStateException.class) public void testPassAfterShutdown() throws InterruptedException; @Test public void testAcquireMultiplePeriods() throws InterruptedException; @Test public void testGetAverageCallsPerPeriod() throws InterruptedException; @Test public void testGetAvailablePermits() throws InterruptedException; public TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit, final int limit); public TimedSemaphoreTestImpl(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit); public int getPeriodEnds(); @Override public synchronized void acquire() throws InterruptedException; @Override protected synchronized void endOfPeriod(); @Override protected ScheduledFuture<?> startTimer(); public SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc); @Override public void run(); } ``` You are a professional Java test case writer, please create a test case named `testAcquireMultiplePeriods` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests a bigger number of invocations that span multiple periods. The * period is set to a very short time. A background thread calls the * semaphore a large number of times. While it runs at last one end of a * period should be reached. */
307
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.concurrent.ScheduledExecutorService; // import java.util.concurrent.ScheduledFuture; // import java.util.concurrent.ScheduledThreadPoolExecutor; // import java.util.concurrent.TimeUnit; // // // // public class TimedSemaphore { // public static final int NO_LIMIT = 0; // private static final int THREAD_POOL_SIZE = 1; // private final ScheduledExecutorService executorService; // private final long period; // private final TimeUnit unit; // private final boolean ownExecutor; // private ScheduledFuture<?> task; // private long totalAcquireCount; // private long periodCount; // private int limit; // private int acquireCount; // private int lastCallsPerPeriod; // private boolean shutdown; // // public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit); // public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod, // final TimeUnit timeUnit, final int limit); // public final synchronized int getLimit(); // public final synchronized void setLimit(final int limit); // public synchronized void shutdown(); // public synchronized boolean isShutdown(); // public synchronized void acquire() throws InterruptedException; // public synchronized int getLastAcquiresPerPeriod(); // public synchronized int getAcquireCount(); // public synchronized int getAvailablePermits(); // public synchronized double getAverageCallsPerPeriod(); // public long getPeriod(); // public TimeUnit getUnit(); // protected ScheduledExecutorService getExecutorService(); // protected ScheduledFuture<?> startTimer(); // synchronized void endOfPeriod(); // @Override // public void run(); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.concurrent; // // 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.util.concurrent.CountDownLatch; // import java.util.concurrent.ScheduledExecutorService; // import java.util.concurrent.ScheduledFuture; // import java.util.concurrent.ScheduledThreadPoolExecutor; // import java.util.concurrent.TimeUnit; // import org.easymock.EasyMock; // import org.junit.Test; // // // // public class TimedSemaphoreTest { // private static final long PERIOD = 500; // private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; // private static final int LIMIT = 10; // // @Test // public void testInit(); // @Test(expected = IllegalArgumentException.class) // public void testInitInvalidPeriod(); // @Test // public void testInitDefaultService(); // @Test // public void testStartTimer() throws InterruptedException; // @Test // public void testShutdownOwnExecutor(); // @Test // public void testShutdownSharedExecutorNoTask(); // private void prepareStartTimer(final ScheduledExecutorService service, // final ScheduledFuture<?> future); // @Test // public void testShutdownSharedExecutorTask() throws InterruptedException; // @Test // public void testShutdownMultipleTimes() throws InterruptedException; // @Test // public void testAcquireLimit() throws InterruptedException; // @Test // public void testAcquireMultipleThreads() throws InterruptedException; // @Test // public void testAcquireNoLimit() throws InterruptedException; // @Test(expected = IllegalStateException.class) // public void testPassAfterShutdown() throws InterruptedException; // @Test // public void testAcquireMultiplePeriods() throws InterruptedException; // @Test // public void testGetAverageCallsPerPeriod() throws InterruptedException; // @Test // public void testGetAvailablePermits() throws InterruptedException; // public TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit, // final int limit); // public TimedSemaphoreTestImpl(final ScheduledExecutorService service, // final long timePeriod, final TimeUnit timeUnit, final int limit); // public int getPeriodEnds(); // @Override // public synchronized void acquire() throws InterruptedException; // @Override // protected synchronized void endOfPeriod(); // @Override // protected ScheduledFuture<?> startTimer(); // public SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc); // @Override // public void run(); // } // You are a professional Java test case writer, please create a test case named `testAcquireMultiplePeriods` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests a bigger number of invocations that span multiple periods. The * period is set to a very short time. A background thread calls the * semaphore a large number of times. While it runs at last one end of a * period should be reached. */ @Test public void testAcquireMultiplePeriods() throws InterruptedException {
/** * Tests a bigger number of invocations that span multiple periods. The * period is set to a very short time. A background thread calls the * semaphore a large number of times. While it runs at last one end of a * period should be reached. */
1
org.apache.commons.lang3.concurrent.TimedSemaphore
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TimedSemaphore { public static final int NO_LIMIT = 0; private static final int THREAD_POOL_SIZE = 1; private final ScheduledExecutorService executorService; private final long period; private final TimeUnit unit; private final boolean ownExecutor; private ScheduledFuture<?> task; private long totalAcquireCount; private long periodCount; private int limit; private int acquireCount; private int lastCallsPerPeriod; private boolean shutdown; public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit); public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit); public final synchronized int getLimit(); public final synchronized void setLimit(final int limit); public synchronized void shutdown(); public synchronized boolean isShutdown(); public synchronized void acquire() throws InterruptedException; public synchronized int getLastAcquiresPerPeriod(); public synchronized int getAcquireCount(); public synchronized int getAvailablePermits(); public synchronized double getAverageCallsPerPeriod(); public long getPeriod(); public TimeUnit getUnit(); protected ScheduledExecutorService getExecutorService(); protected ScheduledFuture<?> startTimer(); synchronized void endOfPeriod(); @Override public void run(); } // Abstract Java Test Class package org.apache.commons.lang3.concurrent; 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.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test; public class TimedSemaphoreTest { private static final long PERIOD = 500; private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; private static final int LIMIT = 10; @Test public void testInit(); @Test(expected = IllegalArgumentException.class) public void testInitInvalidPeriod(); @Test public void testInitDefaultService(); @Test public void testStartTimer() throws InterruptedException; @Test public void testShutdownOwnExecutor(); @Test public void testShutdownSharedExecutorNoTask(); private void prepareStartTimer(final ScheduledExecutorService service, final ScheduledFuture<?> future); @Test public void testShutdownSharedExecutorTask() throws InterruptedException; @Test public void testShutdownMultipleTimes() throws InterruptedException; @Test public void testAcquireLimit() throws InterruptedException; @Test public void testAcquireMultipleThreads() throws InterruptedException; @Test public void testAcquireNoLimit() throws InterruptedException; @Test(expected = IllegalStateException.class) public void testPassAfterShutdown() throws InterruptedException; @Test public void testAcquireMultiplePeriods() throws InterruptedException; @Test public void testGetAverageCallsPerPeriod() throws InterruptedException; @Test public void testGetAvailablePermits() throws InterruptedException; public TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit, final int limit); public TimedSemaphoreTestImpl(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit); public int getPeriodEnds(); @Override public synchronized void acquire() throws InterruptedException; @Override protected synchronized void endOfPeriod(); @Override protected ScheduledFuture<?> startTimer(); public SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc); @Override public void run(); } ``` You are a professional Java test case writer, please create a test case named `testAcquireMultiplePeriods` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests a bigger number of invocations that span multiple periods. The * period is set to a very short time. A background thread calls the * semaphore a large number of times. While it runs at last one end of a * period should be reached. */ @Test public void testAcquireMultiplePeriods() throws InterruptedException { ```
public class TimedSemaphore
package org.apache.commons.lang3.concurrent; 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.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test;
@Test public void testInit(); @Test(expected = IllegalArgumentException.class) public void testInitInvalidPeriod(); @Test public void testInitDefaultService(); @Test public void testStartTimer() throws InterruptedException; @Test public void testShutdownOwnExecutor(); @Test public void testShutdownSharedExecutorNoTask(); private void prepareStartTimer(final ScheduledExecutorService service, final ScheduledFuture<?> future); @Test public void testShutdownSharedExecutorTask() throws InterruptedException; @Test public void testShutdownMultipleTimes() throws InterruptedException; @Test public void testAcquireLimit() throws InterruptedException; @Test public void testAcquireMultipleThreads() throws InterruptedException; @Test public void testAcquireNoLimit() throws InterruptedException; @Test(expected = IllegalStateException.class) public void testPassAfterShutdown() throws InterruptedException; @Test public void testAcquireMultiplePeriods() throws InterruptedException; @Test public void testGetAverageCallsPerPeriod() throws InterruptedException; @Test public void testGetAvailablePermits() throws InterruptedException; public TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit, final int limit); public TimedSemaphoreTestImpl(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit); public int getPeriodEnds(); @Override public synchronized void acquire() throws InterruptedException; @Override protected synchronized void endOfPeriod(); @Override protected ScheduledFuture<?> startTimer(); public SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc); @Override public void run();
c8ebe5676b4c29d84dc7ab480647cd9e2e4d7b29d5076b851edaf62acdf6abb7
[ "org.apache.commons.lang3.concurrent.TimedSemaphoreTest::testAcquireMultiplePeriods" ]
public static final int NO_LIMIT = 0; private static final int THREAD_POOL_SIZE = 1; private final ScheduledExecutorService executorService; private final long period; private final TimeUnit unit; private final boolean ownExecutor; private ScheduledFuture<?> task; private long totalAcquireCount; private long periodCount; private int limit; private int acquireCount; private int lastCallsPerPeriod; private boolean shutdown;
@Test public void testAcquireMultiplePeriods() throws InterruptedException
private static final long PERIOD = 500; private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; private static final int LIMIT = 10;
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.concurrent; 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.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test; /** * Test class for TimedSemaphore. * * @version $Id$ */ public class TimedSemaphoreTest { /** Constant for the time period. */ private static final long PERIOD = 500; /** Constant for the time unit. */ private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; /** Constant for the default limit. */ private static final int LIMIT = 10; /** * Tests creating a new instance. */ @Test public void testInit() { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); EasyMock.replay(service); final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, LIMIT); EasyMock.verify(service); assertEquals("Wrong service", service, semaphore.getExecutorService()); assertEquals("Wrong period", PERIOD, semaphore.getPeriod()); assertEquals("Wrong unit", UNIT, semaphore.getUnit()); assertEquals("Statistic available", 0, semaphore .getLastAcquiresPerPeriod()); assertEquals("Average available", 0.0, semaphore .getAverageCallsPerPeriod(), .05); assertFalse("Already shutdown", semaphore.isShutdown()); assertEquals("Wrong limit", LIMIT, semaphore.getLimit()); } /** * Tries to create an instance with a negative period. This should cause an * exception. */ @Test(expected = IllegalArgumentException.class) public void testInitInvalidPeriod() { new TimedSemaphore(0L, UNIT, LIMIT); } /** * Tests whether a default executor service is created if no service is * provided. */ @Test public void testInitDefaultService() { final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT); final ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore .getExecutorService(); assertFalse("Wrong periodic task policy", exec .getContinueExistingPeriodicTasksAfterShutdownPolicy()); assertFalse("Wrong delayed task policy", exec .getExecuteExistingDelayedTasksAfterShutdownPolicy()); assertFalse("Already shutdown", exec.isShutdown()); semaphore.shutdown(); } /** * Tests starting the timer. */ @Test public void testStartTimer() throws InterruptedException { final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD, UNIT, LIMIT); final ScheduledFuture<?> future = semaphore.startTimer(); assertNotNull("No future returned", future); Thread.sleep(PERIOD); final int trials = 10; int count = 0; do { Thread.sleep(PERIOD); if (count++ > trials) { fail("endOfPeriod() not called!"); } } while (semaphore.getPeriodEnds() <= 0); semaphore.shutdown(); } /** * Tests the shutdown() method if the executor belongs to the semaphore. In * this case it has to be shut down. */ @Test public void testShutdownOwnExecutor() { final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT); semaphore.shutdown(); assertTrue("Not shutdown", semaphore.isShutdown()); assertTrue("Executor not shutdown", semaphore.getExecutorService() .isShutdown()); } /** * Tests the shutdown() method for a shared executor service before a task * was started. This should do pretty much nothing. */ @Test public void testShutdownSharedExecutorNoTask() { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); EasyMock.replay(service); final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, LIMIT); semaphore.shutdown(); assertTrue("Not shutdown", semaphore.isShutdown()); EasyMock.verify(service); } /** * Prepares an executor service mock to expect the start of the timer. * * @param service the mock * @param future the future */ private void prepareStartTimer(final ScheduledExecutorService service, final ScheduledFuture<?> future) { service.scheduleAtFixedRate((Runnable) EasyMock.anyObject(), EasyMock .eq(PERIOD), EasyMock.eq(PERIOD), EasyMock.eq(UNIT)); EasyMock.expectLastCall().andReturn(future); } /** * Tests the shutdown() method for a shared executor after the task was * started. In this case the task must be canceled. */ @Test public void testShutdownSharedExecutorTask() throws InterruptedException { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class); prepareStartTimer(service, future); EasyMock.expect(Boolean.valueOf(future.cancel(false))).andReturn(Boolean.TRUE); EasyMock.replay(service, future); final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD, UNIT, LIMIT); semaphore.acquire(); semaphore.shutdown(); assertTrue("Not shutdown", semaphore.isShutdown()); EasyMock.verify(service, future); } /** * Tests multiple invocations of the shutdown() method. */ @Test public void testShutdownMultipleTimes() throws InterruptedException { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class); prepareStartTimer(service, future); EasyMock.expect(Boolean.valueOf(future.cancel(false))).andReturn(Boolean.TRUE); EasyMock.replay(service, future); final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD, UNIT, LIMIT); semaphore.acquire(); for (int i = 0; i < 10; i++) { semaphore.shutdown(); } EasyMock.verify(service, future); } /** * Tests the acquire() method if a limit is set. */ @Test public void testAcquireLimit() throws InterruptedException { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class); prepareStartTimer(service, future); EasyMock.replay(service, future); final int count = 10; final CountDownLatch latch = new CountDownLatch(count - 1); final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, 1); final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count - 1); semaphore.setLimit(count - 1); // start a thread that calls the semaphore count times t.start(); latch.await(); // now the semaphore's limit should be reached and the thread blocked assertEquals("Wrong semaphore count", count - 1, semaphore .getAcquireCount()); // this wakes up the thread, it should call the semaphore once more semaphore.endOfPeriod(); t.join(); assertEquals("Wrong semaphore count (2)", 1, semaphore .getAcquireCount()); assertEquals("Wrong acquire() count", count - 1, semaphore .getLastAcquiresPerPeriod()); EasyMock.verify(service, future); } /** * Tests the acquire() method if more threads are involved than the limit. * This method starts a number of threads that all invoke the semaphore. The * semaphore's limit is set to 1, so in each period only a single thread can * acquire the semaphore. */ @Test public void testAcquireMultipleThreads() throws InterruptedException { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class); prepareStartTimer(service, future); EasyMock.replay(service, future); final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD, UNIT, 1); semaphore.latch = new CountDownLatch(1); final int count = 10; final SemaphoreThread[] threads = new SemaphoreThread[count]; for (int i = 0; i < count; i++) { threads[i] = new SemaphoreThread(semaphore, null, 1, 0); threads[i].start(); } for (int i = 0; i < count; i++) { semaphore.latch.await(); assertEquals("Wrong count", 1, semaphore.getAcquireCount()); semaphore.latch = new CountDownLatch(1); semaphore.endOfPeriod(); assertEquals("Wrong acquire count", 1, semaphore .getLastAcquiresPerPeriod()); } for (int i = 0; i < count; i++) { threads[i].join(); } EasyMock.verify(service, future); } /** * Tests the acquire() method if no limit is set. A test thread is started * that calls the semaphore a large number of times. Even if the semaphore's * period does not end, the thread should never block. */ @Test public void testAcquireNoLimit() throws InterruptedException { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class); prepareStartTimer(service, future); EasyMock.replay(service, future); final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD, UNIT, TimedSemaphore.NO_LIMIT); final int count = 1000; final CountDownLatch latch = new CountDownLatch(count); final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count); t.start(); latch.await(); EasyMock.verify(service, future); } /** * Tries to call acquire() after shutdown(). This should cause an exception. */ @Test(expected = IllegalStateException.class) public void testPassAfterShutdown() throws InterruptedException { final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT); semaphore.shutdown(); semaphore.acquire(); } /** * Tests a bigger number of invocations that span multiple periods. The * period is set to a very short time. A background thread calls the * semaphore a large number of times. While it runs at last one end of a * period should be reached. */ @Test public void testAcquireMultiplePeriods() throws InterruptedException { final int count = 1000; final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl( PERIOD / 10, TimeUnit.MILLISECONDS, 1); semaphore.setLimit(count / 4); final CountDownLatch latch = new CountDownLatch(count); final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count); t.start(); latch.await(); semaphore.shutdown(); assertTrue("End of period not reached", semaphore.getPeriodEnds() > 0); } /** * Tests the methods for statistics. */ @Test public void testGetAverageCallsPerPeriod() throws InterruptedException { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class); prepareStartTimer(service, future); EasyMock.replay(service, future); final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, LIMIT); semaphore.acquire(); semaphore.endOfPeriod(); assertEquals("Wrong average (1)", 1.0, semaphore .getAverageCallsPerPeriod(), .005); semaphore.acquire(); semaphore.acquire(); semaphore.endOfPeriod(); assertEquals("Wrong average (2)", 1.5, semaphore .getAverageCallsPerPeriod(), .005); EasyMock.verify(service, future); } /** * Tests whether the available non-blocking calls can be queried. */ @Test public void testGetAvailablePermits() throws InterruptedException { final ScheduledExecutorService service = EasyMock .createMock(ScheduledExecutorService.class); final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class); prepareStartTimer(service, future); EasyMock.replay(service, future); final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, LIMIT); for (int i = 0; i < LIMIT; i++) { assertEquals("Wrong available count at " + i, LIMIT - i, semaphore .getAvailablePermits()); semaphore.acquire(); } semaphore.endOfPeriod(); assertEquals("Wrong available count in new period", LIMIT, semaphore .getAvailablePermits()); EasyMock.verify(service, future); } /** * A specialized implementation of {@code TimedSemaphore} that is easier to * test. */ private static class TimedSemaphoreTestImpl extends TimedSemaphore { /** A mock scheduled future. */ ScheduledFuture<?> schedFuture; /** A latch for synchronizing with the main thread. */ volatile CountDownLatch latch; /** Counter for the endOfPeriod() invocations. */ private int periodEnds; public TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit, final int limit) { super(timePeriod, timeUnit, limit); } public TimedSemaphoreTestImpl(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit) { super(service, timePeriod, timeUnit, limit); } /** * Returns the number of invocations of the endOfPeriod() method. * * @return the endOfPeriod() invocations */ public int getPeriodEnds() { synchronized (this) { return periodEnds; } } /** * Invokes the latch if one is set. */ @Override public synchronized void acquire() throws InterruptedException { super.acquire(); if (latch != null) { latch.countDown(); } } /** * Counts the number of invocations. */ @Override protected synchronized void endOfPeriod() { super.endOfPeriod(); periodEnds++; } /** * Either returns the mock future or calls the super method. */ @Override protected ScheduledFuture<?> startTimer() { return schedFuture != null ? schedFuture : super.startTimer(); } } /** * A test thread class that will be used by tests for triggering the * semaphore. The thread calls the semaphore a configurable number of times. * When this is done, it can notify the main thread. */ private static class SemaphoreThread extends Thread { /** The semaphore. */ private final TimedSemaphore semaphore; /** A latch for communication with the main thread. */ private final CountDownLatch latch; /** The number of acquire() calls. */ private final int count; /** The number of invocations of the latch. */ private final int latchCount; public SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc) { semaphore = b; latch = l; count = c; latchCount = lc; } /** * Calls acquire() on the semaphore for the specified number of times. * Optionally the latch will also be triggered to synchronize with the * main test thread. */ @Override public void run() { try { for (int i = 0; i < count; i++) { semaphore.acquire(); if (i < latchCount) { latch.countDown(); } } } catch (final InterruptedException iex) { Thread.currentThread().interrupt(); } } } }
[ { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "acquire", "be_test_function_signature": "()V", "line_numbers": [ "293", "294", "297", "298", "301", "303", "304", "305", "307", "309", "310" ], "method_line_rate": 0.9090909090909091 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "endOfPeriod", "be_test_function_signature": "()V", "line_numbers": [ "416", "417", "418", "419", "420", "421" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "getExecutorService", "be_test_function_signature": "()Ljava/util/concurrent/ScheduledExecutorService;", "line_numbers": [ "391" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "getLimit", "be_test_function_signature": "()I", "line_numbers": [ "232" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "getPeriod", "be_test_function_signature": "()J", "line_numbers": [ "373" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "getUnit", "be_test_function_signature": "()Ljava/util/concurrent/TimeUnit;", "line_numbers": [ "382" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "isShutdown", "be_test_function_signature": "()Z", "line_numbers": [ "278" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "setLimit", "be_test_function_signature": "(I)V", "line_numbers": [ "246", "247" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "shutdown", "be_test_function_signature": "()V", "line_numbers": [ "255", "257", "260", "262", "263", "266", "268" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/TimedSemaphore.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.TimedSemaphore", "be_test_function_name": "startTimer", "be_test_function_signature": "()Ljava/util/concurrent/ScheduledFuture;", "line_numbers": [ "402" ], "method_line_rate": 1 } ]
public class XYPlotTests extends TestCase
public void testSerialization5() { XYSeriesCollection dataset1 = new XYSeriesCollection(); NumberAxis domainAxis1 = new NumberAxis("Domain 1"); NumberAxis rangeAxis1 = new NumberAxis("Range 1"); StandardXYItemRenderer renderer1 = new StandardXYItemRenderer(); XYPlot p1 = new XYPlot(dataset1, domainAxis1, rangeAxis1, renderer1); NumberAxis domainAxis2 = new NumberAxis("Domain 2"); NumberAxis rangeAxis2 = new NumberAxis("Range 2"); StandardXYItemRenderer renderer2 = new StandardXYItemRenderer(); XYSeriesCollection dataset2 = new XYSeriesCollection(); p1.setDataset(1, dataset2); p1.setDomainAxis(1, domainAxis2); p1.setRangeAxis(1, rangeAxis2); p1.setRenderer(1, renderer2); XYPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); p2 = (XYPlot) in.readObject(); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(p1, p2); // now check that all datasets, renderers and axes are being listened // too... NumberAxis domainAxisA = (NumberAxis) p2.getDomainAxis(0); NumberAxis rangeAxisA = (NumberAxis) p2.getRangeAxis(0); XYSeriesCollection datasetA = (XYSeriesCollection) p2.getDataset(0); StandardXYItemRenderer rendererA = (StandardXYItemRenderer) p2.getRenderer(0); NumberAxis domainAxisB = (NumberAxis) p2.getDomainAxis(1); NumberAxis rangeAxisB = (NumberAxis) p2.getRangeAxis(1); XYSeriesCollection datasetB = (XYSeriesCollection) p2.getDataset(1); StandardXYItemRenderer rendererB = (StandardXYItemRenderer) p2.getRenderer(1); assertTrue(datasetA.hasListener(p2)); assertTrue(domainAxisA.hasListener(p2)); assertTrue(rangeAxisA.hasListener(p2)); assertTrue(rendererA.hasListener(p2)); assertTrue(datasetB.hasListener(p2)); assertTrue(domainAxisB.hasListener(p2)); assertTrue(rangeAxisB.hasListener(p2)); assertTrue(rendererB.hasListener(p2)); }
// public AxisSpace getFixedRangeAxisSpace(); // public void setFixedRangeAxisSpace(AxisSpace space); // public void setFixedRangeAxisSpace(AxisSpace space, boolean notify); // public boolean isDomainPannable(); // public void setDomainPannable(boolean pannable); // public boolean isRangePannable(); // public void setRangePannable(boolean pannable); // public void panDomainAxes(double percent, PlotRenderingInfo info, // Point2D source); // public void panRangeAxes(double percent, PlotRenderingInfo info, // Point2D source); // public void zoomDomainAxes(double factor, PlotRenderingInfo info, // Point2D source); // public void zoomDomainAxes(double factor, PlotRenderingInfo info, // Point2D source, boolean useAnchor); // public void zoomDomainAxes(double lowerPercent, double upperPercent, // PlotRenderingInfo info, Point2D source); // public void zoomRangeAxes(double factor, PlotRenderingInfo info, // Point2D source); // public void zoomRangeAxes(double factor, PlotRenderingInfo info, // Point2D source, boolean useAnchor); // public void zoomRangeAxes(double lowerPercent, double upperPercent, // PlotRenderingInfo info, Point2D source); // public boolean isDomainZoomable(); // public boolean isRangeZoomable(); // public int getSeriesCount(); // public LegendItemCollection getFixedLegendItems(); // public void setFixedLegendItems(LegendItemCollection items); // public LegendItemCollection getLegendItems(); // public boolean equals(Object obj); // public Object clone() throws CloneNotSupportedException; // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public boolean canSelectByPoint(); // public boolean canSelectByRegion(); // public void select(double xx, double yy, Rectangle2D dataArea, // RenderingSource source); // public void select(GeneralPath region, Rectangle2D dataArea, // RenderingSource source); // private XYDatasetSelectionState findSelectionStateForDataset( // XYDataset dataset, Object source); // private GeneralPath convertToDataSpace(GeneralPath path, // Rectangle2D dataArea, XYDataset dataset); // public void clearSelection(); // } // // // Abstract Java Test Class // package org.jfree.chart.plot.junit; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Graphics2D; // import java.awt.Stroke; // import java.awt.geom.Point2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import java.util.Arrays; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.ChartFactory; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.LegendItem; // import org.jfree.chart.LegendItemCollection; // import org.jfree.chart.annotations.XYTextAnnotation; // import org.jfree.chart.axis.AxisLocation; // import org.jfree.chart.axis.DateAxis; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.event.MarkerChangeListener; // import org.jfree.chart.labels.StandardXYToolTipGenerator; // import org.jfree.chart.plot.IntervalMarker; // import org.jfree.chart.plot.Marker; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.ValueMarker; // import org.jfree.chart.plot.XYPlot; // import org.jfree.chart.renderer.xy.DefaultXYItemRenderer; // import org.jfree.chart.renderer.xy.StandardXYItemRenderer; // import org.jfree.chart.renderer.xy.XYBarRenderer; // import org.jfree.chart.renderer.xy.XYItemRenderer; // import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; // import org.jfree.chart.util.DefaultShadowGenerator; // import org.jfree.chart.util.Layer; // import org.jfree.chart.util.RectangleInsets; // import org.jfree.data.time.Day; // import org.jfree.data.time.MonthConstants; // import org.jfree.data.time.TimeSeries; // import org.jfree.data.time.TimeSeriesCollection; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // // // // public class XYPlotTests extends TestCase { // // // public static Test suite(); // public XYPlotTests(String name); // public void testEquals(); // public void testCloning(); // public void testCloning2(); // public void testCloning3(); // public void testCloning4(); // public void testCloning_QuadrantOrigin(); // public void testCloning_QuadrantPaint(); // public void testBug2817504(); // public void testCloneIndependence(); // public void testSetNullRenderer(); // public void testSerialization1(); // public void testSerialization2(); // public void testSerialization3(); // public void testSerialization4(); // public void testSerialization5(); // public void testGetRendererForDataset(); // public void testGetLegendItems(); // private IntervalXYDataset createDataset1(); // private XYDataset createDataset2(); // public void testSetRenderer(); // public void testRemoveAnnotation(); // public void testAddDomainMarker(); // public void testAddRangeMarker(); // public void test1654215(); // public void testDrawRangeGridlines(); // public void testDrawSeriesWithZeroItems(); // public void testRemoveDomainMarker(); // public void testRemoveRangeMarker(); // public void testGetDomainAxisForDataset(); // public void testGetRangeAxisForDataset(); // } // You are a professional Java test case writer, please create a test case named `testSerialization5` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests a bug where the plot is no longer registered as a listener * with the dataset(s) and axes after deserialization. See patch 1209475 * at SourceForge. */
tests/org/jfree/chart/plot/junit/XYPlotTests.java
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.RenderingSource; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.annotations.XYAnnotationBoundsInfo; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.AxisCollection; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.TickType; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.axis.ValueTick; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.event.ChartChangeEventType; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.renderer.RendererUtilities; import org.jfree.chart.renderer.xy.AbstractXYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRendererState; import org.jfree.chart.util.Layer; import org.jfree.chart.util.ObjectList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.RectangleInsets; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.ShadowGenerator; import org.jfree.data.Range; import org.jfree.data.general.Dataset; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.AbstractXYDataset; import org.jfree.data.xy.SelectableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYDatasetSelectionState;
public XYPlot(); public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer); public String getPlotType(); public PlotOrientation getOrientation(); public void setOrientation(PlotOrientation orientation); public RectangleInsets getAxisOffset(); public void setAxisOffset(RectangleInsets offset); public ValueAxis getDomainAxis(); public ValueAxis getDomainAxis(int index); public void setDomainAxis(ValueAxis axis); public void setDomainAxis(int index, ValueAxis axis); public void setDomainAxis(int index, ValueAxis axis, boolean notify); public void setDomainAxes(ValueAxis[] axes); public AxisLocation getDomainAxisLocation(); public void setDomainAxisLocation(AxisLocation location); public void setDomainAxisLocation(AxisLocation location, boolean notify); public RectangleEdge getDomainAxisEdge(); public int getDomainAxisCount(); public void clearDomainAxes(); public void configureDomainAxes(); public AxisLocation getDomainAxisLocation(int index); public void setDomainAxisLocation(int index, AxisLocation location); public void setDomainAxisLocation(int index, AxisLocation location, boolean notify); public RectangleEdge getDomainAxisEdge(int index); public ValueAxis getRangeAxis(); public void setRangeAxis(ValueAxis axis); public AxisLocation getRangeAxisLocation(); public void setRangeAxisLocation(AxisLocation location); public void setRangeAxisLocation(AxisLocation location, boolean notify); public RectangleEdge getRangeAxisEdge(); public ValueAxis getRangeAxis(int index); public void setRangeAxis(int index, ValueAxis axis); public void setRangeAxis(int index, ValueAxis axis, boolean notify); public void setRangeAxes(ValueAxis[] axes); public int getRangeAxisCount(); public void clearRangeAxes(); public void configureRangeAxes(); public AxisLocation getRangeAxisLocation(int index); public void setRangeAxisLocation(int index, AxisLocation location); public void setRangeAxisLocation(int index, AxisLocation location, boolean notify); public RectangleEdge getRangeAxisEdge(int index); public XYDataset getDataset(); public XYDataset getDataset(int index); public void setDataset(XYDataset dataset); public void setDataset(int index, XYDataset dataset); public int getDatasetCount(); public int indexOf(XYDataset dataset); public void mapDatasetToDomainAxis(int index, int axisIndex); public void mapDatasetToDomainAxes(int index, List axisIndices); public void mapDatasetToRangeAxis(int index, int axisIndex); public void mapDatasetToRangeAxes(int index, List axisIndices); private void checkAxisIndices(List indices); public int getRendererCount(); public XYItemRenderer getRenderer(); public XYItemRenderer getRenderer(int index); public void setRenderer(XYItemRenderer renderer); public void setRenderer(int index, XYItemRenderer renderer); public void setRenderer(int index, XYItemRenderer renderer, boolean notify); public void setRenderers(XYItemRenderer[] renderers); public DatasetRenderingOrder getDatasetRenderingOrder(); public void setDatasetRenderingOrder(DatasetRenderingOrder order); public SeriesRenderingOrder getSeriesRenderingOrder(); public void setSeriesRenderingOrder(SeriesRenderingOrder order); public int getIndexOf(XYItemRenderer renderer); public XYItemRenderer getRendererForDataset(XYDataset dataset); public int getWeight(); public void setWeight(int weight); public boolean isDomainGridlinesVisible(); public void setDomainGridlinesVisible(boolean visible); public boolean isDomainMinorGridlinesVisible(); public void setDomainMinorGridlinesVisible(boolean visible); public Stroke getDomainGridlineStroke(); public void setDomainGridlineStroke(Stroke stroke); public Stroke getDomainMinorGridlineStroke(); public void setDomainMinorGridlineStroke(Stroke stroke); public Paint getDomainGridlinePaint(); public void setDomainGridlinePaint(Paint paint); public Paint getDomainMinorGridlinePaint(); public void setDomainMinorGridlinePaint(Paint paint); public boolean isRangeGridlinesVisible(); public void setRangeGridlinesVisible(boolean visible); public Stroke getRangeGridlineStroke(); public void setRangeGridlineStroke(Stroke stroke); public Paint getRangeGridlinePaint(); public void setRangeGridlinePaint(Paint paint); public boolean isRangeMinorGridlinesVisible(); public void setRangeMinorGridlinesVisible(boolean visible); public Stroke getRangeMinorGridlineStroke(); public void setRangeMinorGridlineStroke(Stroke stroke); public Paint getRangeMinorGridlinePaint(); public void setRangeMinorGridlinePaint(Paint paint); public boolean isDomainZeroBaselineVisible(); public void setDomainZeroBaselineVisible(boolean visible); public Stroke getDomainZeroBaselineStroke(); public void setDomainZeroBaselineStroke(Stroke stroke); public Paint getDomainZeroBaselinePaint(); public void setDomainZeroBaselinePaint(Paint paint); public boolean isRangeZeroBaselineVisible(); public void setRangeZeroBaselineVisible(boolean visible); public Stroke getRangeZeroBaselineStroke(); public void setRangeZeroBaselineStroke(Stroke stroke); public Paint getRangeZeroBaselinePaint(); public void setRangeZeroBaselinePaint(Paint paint); public Paint getDomainTickBandPaint(); public void setDomainTickBandPaint(Paint paint); public Paint getRangeTickBandPaint(); public void setRangeTickBandPaint(Paint paint); public Point2D getQuadrantOrigin(); public void setQuadrantOrigin(Point2D origin); public Paint getQuadrantPaint(int index); public void setQuadrantPaint(int index, Paint paint); public void addDomainMarker(Marker marker); public void addDomainMarker(Marker marker, Layer layer); public void clearDomainMarkers(); public void clearDomainMarkers(int index); public void addDomainMarker(int index, Marker marker, Layer layer); public void addDomainMarker(int index, Marker marker, Layer layer, boolean notify); public boolean removeDomainMarker(Marker marker); public boolean removeDomainMarker(Marker marker, Layer layer); public boolean removeDomainMarker(int index, Marker marker, Layer layer); public boolean removeDomainMarker(int index, Marker marker, Layer layer, boolean notify); public void addRangeMarker(Marker marker); public void addRangeMarker(Marker marker, Layer layer); public void clearRangeMarkers(); public void addRangeMarker(int index, Marker marker, Layer layer); public void addRangeMarker(int index, Marker marker, Layer layer, boolean notify); public void clearRangeMarkers(int index); public boolean removeRangeMarker(Marker marker); public boolean removeRangeMarker(Marker marker, Layer layer); public boolean removeRangeMarker(int index, Marker marker, Layer layer); public boolean removeRangeMarker(int index, Marker marker, Layer layer, boolean notify); public void addAnnotation(XYAnnotation annotation); public void addAnnotation(XYAnnotation annotation, boolean notify); public boolean removeAnnotation(XYAnnotation annotation); public boolean removeAnnotation(XYAnnotation annotation, boolean notify); public List getAnnotations(); public void clearAnnotations(); public ShadowGenerator getShadowGenerator(); public void setShadowGenerator(ShadowGenerator generator); protected AxisSpace calculateAxisSpace(Graphics2D g2, Rectangle2D plotArea); protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space); protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space); private Rectangle integerise(Rectangle2D rect); public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); public void drawBackground(Graphics2D g2, Rectangle2D area); protected void drawQuadrants(Graphics2D g2, Rectangle2D area); public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks); public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks); protected Map drawAxes(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, PlotRenderingInfo plotState); public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CrosshairState crosshairState); public ValueAxis getDomainAxisForDataset(int index); public ValueAxis getRangeAxisForDataset(int index); protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea, List ticks); protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area, List ticks); protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area); protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area); public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info); protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer); protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer); public Collection getDomainMarkers(Layer layer); public Collection getRangeMarkers(Layer layer); public Collection getDomainMarkers(int index, Layer layer); public Collection getRangeMarkers(int index, Layer layer); protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint); protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint); protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint); protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint); public void handleClick(int x, int y, PlotRenderingInfo info); private List getDatasetsMappedToDomainAxis(Integer axisIndex); private List getDatasetsMappedToRangeAxis(Integer axisIndex); public int getDomainAxisIndex(ValueAxis axis); public int getRangeAxisIndex(ValueAxis axis); public Range getDataRange(ValueAxis axis); public void annotationChanged(AnnotationChangeEvent event); public void datasetChanged(DatasetChangeEvent event); public void rendererChanged(RendererChangeEvent event); public boolean isDomainCrosshairVisible(); public void setDomainCrosshairVisible(boolean flag); public boolean isDomainCrosshairLockedOnData(); public void setDomainCrosshairLockedOnData(boolean flag); public double getDomainCrosshairValue(); public void setDomainCrosshairValue(double value); public void setDomainCrosshairValue(double value, boolean notify); public Stroke getDomainCrosshairStroke(); public void setDomainCrosshairStroke(Stroke stroke); public Paint getDomainCrosshairPaint(); public void setDomainCrosshairPaint(Paint paint); public boolean isRangeCrosshairVisible(); public void setRangeCrosshairVisible(boolean flag); public boolean isRangeCrosshairLockedOnData(); public void setRangeCrosshairLockedOnData(boolean flag); public double getRangeCrosshairValue(); public void setRangeCrosshairValue(double value); public void setRangeCrosshairValue(double value, boolean notify); public Stroke getRangeCrosshairStroke(); public void setRangeCrosshairStroke(Stroke stroke); public Paint getRangeCrosshairPaint(); public void setRangeCrosshairPaint(Paint paint); public AxisSpace getFixedDomainAxisSpace(); public void setFixedDomainAxisSpace(AxisSpace space); public void setFixedDomainAxisSpace(AxisSpace space, boolean notify); public AxisSpace getFixedRangeAxisSpace(); public void setFixedRangeAxisSpace(AxisSpace space); public void setFixedRangeAxisSpace(AxisSpace space, boolean notify); public boolean isDomainPannable(); public void setDomainPannable(boolean pannable); public boolean isRangePannable(); public void setRangePannable(boolean pannable); public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source); public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source); public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source); public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor); public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source); public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor); public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); public boolean isDomainZoomable(); public boolean isRangeZoomable(); public int getSeriesCount(); public LegendItemCollection getFixedLegendItems(); public void setFixedLegendItems(LegendItemCollection items); public LegendItemCollection getLegendItems(); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException; private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public boolean canSelectByPoint(); public boolean canSelectByRegion(); public void select(double xx, double yy, Rectangle2D dataArea, RenderingSource source); public void select(GeneralPath region, Rectangle2D dataArea, RenderingSource source); private XYDatasetSelectionState findSelectionStateForDataset( XYDataset dataset, Object source); private GeneralPath convertToDataSpace(GeneralPath path, Rectangle2D dataArea, XYDataset dataset); public void clearSelection();
912
testSerialization5
```java public AxisSpace getFixedRangeAxisSpace(); public void setFixedRangeAxisSpace(AxisSpace space); public void setFixedRangeAxisSpace(AxisSpace space, boolean notify); public boolean isDomainPannable(); public void setDomainPannable(boolean pannable); public boolean isRangePannable(); public void setRangePannable(boolean pannable); public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source); public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source); public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source); public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor); public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source); public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor); public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); public boolean isDomainZoomable(); public boolean isRangeZoomable(); public int getSeriesCount(); public LegendItemCollection getFixedLegendItems(); public void setFixedLegendItems(LegendItemCollection items); public LegendItemCollection getLegendItems(); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException; private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public boolean canSelectByPoint(); public boolean canSelectByRegion(); public void select(double xx, double yy, Rectangle2D dataArea, RenderingSource source); public void select(GeneralPath region, Rectangle2D dataArea, RenderingSource source); private XYDatasetSelectionState findSelectionStateForDataset( XYDataset dataset, Object source); private GeneralPath convertToDataSpace(GeneralPath path, Rectangle2D dataArea, XYDataset dataset); public void clearSelection(); } // Abstract Java Test Class package org.jfree.chart.plot.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.MarkerChangeListener; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DefaultXYItemRenderer; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.util.DefaultShadowGenerator; import org.jfree.chart.util.Layer; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.time.Day; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class XYPlotTests extends TestCase { public static Test suite(); public XYPlotTests(String name); public void testEquals(); public void testCloning(); public void testCloning2(); public void testCloning3(); public void testCloning4(); public void testCloning_QuadrantOrigin(); public void testCloning_QuadrantPaint(); public void testBug2817504(); public void testCloneIndependence(); public void testSetNullRenderer(); public void testSerialization1(); public void testSerialization2(); public void testSerialization3(); public void testSerialization4(); public void testSerialization5(); public void testGetRendererForDataset(); public void testGetLegendItems(); private IntervalXYDataset createDataset1(); private XYDataset createDataset2(); public void testSetRenderer(); public void testRemoveAnnotation(); public void testAddDomainMarker(); public void testAddRangeMarker(); public void test1654215(); public void testDrawRangeGridlines(); public void testDrawSeriesWithZeroItems(); public void testRemoveDomainMarker(); public void testRemoveRangeMarker(); public void testGetDomainAxisForDataset(); public void testGetRangeAxisForDataset(); } ``` You are a professional Java test case writer, please create a test case named `testSerialization5` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests a bug where the plot is no longer registered as a listener * with the dataset(s) and axes after deserialization. See patch 1209475 * at SourceForge. */
861
// public AxisSpace getFixedRangeAxisSpace(); // public void setFixedRangeAxisSpace(AxisSpace space); // public void setFixedRangeAxisSpace(AxisSpace space, boolean notify); // public boolean isDomainPannable(); // public void setDomainPannable(boolean pannable); // public boolean isRangePannable(); // public void setRangePannable(boolean pannable); // public void panDomainAxes(double percent, PlotRenderingInfo info, // Point2D source); // public void panRangeAxes(double percent, PlotRenderingInfo info, // Point2D source); // public void zoomDomainAxes(double factor, PlotRenderingInfo info, // Point2D source); // public void zoomDomainAxes(double factor, PlotRenderingInfo info, // Point2D source, boolean useAnchor); // public void zoomDomainAxes(double lowerPercent, double upperPercent, // PlotRenderingInfo info, Point2D source); // public void zoomRangeAxes(double factor, PlotRenderingInfo info, // Point2D source); // public void zoomRangeAxes(double factor, PlotRenderingInfo info, // Point2D source, boolean useAnchor); // public void zoomRangeAxes(double lowerPercent, double upperPercent, // PlotRenderingInfo info, Point2D source); // public boolean isDomainZoomable(); // public boolean isRangeZoomable(); // public int getSeriesCount(); // public LegendItemCollection getFixedLegendItems(); // public void setFixedLegendItems(LegendItemCollection items); // public LegendItemCollection getLegendItems(); // public boolean equals(Object obj); // public Object clone() throws CloneNotSupportedException; // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public boolean canSelectByPoint(); // public boolean canSelectByRegion(); // public void select(double xx, double yy, Rectangle2D dataArea, // RenderingSource source); // public void select(GeneralPath region, Rectangle2D dataArea, // RenderingSource source); // private XYDatasetSelectionState findSelectionStateForDataset( // XYDataset dataset, Object source); // private GeneralPath convertToDataSpace(GeneralPath path, // Rectangle2D dataArea, XYDataset dataset); // public void clearSelection(); // } // // // Abstract Java Test Class // package org.jfree.chart.plot.junit; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Graphics2D; // import java.awt.Stroke; // import java.awt.geom.Point2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import java.util.Arrays; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.ChartFactory; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.LegendItem; // import org.jfree.chart.LegendItemCollection; // import org.jfree.chart.annotations.XYTextAnnotation; // import org.jfree.chart.axis.AxisLocation; // import org.jfree.chart.axis.DateAxis; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.event.MarkerChangeListener; // import org.jfree.chart.labels.StandardXYToolTipGenerator; // import org.jfree.chart.plot.IntervalMarker; // import org.jfree.chart.plot.Marker; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.ValueMarker; // import org.jfree.chart.plot.XYPlot; // import org.jfree.chart.renderer.xy.DefaultXYItemRenderer; // import org.jfree.chart.renderer.xy.StandardXYItemRenderer; // import org.jfree.chart.renderer.xy.XYBarRenderer; // import org.jfree.chart.renderer.xy.XYItemRenderer; // import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; // import org.jfree.chart.util.DefaultShadowGenerator; // import org.jfree.chart.util.Layer; // import org.jfree.chart.util.RectangleInsets; // import org.jfree.data.time.Day; // import org.jfree.data.time.MonthConstants; // import org.jfree.data.time.TimeSeries; // import org.jfree.data.time.TimeSeriesCollection; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // // // // public class XYPlotTests extends TestCase { // // // public static Test suite(); // public XYPlotTests(String name); // public void testEquals(); // public void testCloning(); // public void testCloning2(); // public void testCloning3(); // public void testCloning4(); // public void testCloning_QuadrantOrigin(); // public void testCloning_QuadrantPaint(); // public void testBug2817504(); // public void testCloneIndependence(); // public void testSetNullRenderer(); // public void testSerialization1(); // public void testSerialization2(); // public void testSerialization3(); // public void testSerialization4(); // public void testSerialization5(); // public void testGetRendererForDataset(); // public void testGetLegendItems(); // private IntervalXYDataset createDataset1(); // private XYDataset createDataset2(); // public void testSetRenderer(); // public void testRemoveAnnotation(); // public void testAddDomainMarker(); // public void testAddRangeMarker(); // public void test1654215(); // public void testDrawRangeGridlines(); // public void testDrawSeriesWithZeroItems(); // public void testRemoveDomainMarker(); // public void testRemoveRangeMarker(); // public void testGetDomainAxisForDataset(); // public void testGetRangeAxisForDataset(); // } // You are a professional Java test case writer, please create a test case named `testSerialization5` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests a bug where the plot is no longer registered as a listener * with the dataset(s) and axes after deserialization. See patch 1209475 * at SourceForge. */ public void testSerialization5() {
/** * Tests a bug where the plot is no longer registered as a listener * with the dataset(s) and axes after deserialization. See patch 1209475 * at SourceForge. */
1
org.jfree.chart.plot.XYPlot
tests
```java public AxisSpace getFixedRangeAxisSpace(); public void setFixedRangeAxisSpace(AxisSpace space); public void setFixedRangeAxisSpace(AxisSpace space, boolean notify); public boolean isDomainPannable(); public void setDomainPannable(boolean pannable); public boolean isRangePannable(); public void setRangePannable(boolean pannable); public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source); public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source); public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source); public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor); public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source); public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor); public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); public boolean isDomainZoomable(); public boolean isRangeZoomable(); public int getSeriesCount(); public LegendItemCollection getFixedLegendItems(); public void setFixedLegendItems(LegendItemCollection items); public LegendItemCollection getLegendItems(); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException; private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public boolean canSelectByPoint(); public boolean canSelectByRegion(); public void select(double xx, double yy, Rectangle2D dataArea, RenderingSource source); public void select(GeneralPath region, Rectangle2D dataArea, RenderingSource source); private XYDatasetSelectionState findSelectionStateForDataset( XYDataset dataset, Object source); private GeneralPath convertToDataSpace(GeneralPath path, Rectangle2D dataArea, XYDataset dataset); public void clearSelection(); } // Abstract Java Test Class package org.jfree.chart.plot.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.MarkerChangeListener; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DefaultXYItemRenderer; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.util.DefaultShadowGenerator; import org.jfree.chart.util.Layer; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.time.Day; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class XYPlotTests extends TestCase { public static Test suite(); public XYPlotTests(String name); public void testEquals(); public void testCloning(); public void testCloning2(); public void testCloning3(); public void testCloning4(); public void testCloning_QuadrantOrigin(); public void testCloning_QuadrantPaint(); public void testBug2817504(); public void testCloneIndependence(); public void testSetNullRenderer(); public void testSerialization1(); public void testSerialization2(); public void testSerialization3(); public void testSerialization4(); public void testSerialization5(); public void testGetRendererForDataset(); public void testGetLegendItems(); private IntervalXYDataset createDataset1(); private XYDataset createDataset2(); public void testSetRenderer(); public void testRemoveAnnotation(); public void testAddDomainMarker(); public void testAddRangeMarker(); public void test1654215(); public void testDrawRangeGridlines(); public void testDrawSeriesWithZeroItems(); public void testRemoveDomainMarker(); public void testRemoveRangeMarker(); public void testGetDomainAxisForDataset(); public void testGetRangeAxisForDataset(); } ``` You are a professional Java test case writer, please create a test case named `testSerialization5` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests a bug where the plot is no longer registered as a listener * with the dataset(s) and axes after deserialization. See patch 1209475 * at SourceForge. */ public void testSerialization5() { ```
public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Selectable, Zoomable, RendererChangeListener, Cloneable, PublicCloneable, Serializable
package org.jfree.chart.plot.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.MarkerChangeListener; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DefaultXYItemRenderer; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.util.DefaultShadowGenerator; import org.jfree.chart.util.Layer; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.time.Day; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection;
public static Test suite(); public XYPlotTests(String name); public void testEquals(); public void testCloning(); public void testCloning2(); public void testCloning3(); public void testCloning4(); public void testCloning_QuadrantOrigin(); public void testCloning_QuadrantPaint(); public void testBug2817504(); public void testCloneIndependence(); public void testSetNullRenderer(); public void testSerialization1(); public void testSerialization2(); public void testSerialization3(); public void testSerialization4(); public void testSerialization5(); public void testGetRendererForDataset(); public void testGetLegendItems(); private IntervalXYDataset createDataset1(); private XYDataset createDataset2(); public void testSetRenderer(); public void testRemoveAnnotation(); public void testAddDomainMarker(); public void testAddRangeMarker(); public void test1654215(); public void testDrawRangeGridlines(); public void testDrawSeriesWithZeroItems(); public void testRemoveDomainMarker(); public void testRemoveRangeMarker(); public void testGetDomainAxisForDataset(); public void testGetRangeAxisForDataset();
ccc3f835b76c2191424ae611b538bac96922f8431f3756587e31025291ded0ee
[ "org.jfree.chart.plot.junit.XYPlotTests::testSerialization5" ]
private static final long serialVersionUID = 7044148245716569264L; public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] {2.0f, 2.0f}, 0.0f); public static final Paint DEFAULT_GRIDLINE_PAINT = Color.WHITE; public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false; public static final Stroke DEFAULT_CROSSHAIR_STROKE = DEFAULT_GRIDLINE_STROKE; public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue; protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); private PlotOrientation orientation; private RectangleInsets axisOffset; private ObjectList domainAxes; private ObjectList domainAxisLocations; private ObjectList rangeAxes; private ObjectList rangeAxisLocations; private ObjectList datasets; private ObjectList renderers; private Map datasetToDomainAxesMap; private Map datasetToRangeAxesMap; private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0); private transient Paint[] quadrantPaint = new Paint[] {null, null, null, null}; private boolean domainGridlinesVisible; private transient Stroke domainGridlineStroke; private transient Paint domainGridlinePaint; private boolean rangeGridlinesVisible; private transient Stroke rangeGridlineStroke; private transient Paint rangeGridlinePaint; private boolean domainMinorGridlinesVisible; private transient Stroke domainMinorGridlineStroke; private transient Paint domainMinorGridlinePaint; private boolean rangeMinorGridlinesVisible; private transient Stroke rangeMinorGridlineStroke; private transient Paint rangeMinorGridlinePaint; private boolean domainZeroBaselineVisible; private transient Stroke domainZeroBaselineStroke; private transient Paint domainZeroBaselinePaint; private boolean rangeZeroBaselineVisible; private transient Stroke rangeZeroBaselineStroke; private transient Paint rangeZeroBaselinePaint; private boolean domainCrosshairVisible; private double domainCrosshairValue; private transient Stroke domainCrosshairStroke; private transient Paint domainCrosshairPaint; private boolean domainCrosshairLockedOnData = true; private boolean rangeCrosshairVisible; private double rangeCrosshairValue; private transient Stroke rangeCrosshairStroke; private transient Paint rangeCrosshairPaint; private boolean rangeCrosshairLockedOnData = true; private Map foregroundDomainMarkers; private Map backgroundDomainMarkers; private Map foregroundRangeMarkers; private Map backgroundRangeMarkers; private List annotations; private transient Paint domainTickBandPaint; private transient Paint rangeTickBandPaint; private AxisSpace fixedDomainAxisSpace; private AxisSpace fixedRangeAxisSpace; private DatasetRenderingOrder datasetRenderingOrder = DatasetRenderingOrder.REVERSE; private SeriesRenderingOrder seriesRenderingOrder = SeriesRenderingOrder.REVERSE; private int weight; private LegendItemCollection fixedLegendItems; private boolean domainPannable; private boolean rangePannable; private ShadowGenerator shadowGenerator;
public void testSerialization5()
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2009, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * XYPlotTests.java * ---------------- * (C) Copyright 2003-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 26-Mar-2003 : Version 1 (DG); * 22-Mar-2004 : Added new cloning test (DG); * 05-Oct-2004 : Strengthened test for clone independence (DG); * 22-Nov-2006 : Added quadrant fields to equals() and clone() tests (DG); * 09-Jan-2007 : Mark and comment out testGetDatasetCount() (DG); * 05-Feb-2007 : Added testAddDomainMarker() and testAddRangeMarker() (DG); * 07-Feb-2007 : Added test1654215() (DG); * 24-May-2007 : Added testDrawSeriesWithZeroItems() (DG); * 20-Jun-2007 : Removed JCommon dependencies (DG); * 07-Apr-2008 : Added testRemoveDomainMarker() and * testRemoveRangeMarker() (DG); * 10-May-2009 : Extended testEquals(), added testCloning3() (DG); * 06-Jul-2009 : Added testBug2817504() (DG); * */ package org.jfree.chart.plot.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.MarkerChangeListener; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DefaultXYItemRenderer; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.util.DefaultShadowGenerator; import org.jfree.chart.util.Layer; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.time.Day; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /** * Tests for the {@link XYPlot} class. */ public class XYPlotTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(XYPlotTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public XYPlotTests(String name) { super(name); } // FIXME: the getDatasetCount() method is returning a count of the slots // available for datasets, rather than the number of datasets actually // specified...see if there is some way to clean this up. // /** // * Added this test in response to a bug report. // */ // public void testGetDatasetCount() { // XYPlot plot = new XYPlot(); // assertEquals(0, plot.getDatasetCount()); // } /** * Some checks for the equals() method. */ public void testEquals() { XYPlot plot1 = new XYPlot(); XYPlot plot2 = new XYPlot(); assertTrue(plot1.equals(plot2)); // orientation... plot1.setOrientation(PlotOrientation.HORIZONTAL); assertFalse(plot1.equals(plot2)); plot2.setOrientation(PlotOrientation.HORIZONTAL); assertTrue(plot1.equals(plot2)); // axisOffset... plot1.setAxisOffset(new RectangleInsets(0.05, 0.05, 0.05, 0.05)); assertFalse(plot1.equals(plot2)); plot2.setAxisOffset(new RectangleInsets(0.05, 0.05, 0.05, 0.05)); assertTrue(plot1.equals(plot2)); // domainAxis... plot1.setDomainAxis(new NumberAxis("Domain Axis")); assertFalse(plot1.equals(plot2)); plot2.setDomainAxis(new NumberAxis("Domain Axis")); assertTrue(plot1.equals(plot2)); // domainAxisLocation... plot1.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT); assertFalse(plot1.equals(plot2)); plot2.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT); assertTrue(plot1.equals(plot2)); // secondary DomainAxes... plot1.setDomainAxis(11, new NumberAxis("Secondary Domain Axis")); assertFalse(plot1.equals(plot2)); plot2.setDomainAxis(11, new NumberAxis("Secondary Domain Axis")); assertTrue(plot1.equals(plot2)); // secondary DomainAxisLocations... plot1.setDomainAxisLocation(11, AxisLocation.TOP_OR_RIGHT); assertFalse(plot1.equals(plot2)); plot2.setDomainAxisLocation(11, AxisLocation.TOP_OR_RIGHT); assertTrue(plot1.equals(plot2)); // rangeAxis... plot1.setRangeAxis(new NumberAxis("Range Axis")); assertFalse(plot1.equals(plot2)); plot2.setRangeAxis(new NumberAxis("Range Axis")); assertTrue(plot1.equals(plot2)); // rangeAxisLocation... plot1.setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT); assertFalse(plot1.equals(plot2)); plot2.setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT); assertTrue(plot1.equals(plot2)); // secondary RangeAxes... plot1.setRangeAxis(11, new NumberAxis("Secondary Range Axis")); assertFalse(plot1.equals(plot2)); plot2.setRangeAxis(11, new NumberAxis("Secondary Range Axis")); assertTrue(plot1.equals(plot2)); // secondary RangeAxisLocations... plot1.setRangeAxisLocation(11, AxisLocation.TOP_OR_RIGHT); assertFalse(plot1.equals(plot2)); plot2.setRangeAxisLocation(11, AxisLocation.TOP_OR_RIGHT); assertTrue(plot1.equals(plot2)); // secondary DatasetDomainAxisMap... plot1.mapDatasetToDomainAxis(11, 11); assertFalse(plot1.equals(plot2)); plot2.mapDatasetToDomainAxis(11, 11); assertTrue(plot1.equals(plot2)); // secondaryDatasetRangeAxisMap... plot1.mapDatasetToRangeAxis(11, 11); assertFalse(plot1.equals(plot2)); plot2.mapDatasetToRangeAxis(11, 11); assertTrue(plot1.equals(plot2)); // renderer plot1.setRenderer(new DefaultXYItemRenderer()); assertFalse(plot1.equals(plot2)); plot2.setRenderer(new DefaultXYItemRenderer()); assertTrue(plot1.equals(plot2)); // secondary renderers plot1.setRenderer(11, new DefaultXYItemRenderer()); assertFalse(plot1.equals(plot2)); plot2.setRenderer(11, new DefaultXYItemRenderer()); assertTrue(plot1.equals(plot2)); // domainGridlinesVisible plot1.setDomainGridlinesVisible(false); assertFalse(plot1.equals(plot2)); plot2.setDomainGridlinesVisible(false); assertTrue(plot1.equals(plot2)); // domainGridlineStroke Stroke stroke = new BasicStroke(2.0f); plot1.setDomainGridlineStroke(stroke); assertFalse(plot1.equals(plot2)); plot2.setDomainGridlineStroke(stroke); assertTrue(plot1.equals(plot2)); // domainGridlinePaint plot1.setDomainGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.red)); assertFalse(plot1.equals(plot2)); plot2.setDomainGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.red)); assertTrue(plot1.equals(plot2)); // rangeGridlinesVisible plot1.setRangeGridlinesVisible(false); assertFalse(plot1.equals(plot2)); plot2.setRangeGridlinesVisible(false); assertTrue(plot1.equals(plot2)); // rangeGridlineStroke plot1.setRangeGridlineStroke(stroke); assertFalse(plot1.equals(plot2)); plot2.setRangeGridlineStroke(stroke); assertTrue(plot1.equals(plot2)); // rangeGridlinePaint plot1.setRangeGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.green, 3.0f, 4.0f, Color.red)); assertFalse(plot1.equals(plot2)); plot2.setRangeGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.green, 3.0f, 4.0f, Color.red)); assertTrue(plot1.equals(plot2)); // rangeZeroBaselineVisible plot1.setRangeZeroBaselineVisible(true); assertFalse(plot1.equals(plot2)); plot2.setRangeZeroBaselineVisible(true); assertTrue(plot1.equals(plot2)); // rangeZeroBaselineStroke plot1.setRangeZeroBaselineStroke(stroke); assertFalse(plot1.equals(plot2)); plot2.setRangeZeroBaselineStroke(stroke); assertTrue(plot1.equals(plot2)); // rangeZeroBaselinePaint plot1.setRangeZeroBaselinePaint(new GradientPaint(1.0f, 2.0f, Color.white, 3.0f, 4.0f, Color.red)); assertFalse(plot1.equals(plot2)); plot2.setRangeZeroBaselinePaint(new GradientPaint(1.0f, 2.0f, Color.white, 3.0f, 4.0f, Color.red)); assertTrue(plot1.equals(plot2)); // rangeCrosshairVisible plot1.setRangeCrosshairVisible(true); assertFalse(plot1.equals(plot2)); plot2.setRangeCrosshairVisible(true); assertTrue(plot1.equals(plot2)); // rangeCrosshairValue plot1.setRangeCrosshairValue(100.0); assertFalse(plot1.equals(plot2)); plot2.setRangeCrosshairValue(100.0); assertTrue(plot1.equals(plot2)); // rangeCrosshairStroke plot1.setRangeCrosshairStroke(stroke); assertFalse(plot1.equals(plot2)); plot2.setRangeCrosshairStroke(stroke); assertTrue(plot1.equals(plot2)); // rangeCrosshairPaint plot1.setRangeCrosshairPaint(new GradientPaint(1.0f, 2.0f, Color.pink, 3.0f, 4.0f, Color.red)); assertFalse(plot1.equals(plot2)); plot2.setRangeCrosshairPaint(new GradientPaint(1.0f, 2.0f, Color.pink, 3.0f, 4.0f, Color.red)); assertTrue(plot1.equals(plot2)); // rangeCrosshairLockedOnData plot1.setRangeCrosshairLockedOnData(false); assertFalse(plot1.equals(plot2)); plot2.setRangeCrosshairLockedOnData(false); assertTrue(plot1.equals(plot2)); // range markers plot1.addRangeMarker(new ValueMarker(4.0)); assertFalse(plot1.equals(plot2)); plot2.addRangeMarker(new ValueMarker(4.0)); assertTrue(plot1.equals(plot2)); // secondary range markers plot1.addRangeMarker(1, new ValueMarker(4.0), Layer.FOREGROUND); assertFalse(plot1.equals(plot2)); plot2.addRangeMarker(1, new ValueMarker(4.0), Layer.FOREGROUND); assertTrue(plot1.equals(plot2)); plot1.addRangeMarker(1, new ValueMarker(99.0), Layer.BACKGROUND); assertFalse(plot1.equals(plot2)); plot2.addRangeMarker(1, new ValueMarker(99.0), Layer.BACKGROUND); assertTrue(plot1.equals(plot2)); // fixed legend items plot1.setFixedLegendItems(new LegendItemCollection()); assertFalse(plot1.equals(plot2)); plot2.setFixedLegendItems(new LegendItemCollection()); assertTrue(plot1.equals(plot2)); // weight plot1.setWeight(3); assertFalse(plot1.equals(plot2)); plot2.setWeight(3); assertTrue(plot1.equals(plot2)); // quadrant origin plot1.setQuadrantOrigin(new Point2D.Double(12.3, 45.6)); assertFalse(plot1.equals(plot2)); plot2.setQuadrantOrigin(new Point2D.Double(12.3, 45.6)); assertTrue(plot1.equals(plot2)); // quadrant paint plot1.setQuadrantPaint(0, new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setQuadrantPaint(0, new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertTrue(plot1.equals(plot2)); plot1.setQuadrantPaint(1, new GradientPaint(2.0f, 3.0f, Color.red, 4.0f, 5.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setQuadrantPaint(1, new GradientPaint(2.0f, 3.0f, Color.red, 4.0f, 5.0f, Color.blue)); assertTrue(plot1.equals(plot2)); plot1.setQuadrantPaint(2, new GradientPaint(3.0f, 4.0f, Color.red, 5.0f, 6.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setQuadrantPaint(2, new GradientPaint(3.0f, 4.0f, Color.red, 5.0f, 6.0f, Color.blue)); assertTrue(plot1.equals(plot2)); plot1.setQuadrantPaint(3, new GradientPaint(4.0f, 5.0f, Color.red, 6.0f, 7.0f, Color.blue)); assertFalse(plot1.equals(plot2)); plot2.setQuadrantPaint(3, new GradientPaint(4.0f, 5.0f, Color.red, 6.0f, 7.0f, Color.blue)); assertTrue(plot1.equals(plot2)); plot1.setDomainTickBandPaint(Color.red); assertFalse(plot1.equals(plot2)); plot2.setDomainTickBandPaint(Color.red); assertTrue(plot1.equals(plot2)); plot1.setRangeTickBandPaint(Color.blue); assertFalse(plot1.equals(plot2)); plot2.setRangeTickBandPaint(Color.blue); assertTrue(plot1.equals(plot2)); plot1.setDomainMinorGridlinesVisible(true); assertFalse(plot1.equals(plot2)); plot2.setDomainMinorGridlinesVisible(true); assertTrue(plot1.equals(plot2)); plot1.setDomainMinorGridlinePaint(Color.red); assertFalse(plot1.equals(plot2)); plot2.setDomainMinorGridlinePaint(Color.red); assertTrue(plot1.equals(plot2)); plot1.setDomainGridlineStroke(new BasicStroke(1.1f)); assertFalse(plot1.equals(plot2)); plot2.setDomainGridlineStroke(new BasicStroke(1.1f)); assertTrue(plot1.equals(plot2)); plot1.setRangeMinorGridlinesVisible(true); assertFalse(plot1.equals(plot2)); plot2.setRangeMinorGridlinesVisible(true); assertTrue(plot1.equals(plot2)); plot1.setRangeMinorGridlinePaint(Color.blue); assertFalse(plot1.equals(plot2)); plot2.setRangeMinorGridlinePaint(Color.blue); assertTrue(plot1.equals(plot2)); plot1.setRangeMinorGridlineStroke(new BasicStroke(1.23f)); assertFalse(plot1.equals(plot2)); plot2.setRangeMinorGridlineStroke(new BasicStroke(1.23f)); assertTrue(plot1.equals(plot2)); List axisIndices = Arrays.asList(new Integer[] {new Integer(0), new Integer(1)}); plot1.mapDatasetToDomainAxes(0, axisIndices); assertFalse(plot1.equals(plot2)); plot2.mapDatasetToDomainAxes(0, axisIndices); assertTrue(plot1.equals(plot2)); plot1.mapDatasetToRangeAxes(0, axisIndices); assertFalse(plot1.equals(plot2)); plot2.mapDatasetToRangeAxes(0, axisIndices); assertTrue(plot1.equals(plot2)); // shadowGenerator plot1.setShadowGenerator(new DefaultShadowGenerator(5, Color.gray, 0.6f, 4, -Math.PI / 4)); assertFalse(plot1.equals(plot2)); plot2.setShadowGenerator(new DefaultShadowGenerator(5, Color.gray, 0.6f, 4, -Math.PI / 4)); assertTrue(plot1.equals(plot2)); plot1.setShadowGenerator(null); assertFalse(plot1.equals(plot2)); plot2.setShadowGenerator(null); assertTrue(plot1.equals(plot2)); } /** * Confirm that basic cloning works. */ public void testCloning() { XYPlot p1 = new XYPlot(); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); } /** * Tests cloning for a more complex plot. */ public void testCloning2() { XYPlot p1 = new XYPlot(null, new NumberAxis("Domain Axis"), new NumberAxis("Range Axis"), new StandardXYItemRenderer()); p1.setRangeAxis(1, new NumberAxis("Range Axis 2")); List axisIndices = Arrays.asList(new Integer[] {new Integer(0), new Integer(1)}); p1.mapDatasetToDomainAxes(0, axisIndices); p1.mapDatasetToRangeAxes(0, axisIndices); p1.setRenderer(1, new XYBarRenderer()); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); } /** * Tests cloning for a plot where the fixed legend items have been * specified. */ public void testCloning3() { XYPlot p1 = new XYPlot(null, new NumberAxis("Domain Axis"), new NumberAxis("Range Axis"), new StandardXYItemRenderer()); LegendItemCollection c1 = new LegendItemCollection(); p1.setFixedLegendItems(c1); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); // verify independence of fixed legend item collection c1.add(new LegendItem("X")); assertFalse(p1.equals(p2)); } /** * Tests cloning to ensure that the cloned plot is registered as a listener * on the cloned renderer. */ public void testCloning4() { XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(); XYPlot p1 = new XYPlot(null, new NumberAxis("Domain Axis"), new NumberAxis("Range Axis"), r1); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); // verify that the plot is listening to the cloned renderer XYLineAndShapeRenderer r2 = (XYLineAndShapeRenderer) p2.getRenderer(); assertTrue(r2.hasListener(p2)); } /** * Confirm that cloning captures the quadrantOrigin field. */ public void testCloning_QuadrantOrigin() { XYPlot p1 = new XYPlot(); Point2D p = new Point2D.Double(1.2, 3.4); p1.setQuadrantOrigin(p); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); assertTrue(p2.getQuadrantOrigin() != p); } /** * Confirm that cloning captures the quadrantOrigin field. */ public void testCloning_QuadrantPaint() { XYPlot p1 = new XYPlot(); p1.setQuadrantPaint(3, new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); // check for independence p1.setQuadrantPaint(1, Color.red); assertFalse(p1.equals(p2)); p2.setQuadrantPaint(1, Color.red); assertTrue(p1.equals(p2)); } /** * Renderers that belong to the plot are being cloned but they are * retaining a reference to the original plot. */ public void testBug2817504() { XYPlot p1 = new XYPlot(); XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(); p1.setRenderer(r1); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); // check for independence XYLineAndShapeRenderer r2 = (XYLineAndShapeRenderer) p2.getRenderer(); assertTrue(r2.getPlot() == p2); } /** * Tests the independence of the clones. */ public void testCloneIndependence() { XYPlot p1 = new XYPlot(null, new NumberAxis("Domain Axis"), new NumberAxis("Range Axis"), new StandardXYItemRenderer()); p1.setDomainAxis(1, new NumberAxis("Domain Axis 2")); p1.setDomainAxisLocation(1, AxisLocation.BOTTOM_OR_LEFT); p1.setRangeAxis(1, new NumberAxis("Range Axis 2")); p1.setRangeAxisLocation(1, AxisLocation.TOP_OR_RIGHT); p1.setRenderer(1, new XYBarRenderer()); XYPlot p2 = null; try { p2 = (XYPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); System.err.println("Failed to clone."); } assertTrue(p1.equals(p2)); p1.getDomainAxis().setLabel("Label"); assertFalse(p1.equals(p2)); p2.getDomainAxis().setLabel("Label"); assertTrue(p1.equals(p2)); p1.getDomainAxis(1).setLabel("S1"); assertFalse(p1.equals(p2)); p2.getDomainAxis(1).setLabel("S1"); assertTrue(p1.equals(p2)); p1.setDomainAxisLocation(1, AxisLocation.TOP_OR_RIGHT); assertFalse(p1.equals(p2)); p2.setDomainAxisLocation(1, AxisLocation.TOP_OR_RIGHT); assertTrue(p1.equals(p2)); p1.mapDatasetToDomainAxis(2, 1); assertFalse(p1.equals(p2)); p2.mapDatasetToDomainAxis(2, 1); assertTrue(p1.equals(p2)); p1.getRangeAxis().setLabel("Label"); assertFalse(p1.equals(p2)); p2.getRangeAxis().setLabel("Label"); assertTrue(p1.equals(p2)); p1.getRangeAxis(1).setLabel("S1"); assertFalse(p1.equals(p2)); p2.getRangeAxis(1).setLabel("S1"); assertTrue(p1.equals(p2)); p1.setRangeAxisLocation(1, AxisLocation.TOP_OR_LEFT); assertFalse(p1.equals(p2)); p2.setRangeAxisLocation(1, AxisLocation.TOP_OR_LEFT); assertTrue(p1.equals(p2)); p1.mapDatasetToRangeAxis(2, 1); assertFalse(p1.equals(p2)); p2.mapDatasetToRangeAxis(2, 1); assertTrue(p1.equals(p2)); p1.getRenderer().setBaseOutlinePaint(Color.cyan); assertFalse(p1.equals(p2)); p2.getRenderer().setBaseOutlinePaint(Color.cyan); assertTrue(p1.equals(p2)); p1.getRenderer(1).setBaseOutlinePaint(Color.red); assertFalse(p1.equals(p2)); p2.getRenderer(1).setBaseOutlinePaint(Color.red); assertTrue(p1.equals(p2)); } /** * Setting a null renderer should be allowed, but is generating a null * pointer exception in 0.9.7. */ public void testSetNullRenderer() { boolean failed = false; try { XYPlot plot = new XYPlot(null, new NumberAxis("X"), new NumberAxis("Y"), null); plot.setRenderer(null); } catch (Exception e) { failed = true; } assertTrue(!failed); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization1() { XYDataset data = new XYSeriesCollection(); NumberAxis domainAxis = new NumberAxis("Domain"); NumberAxis rangeAxis = new NumberAxis("Range"); StandardXYItemRenderer renderer = new StandardXYItemRenderer(); XYPlot p1 = new XYPlot(data, domainAxis, rangeAxis, renderer); XYPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); p2 = (XYPlot) in.readObject(); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(p1, p2); } /** * Serialize an instance, restore it, and check for equality. This test * uses a {@link DateAxis} and a {@link StandardXYToolTipGenerator}. */ public void testSerialization2() { IntervalXYDataset data1 = createDataset1(); XYItemRenderer renderer1 = new XYBarRenderer(0.20); renderer1.setBaseToolTipGenerator( StandardXYToolTipGenerator.getTimeSeriesInstance()); XYPlot p1 = new XYPlot(data1, new DateAxis("Date"), null, renderer1); XYPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); p2 = (XYPlot) in.readObject(); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(p1, p2); } /** * Problem to reproduce a bug in serialization. The bug (first reported * against the {@link org.jfree.chart.plot.CategoryPlot} class) is a null * pointer exception that occurs when drawing a plot after deserialization. * It is caused by four temporary storage structures (axesAtTop, * axesAtBottom, axesAtLeft and axesAtRight - all initialized as empty * lists in the constructor) not being initialized by the readObject() * method following deserialization. This test has been written to * reproduce the bug (now fixed). */ public void testSerialization3() { XYSeriesCollection dataset = new XYSeriesCollection(); JFreeChart chart = ChartFactory.createXYLineChart("Test Chart", "Domain Axis", "Range Axis", dataset, true); JFreeChart chart2 = null; // serialize and deserialize the chart.... try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(chart); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); chart2 = (JFreeChart) in.readObject(); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(chart, chart2); boolean passed = true; try { chart2.createBufferedImage(300, 200); } catch (Exception e) { passed = false; e.printStackTrace(); } assertTrue(passed); } /** * A test to reproduce a bug in serialization: the domain and/or range * markers for a plot are not being serialized. */ public void testSerialization4() { XYSeriesCollection dataset = new XYSeriesCollection(); JFreeChart chart = ChartFactory.createXYLineChart("Test Chart", "Domain Axis", "Range Axis", dataset, true); XYPlot plot = (XYPlot) chart.getPlot(); plot.addDomainMarker(new ValueMarker(1.0), Layer.FOREGROUND); plot.addDomainMarker(new IntervalMarker(2.0, 3.0), Layer.BACKGROUND); plot.addRangeMarker(new ValueMarker(4.0), Layer.FOREGROUND); plot.addRangeMarker(new IntervalMarker(5.0, 6.0), Layer.BACKGROUND); JFreeChart chart2 = null; // serialize and deserialize the chart.... try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(chart); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); chart2 = (JFreeChart) in.readObject(); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(chart, chart2); boolean passed = true; try { chart2.createBufferedImage(300, 200); } catch (Exception e) { passed = false; e.printStackTrace(); } assertTrue(passed); } /** * Tests a bug where the plot is no longer registered as a listener * with the dataset(s) and axes after deserialization. See patch 1209475 * at SourceForge. */ public void testSerialization5() { XYSeriesCollection dataset1 = new XYSeriesCollection(); NumberAxis domainAxis1 = new NumberAxis("Domain 1"); NumberAxis rangeAxis1 = new NumberAxis("Range 1"); StandardXYItemRenderer renderer1 = new StandardXYItemRenderer(); XYPlot p1 = new XYPlot(dataset1, domainAxis1, rangeAxis1, renderer1); NumberAxis domainAxis2 = new NumberAxis("Domain 2"); NumberAxis rangeAxis2 = new NumberAxis("Range 2"); StandardXYItemRenderer renderer2 = new StandardXYItemRenderer(); XYSeriesCollection dataset2 = new XYSeriesCollection(); p1.setDataset(1, dataset2); p1.setDomainAxis(1, domainAxis2); p1.setRangeAxis(1, rangeAxis2); p1.setRenderer(1, renderer2); XYPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); p2 = (XYPlot) in.readObject(); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(p1, p2); // now check that all datasets, renderers and axes are being listened // too... NumberAxis domainAxisA = (NumberAxis) p2.getDomainAxis(0); NumberAxis rangeAxisA = (NumberAxis) p2.getRangeAxis(0); XYSeriesCollection datasetA = (XYSeriesCollection) p2.getDataset(0); StandardXYItemRenderer rendererA = (StandardXYItemRenderer) p2.getRenderer(0); NumberAxis domainAxisB = (NumberAxis) p2.getDomainAxis(1); NumberAxis rangeAxisB = (NumberAxis) p2.getRangeAxis(1); XYSeriesCollection datasetB = (XYSeriesCollection) p2.getDataset(1); StandardXYItemRenderer rendererB = (StandardXYItemRenderer) p2.getRenderer(1); assertTrue(datasetA.hasListener(p2)); assertTrue(domainAxisA.hasListener(p2)); assertTrue(rangeAxisA.hasListener(p2)); assertTrue(rendererA.hasListener(p2)); assertTrue(datasetB.hasListener(p2)); assertTrue(domainAxisB.hasListener(p2)); assertTrue(rangeAxisB.hasListener(p2)); assertTrue(rendererB.hasListener(p2)); } /** * Some checks for the getRendererForDataset() method. */ public void testGetRendererForDataset() { XYDataset d0 = new XYSeriesCollection(); XYDataset d1 = new XYSeriesCollection(); XYDataset d2 = new XYSeriesCollection(); XYDataset d3 = new XYSeriesCollection(); // not used by plot XYItemRenderer r0 = new XYLineAndShapeRenderer(); XYItemRenderer r2 = new XYLineAndShapeRenderer(); XYPlot plot = new XYPlot(); plot.setDataset(0, d0); plot.setDataset(1, d1); plot.setDataset(2, d2); plot.setRenderer(0, r0); // no renderer 1 plot.setRenderer(2, r2); assertEquals(r0, plot.getRendererForDataset(d0)); assertEquals(r0, plot.getRendererForDataset(d1)); assertEquals(r2, plot.getRendererForDataset(d2)); assertEquals(null, plot.getRendererForDataset(d3)); assertEquals(null, plot.getRendererForDataset(null)); } /** * Some checks for the getLegendItems() method. */ public void testGetLegendItems() { // check the case where there is a secondary dataset that doesn't // have a renderer (i.e. falls back to renderer 0) XYDataset d0 = createDataset1(); XYDataset d1 = createDataset2(); XYItemRenderer r0 = new XYLineAndShapeRenderer(); XYPlot plot = new XYPlot(); plot.setDataset(0, d0); plot.setDataset(1, d1); plot.setRenderer(0, r0); LegendItemCollection items = plot.getLegendItems(); assertEquals(2, items.getItemCount()); } /** * Creates a sample dataset. * * @return Series 1. */ private IntervalXYDataset createDataset1() { // create dataset 1... TimeSeries series1 = new TimeSeries("Series 1"); series1.add(new Day(1, MonthConstants.MARCH, 2002), 12353.3); series1.add(new Day(2, MonthConstants.MARCH, 2002), 13734.4); series1.add(new Day(3, MonthConstants.MARCH, 2002), 14525.3); series1.add(new Day(4, MonthConstants.MARCH, 2002), 13984.3); series1.add(new Day(5, MonthConstants.MARCH, 2002), 12999.4); series1.add(new Day(6, MonthConstants.MARCH, 2002), 14274.3); series1.add(new Day(7, MonthConstants.MARCH, 2002), 15943.5); series1.add(new Day(8, MonthConstants.MARCH, 2002), 14845.3); series1.add(new Day(9, MonthConstants.MARCH, 2002), 14645.4); series1.add(new Day(10, MonthConstants.MARCH, 2002), 16234.6); series1.add(new Day(11, MonthConstants.MARCH, 2002), 17232.3); series1.add(new Day(12, MonthConstants.MARCH, 2002), 14232.2); series1.add(new Day(13, MonthConstants.MARCH, 2002), 13102.2); series1.add(new Day(14, MonthConstants.MARCH, 2002), 14230.2); series1.add(new Day(15, MonthConstants.MARCH, 2002), 11235.2); TimeSeriesCollection collection = new TimeSeriesCollection(series1); return collection; } /** * Creates a sample dataset. * * @return A sample dataset. */ private XYDataset createDataset2() { // create dataset 1... XYSeries series = new XYSeries("Series 2"); XYSeriesCollection collection = new XYSeriesCollection(series); return collection; } /** * A test for a bug where setting the renderer doesn't register the plot * as a RendererChangeListener. */ public void testSetRenderer() { XYPlot plot = new XYPlot(); XYItemRenderer renderer = new XYLineAndShapeRenderer(); plot.setRenderer(renderer); // now make a change to the renderer and see if it triggers a plot // change event... MyPlotChangeListener listener = new MyPlotChangeListener(); plot.addChangeListener(listener); renderer.setSeriesPaint(0, Color.black); assertTrue(listener.getEvent() != null); } /** * Some checks for the removeAnnotation() method. */ public void testRemoveAnnotation() { XYPlot plot = new XYPlot(); XYTextAnnotation a1 = new XYTextAnnotation("X", 1.0, 2.0); XYTextAnnotation a2 = new XYTextAnnotation("X", 3.0, 4.0); XYTextAnnotation a3 = new XYTextAnnotation("X", 1.0, 2.0); plot.addAnnotation(a1); plot.addAnnotation(a2); plot.addAnnotation(a3); plot.removeAnnotation(a2); XYTextAnnotation x = (XYTextAnnotation) plot.getAnnotations().get(0); assertEquals(x, a1); // now remove a3, but since a3.equals(a1), this will in fact remove // a1... assertTrue(a1.equals(a3)); plot.removeAnnotation(a3); // actually removes a1 x = (XYTextAnnotation) plot.getAnnotations().get(0); assertEquals(x, a3); } /** * Some tests for the addDomainMarker() method(s). */ public void testAddDomainMarker() { XYPlot plot = new XYPlot(); Marker m = new ValueMarker(1.0); plot.addDomainMarker(m); List listeners = Arrays.asList(m.getListeners( MarkerChangeListener.class)); assertTrue(listeners.contains(plot)); plot.clearDomainMarkers(); listeners = Arrays.asList(m.getListeners(MarkerChangeListener.class)); assertFalse(listeners.contains(plot)); } /** * Some tests for the addRangeMarker() method(s). */ public void testAddRangeMarker() { XYPlot plot = new XYPlot(); Marker m = new ValueMarker(1.0); plot.addRangeMarker(m); List listeners = Arrays.asList(m.getListeners( MarkerChangeListener.class)); assertTrue(listeners.contains(plot)); plot.clearRangeMarkers(); listeners = Arrays.asList(m.getListeners(MarkerChangeListener.class)); assertFalse(listeners.contains(plot)); } /** * A test for bug 1654215 (where a renderer is added to the plot without * a corresponding dataset and it throws an exception at drawing time). */ public void test1654215() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("Title", "X", "Y", dataset, true); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRenderer(1, new XYLineAndShapeRenderer()); boolean success = false; try { BufferedImage image = new BufferedImage(200 , 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null); g2.dispose(); success = true; } catch (Exception e) { e.printStackTrace(); success = false; } assertTrue(success); } /** * A test for drawing range grid lines when there is no primary renderer. * In 1.0.4, this is throwing a NullPointerException. */ public void testDrawRangeGridlines() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("Title", "X", "Y", dataset, true); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRenderer(null); boolean success = false; try { BufferedImage image = new BufferedImage(200 , 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null); g2.dispose(); success = true; } catch (Exception e) { e.printStackTrace(); success = false; } assertTrue(success); } /** * A test for drawing a plot where a series has zero items. With * JFreeChart 1.0.5+cvs this was throwing an exception at one point. */ public void testDrawSeriesWithZeroItems() { DefaultXYDataset dataset = new DefaultXYDataset(); dataset.addSeries("Series 1", new double[][] {{1.0, 2.0}, {3.0, 4.0}}); dataset.addSeries("Series 2", new double[][] {{}, {}}); JFreeChart chart = ChartFactory.createXYLineChart("Title", "X", "Y", dataset, true); boolean success = false; try { BufferedImage image = new BufferedImage(200 , 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null); g2.dispose(); success = true; } catch (Exception e) { e.printStackTrace(); success = false; } assertTrue(success); } /** * Check that removing a marker that isn't assigned to the plot returns * false. */ public void testRemoveDomainMarker() { XYPlot plot = new XYPlot(); assertFalse(plot.removeDomainMarker(new ValueMarker(0.5))); } /** * Check that removing a marker that isn't assigned to the plot returns * false. */ public void testRemoveRangeMarker() { XYPlot plot = new XYPlot(); assertFalse(plot.removeRangeMarker(new ValueMarker(0.5))); } /** * Some tests for the getDomainAxisForDataset() method. */ public void testGetDomainAxisForDataset() { XYDataset dataset = new XYSeriesCollection(); NumberAxis xAxis = new NumberAxis("X"); NumberAxis yAxis = new NumberAxis("Y"); XYItemRenderer renderer = new DefaultXYItemRenderer(); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); assertEquals(xAxis, plot.getDomainAxisForDataset(0)); // should get IllegalArgumentException for negative index boolean pass = false; try { plot.getDomainAxisForDataset(-1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // should get IllegalArgumentException for index too high pass = false; try { plot.getDomainAxisForDataset(1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // if multiple axes are mapped, the first in the list should be // returned... NumberAxis xAxis2 = new NumberAxis("X2"); plot.setDomainAxis(1, xAxis2); assertEquals(xAxis, plot.getDomainAxisForDataset(0)); plot.mapDatasetToDomainAxis(0, 1); assertEquals(xAxis2, plot.getDomainAxisForDataset(0)); List axisIndices = Arrays.asList(new Integer[] {new Integer(0), new Integer(1)}); plot.mapDatasetToDomainAxes(0, axisIndices); assertEquals(xAxis, plot.getDomainAxisForDataset(0)); axisIndices = Arrays.asList(new Integer[] {new Integer(1), new Integer(2)}); plot.mapDatasetToDomainAxes(0, axisIndices); assertEquals(xAxis2, plot.getDomainAxisForDataset(0)); } /** * Some tests for the getRangeAxisForDataset() method. */ public void testGetRangeAxisForDataset() { XYDataset dataset = new XYSeriesCollection(); NumberAxis xAxis = new NumberAxis("X"); NumberAxis yAxis = new NumberAxis("Y"); XYItemRenderer renderer = new DefaultXYItemRenderer(); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); assertEquals(yAxis, plot.getRangeAxisForDataset(0)); // should get IllegalArgumentException for negative index boolean pass = false; try { plot.getRangeAxisForDataset(-1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // should get IllegalArgumentException for index too high pass = false; try { plot.getRangeAxisForDataset(1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // if multiple axes are mapped, the first in the list should be // returned... NumberAxis yAxis2 = new NumberAxis("Y2"); plot.setRangeAxis(1, yAxis2); assertEquals(yAxis, plot.getRangeAxisForDataset(0)); plot.mapDatasetToRangeAxis(0, 1); assertEquals(yAxis2, plot.getRangeAxisForDataset(0)); List axisIndices = Arrays.asList(new Integer[] {new Integer(0), new Integer(1)}); plot.mapDatasetToRangeAxes(0, axisIndices); assertEquals(yAxis, plot.getRangeAxisForDataset(0)); axisIndices = Arrays.asList(new Integer[] {new Integer(1), new Integer(2)}); plot.mapDatasetToRangeAxes(0, axisIndices); assertEquals(yAxis2, plot.getRangeAxisForDataset(0)); } }
[ { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "checkAxisIndices", "be_test_function_signature": "(Ljava/util/List;)V", "line_numbers": [ "1559", "1560", "1562", "1563", "1564", "1566", "1567", "1568", "1569", "1570", "1573", "1574", "1576", "1578" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "configureDomainAxes", "be_test_function_signature": "()V", "line_numbers": [ "986", "987", "988", "989", "992" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "configureRangeAxes", "be_test_function_signature": "()V", "line_numbers": [ "1286", "1287", "1288", "1289", "1292" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "datasetChanged", "be_test_function_signature": "(Lorg/jfree/data/event/DatasetChangeEvent;)V", "line_numbers": [ "4649", "4650", "4651", "4652", "4655", "4656", "4657", "4659" ], "method_line_rate": 0.875 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "equals", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "5430", "5431", "5433", "5434", "5436", "5437", "5438", "5440", "5441", "5443", "5444", "5446", "5447", "5449", "5451", "5453", "5454", "5456", "5457", "5459", "5461", "5463", "5465", "5467", "5468", "5470", "5471", "5473", "5474", "5476", "5477", "5479", "5481", "5483", "5484", "5486", "5487", "5489", "5490", "5492", "5493", "5495", "5496", "5498", "5499", "5501", "5503", "5505", "5507", "5509", "5511", "5513", "5515", "5517", "5519", "5521", "5523", "5525", "5527", "5529", "5531", "5533", "5535", "5537", "5539", "5541", "5543", "5545", "5547", "5549", "5551", "5553", "5555", "5557", "5559", "5561", "5563", "5565", "5567", "5569", "5571", "5573", "5575", "5577", "5579", "5581", "5583", "5585", "5587", "5589", "5591", "5593", "5595", "5597", "5599", "5601", "5603", "5605", "5606", "5608", "5610", "5612", "5614", "5616", "5618", "5620", "5621", "5623", "5624", "5626", "5629", "5631", "5633" ], "method_line_rate": 0.5309734513274337 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDataRange", "be_test_function_signature": "(Lorg/jfree/chart/axis/ValueAxis;)Lorg/jfree/data/Range;", "line_numbers": [ "4527", "4528", "4529", "4530", "4533", "4534", "4535", "4536", "4538", "4540", "4541", "4542", "4543", "4544", "4546", "4551", "4552", "4553", "4554", "4556", "4557", "4558", "4559", "4560", "4561", "4563", "4569", "4570", "4571", "4572", "4573", "4574", "4575", "4576", "4579", "4584", "4585", "4588", "4593", "4594", "4595", "4596", "4597", "4598", "4599", "4601", "4604", "4606", "4607", "4608", "4609", "4610", "4611", "4614", "4617", "4619" ], "method_line_rate": 0.6428571428571429 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDataset", "be_test_function_signature": "(I)Lorg/jfree/data/xy/XYDataset;", "line_numbers": [ "1399", "1400", "1401", "1403" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDatasetCount", "be_test_function_signature": "()I", "line_numbers": [ "1450" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDatasetsMappedToDomainAxis", "be_test_function_signature": "(Ljava/lang/Integer;)Ljava/util/List;", "line_numbers": [ "4423", "4424", "4426", "4427", "4428", "4430", "4431", "4432", "4436", "4437", "4441" ], "method_line_rate": 0.9090909090909091 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDatasetsMappedToRangeAxis", "be_test_function_signature": "(Ljava/lang/Integer;)Ljava/util/List;", "line_numbers": [ "4453", "4454", "4456", "4457", "4458", "4460", "4461", "4462", "4466", "4467", "4471" ], "method_line_rate": 0.9090909090909091 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDomainAxis", "be_test_function_signature": "(I)Lorg/jfree/chart/axis/ValueAxis;", "line_numbers": [ "818", "819", "820", "822", "823", "824", "825", "826", "829" ], "method_line_rate": 0.7777777777777778 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDomainAxisForDataset", "be_test_function_signature": "(I)Lorg/jfree/chart/axis/ValueAxis;", "line_numbers": [ "3909", "3910", "3911", "3914", "3915", "3917", "3919", "3920", "3921", "3923", "3925" ], "method_line_rate": 0.9090909090909091 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDomainAxisIndex", "be_test_function_signature": "(Lorg/jfree/chart/axis/ValueAxis;)I", "line_numbers": [ "4484", "4485", "4487", "4488", "4489", "4490", "4493" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getIndexOf", "be_test_function_signature": "(Lorg/jfree/chart/renderer/xy/XYItemRenderer;)I", "line_numbers": [ "1754" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRangeAxis", "be_test_function_signature": "(I)Lorg/jfree/chart/axis/ValueAxis;", "line_numbers": [ "1182", "1183", "1184", "1186", "1187", "1188", "1189", "1190", "1193" ], "method_line_rate": 0.7777777777777778 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRangeAxisIndex", "be_test_function_signature": "(Lorg/jfree/chart/axis/ValueAxis;)I", "line_numbers": [ "4506", "4507", "4509", "4510", "4511", "4512", "4515" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRenderer", "be_test_function_signature": "()Lorg/jfree/chart/renderer/xy/XYItemRenderer;", "line_numbers": [ "1599" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRenderer", "be_test_function_signature": "(I)Lorg/jfree/chart/renderer/xy/XYItemRenderer;", "line_numbers": [ "1612", "1613", "1614", "1616" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRendererCount", "be_test_function_signature": "()I", "line_numbers": [ "1588" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRendererForDataset", "be_test_function_signature": "(Lorg/jfree/data/xy/XYDataset;)Lorg/jfree/chart/renderer/xy/XYItemRenderer;", "line_numbers": [ "1767", "1768", "1769", "1770", "1771", "1772", "1777" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "mapDatasetToDomainAxes", "be_test_function_signature": "(ILjava/util/List;)V", "line_numbers": [ "1498", "1499", "1501", "1502", "1503", "1505", "1508" ], "method_line_rate": 0.8571428571428571 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "mapDatasetToDomainAxis", "be_test_function_signature": "(II)V", "line_numbers": [ "1482", "1483", "1484", "1485" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "mapDatasetToRangeAxes", "be_test_function_signature": "(ILjava/util/List;)V", "line_numbers": [ "1536", "1537", "1539", "1540", "1541", "1543", "1546" ], "method_line_rate": 0.8571428571428571 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "mapDatasetToRangeAxis", "be_test_function_signature": "(II)V", "line_numbers": [ "1520", "1521", "1522", "1523" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "readObject", "be_test_function_signature": "(Ljava/io/ObjectInputStream;)V", "line_numbers": [ "5770", "5771", "5772", "5773", "5774", "5775", "5776", "5777", "5778", "5779", "5780", "5781", "5782", "5783", "5784", "5785", "5786", "5787", "5788", "5789", "5790", "5793", "5794", "5798", "5799", "5800", "5801", "5802", "5803", "5806", "5807", "5808", "5809", "5810", "5811", "5814", "5815", "5816", "5817", "5818", "5821", "5822", "5823", "5824", "5825", "5829" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setDataset", "be_test_function_signature": "(ILorg/jfree/data/xy/XYDataset;)V", "line_numbers": [ "1428", "1429", "1430", "1432", "1433", "1434", "1438", "1441", "1442" ], "method_line_rate": 0.8888888888888888 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setDomainAxis", "be_test_function_signature": "(ILorg/jfree/chart/axis/ValueAxis;)V", "line_numbers": [ "856", "857" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setDomainAxis", "be_test_function_signature": "(ILorg/jfree/chart/axis/ValueAxis;Z)V", "line_numbers": [ "870", "871", "872", "874", "875", "877", "878", "879", "880", "882", "883", "885" ], "method_line_rate": 0.9166666666666666 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRangeAxis", "be_test_function_signature": "(ILorg/jfree/chart/axis/ValueAxis;)V", "line_numbers": [ "1206", "1207" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRangeAxis", "be_test_function_signature": "(ILorg/jfree/chart/axis/ValueAxis;Z)V", "line_numbers": [ "1220", "1221", "1222", "1224", "1225", "1227", "1228", "1229", "1230", "1232", "1233", "1235" ], "method_line_rate": 0.9166666666666666 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRenderer", "be_test_function_signature": "(ILorg/jfree/chart/renderer/xy/XYItemRenderer;)V", "line_numbers": [ "1643", "1644" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRenderer", "be_test_function_signature": "(ILorg/jfree/chart/renderer/xy/XYItemRenderer;Z)V", "line_numbers": [ "1658", "1659", "1660", "1662", "1663", "1664", "1665", "1667", "1668", "1669", "1670", "1672" ], "method_line_rate": 0.9166666666666666 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "writeObject", "be_test_function_signature": "(Ljava/io/ObjectOutputStream;)V", "line_numbers": [ "5734", "5735", "5736", "5737", "5738", "5739", "5740", "5741", "5742", "5743", "5744", "5745", "5746", "5747", "5748", "5749", "5750", "5751", "5752", "5753", "5755", "5756", "5757" ], "method_line_rate": 1 } ]
public class SkippingIteratorTest<E> extends AbstractIteratorTest<E>
@Test public void testRemoveWithoutCallingNext() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new SkippingIterator<E>(testListCopy.iterator(), 1); try { iter.remove(); fail("Expected IllegalStateException."); } catch (IllegalStateException ise) { /* Success case */ } }
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // // // // public class SkippingIterator<E> extends AbstractIteratorDecorator<E> { // private final long offset; // private long pos; // // public SkippingIterator(final Iterator<E> iterator, final long offset); // private void init(); // @Override // public E next(); // @Override // public void remove(); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.iterators; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.Iterator; // import java.util.List; // import java.util.NoSuchElementException; // import org.junit.Test; // // // // public class SkippingIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public SkippingIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testSkipping(); // @Test // public void testSameAsDecorated(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testNegativeOffset(); // @Test // public void testRemoveWithoutCallingNext(); // @Test // public void testRemoveCalledTwice(); // @Test // public void testRemoveFirst(); // @Test // public void testRemoveMiddle(); // @Test // public void testRemoveLast(); // @Test // public void testRemoveUnsupported(); // @Override // public void remove(); // } // You are a professional Java test case writer, please create a test case named `testRemoveWithoutCallingNext` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the <code>remove()</code> method being called without * <code>next()</code> being called first. */
src/test/java/org/apache/commons/collections4/iterators/SkippingIteratorTest.java
package org.apache.commons.collections4.iterators; import java.util.Iterator;
public SkippingIterator(final Iterator<E> iterator, final long offset); private void init(); @Override public E next(); @Override public void remove();
165
testRemoveWithoutCallingNext
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; public class SkippingIterator<E> extends AbstractIteratorDecorator<E> { private final long offset; private long pos; public SkippingIterator(final Iterator<E> iterator, final long offset); private void init(); @Override public E next(); @Override public void remove(); } // Abstract Java Test Class package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; public class SkippingIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public SkippingIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testSkipping(); @Test public void testSameAsDecorated(); @Test public void testOffsetGreaterThanSize(); @Test public void testNegativeOffset(); @Test public void testRemoveWithoutCallingNext(); @Test public void testRemoveCalledTwice(); @Test public void testRemoveFirst(); @Test public void testRemoveMiddle(); @Test public void testRemoveLast(); @Test public void testRemoveUnsupported(); @Override public void remove(); } ``` You are a professional Java test case writer, please create a test case named `testRemoveWithoutCallingNext` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the <code>remove()</code> method being called without * <code>next()</code> being called first. */
155
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // // // // public class SkippingIterator<E> extends AbstractIteratorDecorator<E> { // private final long offset; // private long pos; // // public SkippingIterator(final Iterator<E> iterator, final long offset); // private void init(); // @Override // public E next(); // @Override // public void remove(); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.iterators; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.Iterator; // import java.util.List; // import java.util.NoSuchElementException; // import org.junit.Test; // // // // public class SkippingIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public SkippingIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testSkipping(); // @Test // public void testSameAsDecorated(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testNegativeOffset(); // @Test // public void testRemoveWithoutCallingNext(); // @Test // public void testRemoveCalledTwice(); // @Test // public void testRemoveFirst(); // @Test // public void testRemoveMiddle(); // @Test // public void testRemoveLast(); // @Test // public void testRemoveUnsupported(); // @Override // public void remove(); // } // You are a professional Java test case writer, please create a test case named `testRemoveWithoutCallingNext` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the <code>remove()</code> method being called without * <code>next()</code> being called first. */ @Test public void testRemoveWithoutCallingNext() {
/** * Test the <code>remove()</code> method being called without * <code>next()</code> being called first. */
28
org.apache.commons.collections4.iterators.SkippingIterator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; public class SkippingIterator<E> extends AbstractIteratorDecorator<E> { private final long offset; private long pos; public SkippingIterator(final Iterator<E> iterator, final long offset); private void init(); @Override public E next(); @Override public void remove(); } // Abstract Java Test Class package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; public class SkippingIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public SkippingIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testSkipping(); @Test public void testSameAsDecorated(); @Test public void testOffsetGreaterThanSize(); @Test public void testNegativeOffset(); @Test public void testRemoveWithoutCallingNext(); @Test public void testRemoveCalledTwice(); @Test public void testRemoveFirst(); @Test public void testRemoveMiddle(); @Test public void testRemoveLast(); @Test public void testRemoveUnsupported(); @Override public void remove(); } ``` You are a professional Java test case writer, please create a test case named `testRemoveWithoutCallingNext` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the <code>remove()</code> method being called without * <code>next()</code> being called first. */ @Test public void testRemoveWithoutCallingNext() { ```
public class SkippingIterator<E> extends AbstractIteratorDecorator<E>
package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test;
public SkippingIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testSkipping(); @Test public void testSameAsDecorated(); @Test public void testOffsetGreaterThanSize(); @Test public void testNegativeOffset(); @Test public void testRemoveWithoutCallingNext(); @Test public void testRemoveCalledTwice(); @Test public void testRemoveFirst(); @Test public void testRemoveMiddle(); @Test public void testRemoveLast(); @Test public void testRemoveUnsupported(); @Override public void remove();
cd77aae2eddfd9a0330a334e4cf52479dc26580112ecd50147c2fd946f37bd99
[ "org.apache.commons.collections4.iterators.SkippingIteratorTest::testRemoveWithoutCallingNext" ]
private final long offset; private long pos;
@Test public void testRemoveWithoutCallingNext()
private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList;
Collections
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; /** * A unit test to test the basic functions of {@link SkippingIterator}. * * @version $Id$ */ public class SkippingIteratorTest<E> extends AbstractIteratorTest<E> { /** Test array of size 7 */ private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public SkippingIteratorTest(final String testName) { super(testName); } @SuppressWarnings("unchecked") @Override public void setUp() throws Exception { super.setUp(); testList = Arrays.asList((E[]) testArray); } @Override public Iterator<E> makeEmptyIterator() { return new SkippingIterator<E>(Collections.<E>emptyList().iterator(), 0); } @Override public Iterator<E> makeObject() { return new SkippingIterator<E>(new ArrayList<E>(testList).iterator(), 1); } // ---------------- Tests --------------------- /** * Test a decorated iterator bounded such that the first element returned is * at an index greater its first element, and the last element returned is * at an index less than its last element. */ @Test public void testSkipping() { Iterator<E> iter = new SkippingIterator<E>(testList.iterator(), 2); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); assertTrue(iter.hasNext()); assertEquals("d", iter.next()); assertTrue(iter.hasNext()); assertEquals("e", iter.next()); assertTrue(iter.hasNext()); assertEquals("f", iter.next()); assertTrue(iter.hasNext()); assertEquals("g", iter.next()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test a decorated iterator bounded such that the <code>offset</code> is * zero, in that the SkippingIterator should return all the same elements * as its decorated iterator. */ @Test public void testSameAsDecorated() { Iterator<E> iter = new SkippingIterator<E>(testList.iterator(), 0); assertTrue(iter.hasNext()); assertEquals("a", iter.next()); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); assertTrue(iter.hasNext()); assertEquals("d", iter.next()); assertTrue(iter.hasNext()); assertEquals("e", iter.next()); assertTrue(iter.hasNext()); assertEquals("f", iter.next()); assertTrue(iter.hasNext()); assertEquals("g", iter.next()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The SkippingIterator should * behave as if there are no more elements to return. */ @Test public void testOffsetGreaterThanSize() { Iterator<E> iter = new SkippingIterator<E>(testList.iterator(), 10); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test the case if a negative <code>offset</code> is passed to the * constructor. {@link IllegalArgumentException} is expected. */ @Test public void testNegativeOffset() { try { new SkippingIterator<E>(testList.iterator(), -1); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException iae) { /* Success case */ } } /** * Test the <code>remove()</code> method being called without * <code>next()</code> being called first. */ @Test public void testRemoveWithoutCallingNext() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new SkippingIterator<E>(testListCopy.iterator(), 1); try { iter.remove(); fail("Expected IllegalStateException."); } catch (IllegalStateException ise) { /* Success case */ } } /** * Test the <code>remove()</code> method being called twice without calling * <code>next()</code> in between. */ @Test public void testRemoveCalledTwice() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new SkippingIterator<E>(testListCopy.iterator(), 1); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); iter.remove(); try { iter.remove(); fail("Expected IllegalStateException."); } catch (IllegalStateException ise) { /* Success case */ } } /** * Test removing the first element. Verify that the element is removed from * the underlying collection. */ @Test public void testRemoveFirst() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new SkippingIterator<E>(testListCopy.iterator(), 4); assertTrue(iter.hasNext()); assertEquals("e", iter.next()); iter.remove(); assertFalse(testListCopy.contains("e")); assertTrue(iter.hasNext()); assertEquals("f", iter.next()); assertTrue(iter.hasNext()); assertEquals("g", iter.next()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */ @Test public void testRemoveMiddle() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new SkippingIterator<E>(testListCopy.iterator(), 3); assertTrue(iter.hasNext()); assertEquals("d", iter.next()); iter.remove(); assertFalse(testListCopy.contains("d")); assertTrue(iter.hasNext()); assertEquals("e", iter.next()); assertTrue(iter.hasNext()); assertEquals("f", iter.next()); assertTrue(iter.hasNext()); assertEquals("g", iter.next()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test removing the last element. Verify that the element is removed from * the underlying collection. */ @Test public void testRemoveLast() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new SkippingIterator<E>(testListCopy.iterator(), 5); assertTrue(iter.hasNext()); assertEquals("f", iter.next()); assertTrue(iter.hasNext()); assertEquals("g", iter.next()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } iter.remove(); assertFalse(testListCopy.contains("g")); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test the case if the decorated iterator does not support the * <code>remove()</code> method and throws an {@link UnsupportedOperationException}. */ @Test public void testRemoveUnsupported() { Iterator<E> mockIterator = new AbstractIteratorDecorator<E>(testList.iterator()) { @Override public void remove() { throw new UnsupportedOperationException(); } }; Iterator<E> iter = new SkippingIterator<E>(mockIterator, 1); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); try { iter.remove(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException usoe) { /* Success case */ } } }
[ { "be_test_class_file": "org/apache/commons/collections4/iterators/SkippingIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.SkippingIterator", "be_test_function_name": "init", "be_test_function_signature": "()V", "line_numbers": [ "66", "67", "69" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/SkippingIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.SkippingIterator", "be_test_function_name": "next", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "75", "76", "77" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/SkippingIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.SkippingIterator", "be_test_function_name": "remove", "be_test_function_signature": "()V", "line_numbers": [ "90", "91", "93", "94" ], "method_line_rate": 0.5 } ]
public class FastDatePrinterTest
@Test public void testSimpleDate() { final Calendar cal = Calendar.getInstance(); final DatePrinter format = getInstance(YYYY_MM_DD); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); }
// private String applyRulesToString(final Calendar c); // private GregorianCalendar newCalendar(); // @Override // public String format(final Date date); // @Override // public String format(final Calendar calendar); // @Override // public StringBuffer format(final long millis, final StringBuffer buf); // @Override // public StringBuffer format(final Date date, final StringBuffer buf); // @Override // public StringBuffer format(final Calendar calendar, final StringBuffer buf); // protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf); // @Override // public String getPattern(); // @Override // public TimeZone getTimeZone(); // @Override // public Locale getLocale(); // public int getMaxLengthEstimate(); // @Override // public boolean equals(final Object obj); // @Override // public int hashCode(); // @Override // public String toString(); // private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException; // static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale); // CharacterLiteral(final char value); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // StringLiteral(final String value); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // TextField(final int field, final String[] values); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // UnpaddedNumberField(final int field); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // UnpaddedMonthField(); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // PaddedNumberField(final int field, final int size); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwoDigitNumberField(final int field); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwoDigitYearField(); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwoDigitMonthField(); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwelveHourField(final NumberRule rule); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public void appendTo(final StringBuffer buffer, final int value); // TwentyFourHourField(final NumberRule rule); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public void appendTo(final StringBuffer buffer, final int value); // TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // TimeZoneNumberRule(final boolean colon); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // TimeZoneDisplayKey(final TimeZone timeZone, // final boolean daylight, int style, final Locale locale); // @Override // public int hashCode(); // @Override // public boolean equals(final Object obj); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.time; // // import static org.junit.Assert.assertNotNull; // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertTrue; // import java.io.Serializable; // 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.commons.lang3.SerializationUtils; // import org.junit.Test; // // // // public class FastDatePrinterTest { // private static final String YYYY_MM_DD = "yyyy/MM/dd"; // private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); // private static final Locale SWEDEN = new Locale("sv", "SE"); // // DatePrinter getInstance(final String format); // private DatePrinter getDateInstance(final int dateStyle, final Locale locale); // private DatePrinter getInstance(final String format, final Locale locale); // private DatePrinter getInstance(final String format, final TimeZone timeZone); // protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale); // @Test // public void testFormat(); // @Test // public void testShortDateStyleWithLocales(); // @Test // public void testLowYearPadding(); // @Test // public void testMilleniumBug(); // @Test // public void testSimpleDate(); // @Test // public void testLang303(); // @Test // public void testLang538(); // @Test // public void testLang645(); // @Test // public void testEquals(); // @Test // public void testToStringContainsName(); // @Test // public void testPatternMatches(); // @Test // public void testLocaleMatches(); // @Test // public void testTimeZoneMatches(); // @Test // public void testCalendarTimezoneRespected(); // } // You are a professional Java test case writer, please create a test case named `testSimpleDate` for the `FastDatePrinter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */
src/test/java/org/apache/commons/lang3/time/FastDatePrinterTest.java
package org.apache.commons.lang3.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.FieldPosition; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.lang3.Validate;
protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale); private void init(); protected List<Rule> parsePattern(); protected String parseToken(final String pattern, final int[] indexRef); protected NumberRule selectNumberRule(final int field, final int padding); @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); @Override public String format(final long millis); private String applyRulesToString(final Calendar c); private GregorianCalendar newCalendar(); @Override public String format(final Date date); @Override public String format(final Calendar calendar); @Override public StringBuffer format(final long millis, final StringBuffer buf); @Override public StringBuffer format(final Date date, final StringBuffer buf); @Override public StringBuffer format(final Calendar calendar, final StringBuffer buf); protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf); @Override public String getPattern(); @Override public TimeZone getTimeZone(); @Override public Locale getLocale(); public int getMaxLengthEstimate(); @Override public boolean equals(final Object obj); @Override public int hashCode(); @Override public String toString(); private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException; static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale); CharacterLiteral(final char value); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); StringLiteral(final String value); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TextField(final int field, final String[] values); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); UnpaddedNumberField(final int field); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); UnpaddedMonthField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); PaddedNumberField(final int field, final int size); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitNumberField(final int field); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitYearField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitMonthField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwelveHourField(final NumberRule rule); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public void appendTo(final StringBuffer buffer, final int value); TwentyFourHourField(final NumberRule rule); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public void appendTo(final StringBuffer buffer, final int value); TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TimeZoneNumberRule(final boolean colon); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TimeZoneDisplayKey(final TimeZone timeZone, final boolean daylight, int style, final Locale locale); @Override public int hashCode(); @Override public boolean equals(final Object obj);
189
testSimpleDate
```java private String applyRulesToString(final Calendar c); private GregorianCalendar newCalendar(); @Override public String format(final Date date); @Override public String format(final Calendar calendar); @Override public StringBuffer format(final long millis, final StringBuffer buf); @Override public StringBuffer format(final Date date, final StringBuffer buf); @Override public StringBuffer format(final Calendar calendar, final StringBuffer buf); protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf); @Override public String getPattern(); @Override public TimeZone getTimeZone(); @Override public Locale getLocale(); public int getMaxLengthEstimate(); @Override public boolean equals(final Object obj); @Override public int hashCode(); @Override public String toString(); private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException; static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale); CharacterLiteral(final char value); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); StringLiteral(final String value); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TextField(final int field, final String[] values); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); UnpaddedNumberField(final int field); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); UnpaddedMonthField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); PaddedNumberField(final int field, final int size); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitNumberField(final int field); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitYearField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitMonthField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwelveHourField(final NumberRule rule); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public void appendTo(final StringBuffer buffer, final int value); TwentyFourHourField(final NumberRule rule); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public void appendTo(final StringBuffer buffer, final int value); TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TimeZoneNumberRule(final boolean colon); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TimeZoneDisplayKey(final TimeZone timeZone, final boolean daylight, int style, final Locale locale); @Override public int hashCode(); @Override public boolean equals(final Object obj); } // Abstract Java Test Class package org.apache.commons.lang3.time; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.Serializable; 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.commons.lang3.SerializationUtils; import org.junit.Test; public class FastDatePrinterTest { private static final String YYYY_MM_DD = "yyyy/MM/dd"; private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); private static final Locale SWEDEN = new Locale("sv", "SE"); DatePrinter getInstance(final String format); private DatePrinter getDateInstance(final int dateStyle, final Locale locale); private DatePrinter getInstance(final String format, final Locale locale); private DatePrinter getInstance(final String format, final TimeZone timeZone); protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale); @Test public void testFormat(); @Test public void testShortDateStyleWithLocales(); @Test public void testLowYearPadding(); @Test public void testMilleniumBug(); @Test public void testSimpleDate(); @Test public void testLang303(); @Test public void testLang538(); @Test public void testLang645(); @Test public void testEquals(); @Test public void testToStringContainsName(); @Test public void testPatternMatches(); @Test public void testLocaleMatches(); @Test public void testTimeZoneMatches(); @Test public void testCalendarTimezoneRespected(); } ``` You are a professional Java test case writer, please create a test case named `testSimpleDate` for the `FastDatePrinter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */
178
// private String applyRulesToString(final Calendar c); // private GregorianCalendar newCalendar(); // @Override // public String format(final Date date); // @Override // public String format(final Calendar calendar); // @Override // public StringBuffer format(final long millis, final StringBuffer buf); // @Override // public StringBuffer format(final Date date, final StringBuffer buf); // @Override // public StringBuffer format(final Calendar calendar, final StringBuffer buf); // protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf); // @Override // public String getPattern(); // @Override // public TimeZone getTimeZone(); // @Override // public Locale getLocale(); // public int getMaxLengthEstimate(); // @Override // public boolean equals(final Object obj); // @Override // public int hashCode(); // @Override // public String toString(); // private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException; // static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale); // CharacterLiteral(final char value); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // StringLiteral(final String value); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // TextField(final int field, final String[] values); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // UnpaddedNumberField(final int field); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // UnpaddedMonthField(); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // PaddedNumberField(final int field, final int size); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwoDigitNumberField(final int field); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwoDigitYearField(); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwoDigitMonthField(); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public final void appendTo(final StringBuffer buffer, final int value); // TwelveHourField(final NumberRule rule); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public void appendTo(final StringBuffer buffer, final int value); // TwentyFourHourField(final NumberRule rule); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // @Override // public void appendTo(final StringBuffer buffer, final int value); // TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // TimeZoneNumberRule(final boolean colon); // @Override // public int estimateLength(); // @Override // public void appendTo(final StringBuffer buffer, final Calendar calendar); // TimeZoneDisplayKey(final TimeZone timeZone, // final boolean daylight, int style, final Locale locale); // @Override // public int hashCode(); // @Override // public boolean equals(final Object obj); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.time; // // import static org.junit.Assert.assertNotNull; // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertTrue; // import java.io.Serializable; // 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.commons.lang3.SerializationUtils; // import org.junit.Test; // // // // public class FastDatePrinterTest { // private static final String YYYY_MM_DD = "yyyy/MM/dd"; // private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); // private static final Locale SWEDEN = new Locale("sv", "SE"); // // DatePrinter getInstance(final String format); // private DatePrinter getDateInstance(final int dateStyle, final Locale locale); // private DatePrinter getInstance(final String format, final Locale locale); // private DatePrinter getInstance(final String format, final TimeZone timeZone); // protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale); // @Test // public void testFormat(); // @Test // public void testShortDateStyleWithLocales(); // @Test // public void testLowYearPadding(); // @Test // public void testMilleniumBug(); // @Test // public void testSimpleDate(); // @Test // public void testLang303(); // @Test // public void testLang538(); // @Test // public void testLang645(); // @Test // public void testEquals(); // @Test // public void testToStringContainsName(); // @Test // public void testPatternMatches(); // @Test // public void testLocaleMatches(); // @Test // public void testTimeZoneMatches(); // @Test // public void testCalendarTimezoneRespected(); // } // You are a professional Java test case writer, please create a test case named `testSimpleDate` for the `FastDatePrinter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ @Test public void testSimpleDate() {
/** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */
1
org.apache.commons.lang3.time.FastDatePrinter
src/test/java
```java private String applyRulesToString(final Calendar c); private GregorianCalendar newCalendar(); @Override public String format(final Date date); @Override public String format(final Calendar calendar); @Override public StringBuffer format(final long millis, final StringBuffer buf); @Override public StringBuffer format(final Date date, final StringBuffer buf); @Override public StringBuffer format(final Calendar calendar, final StringBuffer buf); protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf); @Override public String getPattern(); @Override public TimeZone getTimeZone(); @Override public Locale getLocale(); public int getMaxLengthEstimate(); @Override public boolean equals(final Object obj); @Override public int hashCode(); @Override public String toString(); private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException; static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale); CharacterLiteral(final char value); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); StringLiteral(final String value); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TextField(final int field, final String[] values); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); UnpaddedNumberField(final int field); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); UnpaddedMonthField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); PaddedNumberField(final int field, final int size); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitNumberField(final int field); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitYearField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwoDigitMonthField(); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public final void appendTo(final StringBuffer buffer, final int value); TwelveHourField(final NumberRule rule); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public void appendTo(final StringBuffer buffer, final int value); TwentyFourHourField(final NumberRule rule); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); @Override public void appendTo(final StringBuffer buffer, final int value); TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TimeZoneNumberRule(final boolean colon); @Override public int estimateLength(); @Override public void appendTo(final StringBuffer buffer, final Calendar calendar); TimeZoneDisplayKey(final TimeZone timeZone, final boolean daylight, int style, final Locale locale); @Override public int hashCode(); @Override public boolean equals(final Object obj); } // Abstract Java Test Class package org.apache.commons.lang3.time; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.Serializable; 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.commons.lang3.SerializationUtils; import org.junit.Test; public class FastDatePrinterTest { private static final String YYYY_MM_DD = "yyyy/MM/dd"; private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); private static final Locale SWEDEN = new Locale("sv", "SE"); DatePrinter getInstance(final String format); private DatePrinter getDateInstance(final int dateStyle, final Locale locale); private DatePrinter getInstance(final String format, final Locale locale); private DatePrinter getInstance(final String format, final TimeZone timeZone); protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale); @Test public void testFormat(); @Test public void testShortDateStyleWithLocales(); @Test public void testLowYearPadding(); @Test public void testMilleniumBug(); @Test public void testSimpleDate(); @Test public void testLang303(); @Test public void testLang538(); @Test public void testLang645(); @Test public void testEquals(); @Test public void testToStringContainsName(); @Test public void testPatternMatches(); @Test public void testLocaleMatches(); @Test public void testTimeZoneMatches(); @Test public void testCalendarTimezoneRespected(); } ``` You are a professional Java test case writer, please create a test case named `testSimpleDate` for the `FastDatePrinter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ @Test public void testSimpleDate() { ```
public class FastDatePrinter implements DatePrinter, Serializable
package org.apache.commons.lang3.time; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.Serializable; 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.commons.lang3.SerializationUtils; import org.junit.Test;
DatePrinter getInstance(final String format); private DatePrinter getDateInstance(final int dateStyle, final Locale locale); private DatePrinter getInstance(final String format, final Locale locale); private DatePrinter getInstance(final String format, final TimeZone timeZone); protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale); @Test public void testFormat(); @Test public void testShortDateStyleWithLocales(); @Test public void testLowYearPadding(); @Test public void testMilleniumBug(); @Test public void testSimpleDate(); @Test public void testLang303(); @Test public void testLang538(); @Test public void testLang645(); @Test public void testEquals(); @Test public void testToStringContainsName(); @Test public void testPatternMatches(); @Test public void testLocaleMatches(); @Test public void testTimeZoneMatches(); @Test public void testCalendarTimezoneRespected();
cdeabde133262f04e0cf9635cfc038c1d8e37ce689468f1126beae700582edfb
[ "org.apache.commons.lang3.time.FastDatePrinterTest::testSimpleDate" ]
private static final long serialVersionUID = 1L; public static final int FULL = DateFormat.FULL; public static final int LONG = DateFormat.LONG; public static final int MEDIUM = DateFormat.MEDIUM; public static final int SHORT = DateFormat.SHORT; private final String mPattern; private final TimeZone mTimeZone; private final Locale mLocale; private transient Rule[] mRules; private transient int mMaxLengthEstimate; private static ConcurrentMap<TimeZoneDisplayKey, String> cTimeZoneDisplayCache = new ConcurrentHashMap<TimeZoneDisplayKey, String>(7);
@Test public void testSimpleDate()
private static final String YYYY_MM_DD = "yyyy/MM/dd"; private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); private static final Locale SWEDEN = new Locale("sv", "SE");
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.Serializable; 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.commons.lang3.SerializationUtils; import org.junit.Test; /** * Unit tests {@link org.apache.commons.lang3.time.FastDatePrinter}. * * @since 3.0 */ public class FastDatePrinterTest { private static final String YYYY_MM_DD = "yyyy/MM/dd"; private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); private static final Locale SWEDEN = new Locale("sv", "SE"); DatePrinter getInstance(final String format) { return getInstance(format, TimeZone.getDefault(), Locale.getDefault()); } private DatePrinter getDateInstance(final int dateStyle, final Locale locale) { return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault()); } private DatePrinter getInstance(final String format, final Locale locale) { return getInstance(format, TimeZone.getDefault(), locale); } private DatePrinter getInstance(final String format, final TimeZone timeZone) { return getInstance(format, timeZone, Locale.getDefault()); } /** * Override this method in derived tests to change the construction of instances * @param format * @param timeZone * @param locale * @return */ protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale) { return new FastDatePrinter(format, timeZone, locale); } @Test public void testFormat() { final Locale realDefaultLocale = Locale.getDefault(); final TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(NEW_YORK); final GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); final GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); final Date date1 = cal1.getTime(); final Date date2 = cal2.getTime(); final long millis1 = date1.getTime(); final long millis2 = date2.getTime(); DatePrinter fdf = getInstance("yyyy-MM-dd'T'HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); assertEquals(sdf.format(date1), fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); assertEquals("2003-07-10T09:00:00", fdf.format(date2)); assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); fdf = getInstance("Z"); assertEquals("-0500", fdf.format(date1)); assertEquals("-0500", fdf.format(cal1)); assertEquals("-0500", fdf.format(millis1)); assertEquals("-0400", fdf.format(date2)); assertEquals("-0400", fdf.format(cal2)); assertEquals("-0400", fdf.format(millis2)); fdf = getInstance("ZZ"); assertEquals("-05:00", fdf.format(date1)); assertEquals("-05:00", fdf.format(cal1)); assertEquals("-05:00", fdf.format(millis1)); assertEquals("-04:00", fdf.format(date2)); assertEquals("-04:00", fdf.format(cal2)); assertEquals("-04:00", fdf.format(millis2)); final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; fdf = getInstance(pattern); sdf = new SimpleDateFormat(pattern); // SDF bug fix starting with Java 7 assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1)); assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2)); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } /** * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}. */ @Test public void testShortDateStyleWithLocales() { final Locale usLocale = Locale.US; final Locale swedishLocale = new Locale("sv", "SE"); final Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); DatePrinter fdf = getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ @Test public void testLowYearPadding() { final Calendar cal = Calendar.getInstance(); final DatePrinter format = getInstance(YYYY_MM_DD); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ @Test public void testMilleniumBug() { final Calendar cal = Calendar.getInstance(); final DatePrinter format = getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ @Test public void testSimpleDate() { final Calendar cal = Calendar.getInstance(); final DatePrinter format = getInstance(YYYY_MM_DD); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } @Test public void testLang303() { final Calendar cal = Calendar.getInstance(); cal.set(2004, 11, 31); DatePrinter format = getInstance(YYYY_MM_DD); final String output = format.format(cal); format = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) format)); assertEquals(output, format.format(cal)); } @Test public void testLang538() { // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone final GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); final DatePrinter format = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", "2009-10-16T16:42:16.000Z", format.format(cal.getTime())); assertEquals("dateTime", "2009-10-16T08:42:16.000Z", format.format(cal)); } @Test public void testLang645() { final Locale locale = new Locale("sv", "SE"); final Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1, 12, 0, 0); final Date d = cal.getTime(); final DatePrinter fdf = getInstance("EEEE', week 'ww", locale); assertEquals("fredag, week 53", fdf.format(d)); } @Test public void testEquals() { final DatePrinter printer1= getInstance(YYYY_MM_DD); final DatePrinter printer2= getInstance(YYYY_MM_DD); assertEquals(printer1, printer2); assertEquals(printer1.hashCode(), printer2.hashCode()); assertFalse(printer1.equals(new Object())); } @Test public void testToStringContainsName() { final DatePrinter printer= getInstance(YYYY_MM_DD); assertTrue(printer.toString().startsWith("FastDate")); } @Test public void testPatternMatches() { final DatePrinter printer= getInstance(YYYY_MM_DD); assertEquals(YYYY_MM_DD, printer.getPattern()); } @Test public void testLocaleMatches() { final DatePrinter printer= getInstance(YYYY_MM_DD, SWEDEN); assertEquals(SWEDEN, printer.getLocale()); } @Test public void testTimeZoneMatches() { final DatePrinter printer= getInstance(YYYY_MM_DD, NEW_YORK); assertEquals(NEW_YORK, printer.getTimeZone()); } @Test public void testCalendarTimezoneRespected() {} // Defects4J: flaky method // @Test // public void testCalendarTimezoneRespected() { // final String[] availableZones = TimeZone.getAvailableIDs(); // final TimeZone currentZone = TimeZone.getDefault(); // // TimeZone anotherZone = null; // for (final String zone : availableZones) { // if (!zone.equals(currentZone.getID())) { // anotherZone = TimeZone.getTimeZone(zone); // } // } // // assertNotNull("Cannot find another timezone", anotherZone); // // final String pattern = "h:mma z"; // final Calendar cal = Calendar.getInstance(anotherZone); // // final SimpleDateFormat sdf = new SimpleDateFormat(pattern); // sdf.setTimeZone(anotherZone); // final String expectedValue = sdf.format(cal.getTime()); // final String actualValue = FastDateFormat.getInstance(pattern).format(cal); // assertEquals(expectedValue, actualValue); // } }
[ { "be_test_class_file": "org/apache/commons/lang3/time/FastDatePrinter.java", "be_test_class_name": "org.apache.commons.lang3.time.FastDatePrinter", "be_test_function_name": "applyRules", "be_test_function_signature": "(Ljava/util/Calendar;Ljava/lang/StringBuffer;)Ljava/lang/StringBuffer;", "line_numbers": [ "464", "465", "467" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/time/FastDatePrinter.java", "be_test_class_name": "org.apache.commons.lang3.time.FastDatePrinter", "be_test_function_name": "format", "be_test_function_signature": "(Ljava/util/Calendar;)Ljava/lang/String;", "line_numbers": [ "426" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/time/FastDatePrinter.java", "be_test_class_name": "org.apache.commons.lang3.time.FastDatePrinter", "be_test_function_name": "format", "be_test_function_signature": "(Ljava/util/Calendar;Ljava/lang/StringBuffer;)Ljava/lang/StringBuffer;", "line_numbers": [ "452" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/time/FastDatePrinter.java", "be_test_class_name": "org.apache.commons.lang3.time.FastDatePrinter", "be_test_function_name": "init", "be_test_function_signature": "()V", "line_numbers": [ "148", "149", "151", "152", "153", "156", "157" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/time/FastDatePrinter.java", "be_test_class_name": "org.apache.commons.lang3.time.FastDatePrinter", "be_test_function_name": "parsePattern", "be_test_function_signature": "()Ljava/util/List;", "line_numbers": [ "168", "169", "171", "172", "173", "174", "175", "176", "178", "179", "181", "182", "183", "184", "186", "187", "188", "192", "194", "196", "197", "199", "200", "202", "204", "206", "207", "208", "209", "210", "211", "213", "215", "217", "218", "220", "221", "223", "224", "226", "227", "229", "230", "232", "233", "235", "236", "238", "239", "241", "242", "244", "245", "247", "248", "250", "251", "253", "254", "256", "257", "259", "260", "262", "264", "266", "267", "269", "271", "273", "274", "275", "277", "279", "281", "284", "287" ], "method_line_rate": 0.4155844155844156 }, { "be_test_class_file": "org/apache/commons/lang3/time/FastDatePrinter.java", "be_test_class_name": "org.apache.commons.lang3.time.FastDatePrinter", "be_test_function_name": "parseToken", "be_test_function_signature": "(Ljava/lang/String;[I)Ljava/lang/String;", "line_numbers": [ "298", "300", "301", "303", "304", "307", "309", "310", "311", "312", "313", "317", "320", "322", "324", "325", "327", "328", "330", "331", "333", "335", "337", "338", "340", "345", "346" ], "method_line_rate": 0.8518518518518519 }, { "be_test_class_file": "org/apache/commons/lang3/time/FastDatePrinter.java", "be_test_class_name": "org.apache.commons.lang3.time.FastDatePrinter", "be_test_function_name": "selectNumberRule", "be_test_function_signature": "(II)Lorg/apache/commons/lang3/time/FastDatePrinter$NumberRule;", "line_numbers": [ "357", "359", "361", "363" ], "method_line_rate": 0.75 } ]
public class ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener
public void test2502355_zoomOutDomain() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainAxis(1, new NumberAxis("X2")); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoomOutDomain(1.0, 2.0); assertEquals(1, this.chartChangeEvents.size()); }
// public int getZoomTriggerDistance(); // public void setZoomTriggerDistance(int distance); // public File getDefaultDirectoryForSaveAs(); // public void setDefaultDirectoryForSaveAs(File directory); // public boolean isEnforceFileExtensions(); // public void setEnforceFileExtensions(boolean enforce); // public boolean getZoomAroundAnchor(); // public void setZoomAroundAnchor(boolean zoomAroundAnchor); // public Paint getZoomFillPaint(); // public void setZoomFillPaint(Paint paint); // public Paint getZoomOutlinePaint(); // public void setZoomOutlinePaint(Paint paint); // public boolean isMouseWheelEnabled(); // public void setMouseWheelEnabled(boolean flag); // public void addOverlay(Overlay overlay); // public void removeOverlay(Overlay overlay); // public void overlayChanged(OverlayChangeEvent event); // public boolean getUseBuffer(); // public PlotOrientation getOrientation(); // public void addMouseHandler(AbstractMouseHandler handler); // public boolean removeMouseHandler(AbstractMouseHandler handler); // public void clearLiveMouseHandler(); // public ZoomHandler getZoomHandler(); // public Rectangle2D getZoomRectangle(); // public void setZoomRectangle(Rectangle2D rect); // public void setDisplayToolTips(boolean flag); // public String getToolTipText(MouseEvent e); // public Point translateJava2DToScreen(Point2D java2DPoint); // public Point2D translateScreenToJava2D(Point screenPoint); // public Rectangle2D scale(Rectangle2D rect); // public ChartEntity getEntityForPoint(int viewX, int viewY); // public boolean getRefreshBuffer(); // public void setRefreshBuffer(boolean flag); // public void paintComponent(Graphics g); // public void chartChanged(ChartChangeEvent event); // public void chartProgress(ChartProgressEvent event); // public void actionPerformed(ActionEvent event); // public void mouseEntered(MouseEvent e); // public void mouseExited(MouseEvent e); // public void mousePressed(MouseEvent e); // public void mouseDragged(MouseEvent e); // public void mouseReleased(MouseEvent e); // public void mouseClicked(MouseEvent event); // public void mouseMoved(MouseEvent e); // public void zoomInBoth(double x, double y); // public void zoomInDomain(double x, double y); // public void zoomInRange(double x, double y); // public void zoomOutBoth(double x, double y); // public void zoomOutDomain(double x, double y); // public void zoomOutRange(double x, double y); // public void zoom(Rectangle2D selection); // public void restoreAutoBounds(); // public void restoreAutoDomainBounds(); // public void restoreAutoRangeBounds(); // public Rectangle2D getScreenDataArea(); // public Rectangle2D getScreenDataArea(int x, int y); // public int getInitialDelay(); // public int getReshowDelay(); // public int getDismissDelay(); // public void setInitialDelay(int delay); // public void setReshowDelay(int delay); // public void setDismissDelay(int delay); // public double getZoomInFactor(); // public void setZoomInFactor(double factor); // public double getZoomOutFactor(); // public void setZoomOutFactor(double factor); // private void drawZoomRectangle(Graphics2D g2, boolean xor); // private void drawSelectionShape(Graphics2D g2, boolean xor); // public void doEditChartProperties(); // public void doCopy(); // public void doSaveAs() throws IOException; // public void createChartPrintJob(); // public int print(Graphics g, PageFormat pf, int pageIndex); // public void addChartMouseListener(ChartMouseListener listener); // public void removeChartMouseListener(ChartMouseListener listener); // public EventListener[] getListeners(Class listenerType); // protected JPopupMenu createPopupMenu(boolean properties, boolean save, // boolean print, boolean zoom); // protected JPopupMenu createPopupMenu(boolean properties, // boolean copy, boolean save, boolean print, boolean zoom); // protected void displayPopupMenu(int x, int y); // public void updateUI(); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public Shape getSelectionShape(); // public void setSelectionShape(Shape shape); // public Paint getSelectionFillPaint(); // public void setSelectionFillPaint(Paint paint); // public Paint getSelectionOutlinePaint(); // public void setSelectionOutlinePaint(Paint paint); // public Stroke getSelectionOutlineStroke(); // public void setSelectionOutlineStroke(Stroke stroke); // public DatasetSelectionState getSelectionState(Dataset dataset); // public void putSelectionState(Dataset dataset, // DatasetSelectionState state); // public Graphics2D createGraphics2D(); // } // // // Abstract Java Test Class // package org.jfree.chart.junit; // // import java.awt.geom.Rectangle2D; // import java.util.EventListener; // import java.util.List; // import javax.swing.event.CaretListener; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.ChartFactory; // import org.jfree.chart.ChartMouseEvent; // import org.jfree.chart.ChartMouseListener; // import org.jfree.chart.ChartPanel; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.event.ChartChangeEvent; // import org.jfree.chart.event.ChartChangeListener; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.XYPlot; // import org.jfree.data.xy.DefaultXYDataset; // // // // public class ChartPanelTests extends TestCase // implements ChartChangeListener, ChartMouseListener { // private List chartChangeEvents = new java.util.ArrayList(); // // public void chartChanged(ChartChangeEvent event); // public static Test suite(); // public ChartPanelTests(String name); // public void testConstructor1(); // public void testSetChart(); // public void testGetListeners(); // public void chartMouseClicked(ChartMouseEvent event); // public void chartMouseMoved(ChartMouseEvent event); // public void test2502355_zoom(); // public void test2502355_zoomInBoth(); // public void test2502355_zoomOutBoth(); // public void test2502355_restoreAutoBounds(); // public void test2502355_zoomInDomain(); // public void test2502355_zoomInRange(); // public void test2502355_zoomOutDomain(); // public void test2502355_zoomOutRange(); // public void test2502355_restoreAutoDomainBounds(); // public void test2502355_restoreAutoRangeBounds(); // public void testSetMouseWheelEnabled(); // } // You are a professional Java test case writer, please create a test case named `test2502355_zoomOutDomain` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Checks that a call to the zoomOutDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */
tests/org/jfree/chart/junit/ChartPanelTests.java
package org.jfree.chart; import java.awt.AWTEvent; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Insets; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.Toolkit; import java.awt.Transparency; import java.awt.datatransfer.Clipboard; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.EventListener; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.event.EventListenerList; import org.jfree.chart.editor.ChartEditor; import org.jfree.chart.editor.ChartEditorManager; import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.panel.Overlay; import org.jfree.chart.event.OverlayChangeEvent; import org.jfree.chart.event.OverlayChangeListener; import org.jfree.chart.panel.AbstractMouseHandler; import org.jfree.chart.panel.PanHandler; import org.jfree.chart.panel.ZoomHandler; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.Zoomable; import org.jfree.chart.ui.ExtensionFileFilter; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.general.Dataset; import org.jfree.data.general.DatasetAndSelection; import org.jfree.data.general.DatasetSelectionState;
public ChartPanel(JFreeChart chart); public ChartPanel(JFreeChart chart, boolean useBuffer); public ChartPanel(JFreeChart chart, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips); public ChartPanel(JFreeChart chart, int width, int height, int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth, int maximumDrawHeight, boolean useBuffer, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips); public ChartPanel(JFreeChart chart, int width, int height, int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth, int maximumDrawHeight, boolean useBuffer, boolean properties, boolean copy, boolean save, boolean print, boolean zoom, boolean tooltips); public JFreeChart getChart(); public void setChart(JFreeChart chart); public int getMinimumDrawWidth(); public void setMinimumDrawWidth(int width); public int getMaximumDrawWidth(); public void setMaximumDrawWidth(int width); public int getMinimumDrawHeight(); public void setMinimumDrawHeight(int height); public int getMaximumDrawHeight(); public void setMaximumDrawHeight(int height); public double getScaleX(); public double getScaleY(); public Point2D getAnchor(); protected void setAnchor(Point2D anchor); public JPopupMenu getPopupMenu(); public void setPopupMenu(JPopupMenu popup); public ChartRenderingInfo getChartRenderingInfo(); public void setMouseZoomable(boolean flag); public void setMouseZoomable(boolean flag, boolean fillRectangle); public boolean isDomainZoomable(); public void setDomainZoomable(boolean flag); public boolean isRangeZoomable(); public void setRangeZoomable(boolean flag); public boolean getFillZoomRectangle(); public void setFillZoomRectangle(boolean flag); public int getZoomTriggerDistance(); public void setZoomTriggerDistance(int distance); public File getDefaultDirectoryForSaveAs(); public void setDefaultDirectoryForSaveAs(File directory); public boolean isEnforceFileExtensions(); public void setEnforceFileExtensions(boolean enforce); public boolean getZoomAroundAnchor(); public void setZoomAroundAnchor(boolean zoomAroundAnchor); public Paint getZoomFillPaint(); public void setZoomFillPaint(Paint paint); public Paint getZoomOutlinePaint(); public void setZoomOutlinePaint(Paint paint); public boolean isMouseWheelEnabled(); public void setMouseWheelEnabled(boolean flag); public void addOverlay(Overlay overlay); public void removeOverlay(Overlay overlay); public void overlayChanged(OverlayChangeEvent event); public boolean getUseBuffer(); public PlotOrientation getOrientation(); public void addMouseHandler(AbstractMouseHandler handler); public boolean removeMouseHandler(AbstractMouseHandler handler); public void clearLiveMouseHandler(); public ZoomHandler getZoomHandler(); public Rectangle2D getZoomRectangle(); public void setZoomRectangle(Rectangle2D rect); public void setDisplayToolTips(boolean flag); public String getToolTipText(MouseEvent e); public Point translateJava2DToScreen(Point2D java2DPoint); public Point2D translateScreenToJava2D(Point screenPoint); public Rectangle2D scale(Rectangle2D rect); public ChartEntity getEntityForPoint(int viewX, int viewY); public boolean getRefreshBuffer(); public void setRefreshBuffer(boolean flag); public void paintComponent(Graphics g); public void chartChanged(ChartChangeEvent event); public void chartProgress(ChartProgressEvent event); public void actionPerformed(ActionEvent event); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseDragged(MouseEvent e); public void mouseReleased(MouseEvent e); public void mouseClicked(MouseEvent event); public void mouseMoved(MouseEvent e); public void zoomInBoth(double x, double y); public void zoomInDomain(double x, double y); public void zoomInRange(double x, double y); public void zoomOutBoth(double x, double y); public void zoomOutDomain(double x, double y); public void zoomOutRange(double x, double y); public void zoom(Rectangle2D selection); public void restoreAutoBounds(); public void restoreAutoDomainBounds(); public void restoreAutoRangeBounds(); public Rectangle2D getScreenDataArea(); public Rectangle2D getScreenDataArea(int x, int y); public int getInitialDelay(); public int getReshowDelay(); public int getDismissDelay(); public void setInitialDelay(int delay); public void setReshowDelay(int delay); public void setDismissDelay(int delay); public double getZoomInFactor(); public void setZoomInFactor(double factor); public double getZoomOutFactor(); public void setZoomOutFactor(double factor); private void drawZoomRectangle(Graphics2D g2, boolean xor); private void drawSelectionShape(Graphics2D g2, boolean xor); public void doEditChartProperties(); public void doCopy(); public void doSaveAs() throws IOException; public void createChartPrintJob(); public int print(Graphics g, PageFormat pf, int pageIndex); public void addChartMouseListener(ChartMouseListener listener); public void removeChartMouseListener(ChartMouseListener listener); public EventListener[] getListeners(Class listenerType); protected JPopupMenu createPopupMenu(boolean properties, boolean save, boolean print, boolean zoom); protected JPopupMenu createPopupMenu(boolean properties, boolean copy, boolean save, boolean print, boolean zoom); protected void displayPopupMenu(int x, int y); public void updateUI(); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public Shape getSelectionShape(); public void setSelectionShape(Shape shape); public Paint getSelectionFillPaint(); public void setSelectionFillPaint(Paint paint); public Paint getSelectionOutlinePaint(); public void setSelectionOutlinePaint(Paint paint); public Stroke getSelectionOutlineStroke(); public void setSelectionOutlineStroke(Stroke stroke); public DatasetSelectionState getSelectionState(Dataset dataset); public void putSelectionState(Dataset dataset, DatasetSelectionState state); public Graphics2D createGraphics2D();
283
test2502355_zoomOutDomain
```java public int getZoomTriggerDistance(); public void setZoomTriggerDistance(int distance); public File getDefaultDirectoryForSaveAs(); public void setDefaultDirectoryForSaveAs(File directory); public boolean isEnforceFileExtensions(); public void setEnforceFileExtensions(boolean enforce); public boolean getZoomAroundAnchor(); public void setZoomAroundAnchor(boolean zoomAroundAnchor); public Paint getZoomFillPaint(); public void setZoomFillPaint(Paint paint); public Paint getZoomOutlinePaint(); public void setZoomOutlinePaint(Paint paint); public boolean isMouseWheelEnabled(); public void setMouseWheelEnabled(boolean flag); public void addOverlay(Overlay overlay); public void removeOverlay(Overlay overlay); public void overlayChanged(OverlayChangeEvent event); public boolean getUseBuffer(); public PlotOrientation getOrientation(); public void addMouseHandler(AbstractMouseHandler handler); public boolean removeMouseHandler(AbstractMouseHandler handler); public void clearLiveMouseHandler(); public ZoomHandler getZoomHandler(); public Rectangle2D getZoomRectangle(); public void setZoomRectangle(Rectangle2D rect); public void setDisplayToolTips(boolean flag); public String getToolTipText(MouseEvent e); public Point translateJava2DToScreen(Point2D java2DPoint); public Point2D translateScreenToJava2D(Point screenPoint); public Rectangle2D scale(Rectangle2D rect); public ChartEntity getEntityForPoint(int viewX, int viewY); public boolean getRefreshBuffer(); public void setRefreshBuffer(boolean flag); public void paintComponent(Graphics g); public void chartChanged(ChartChangeEvent event); public void chartProgress(ChartProgressEvent event); public void actionPerformed(ActionEvent event); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseDragged(MouseEvent e); public void mouseReleased(MouseEvent e); public void mouseClicked(MouseEvent event); public void mouseMoved(MouseEvent e); public void zoomInBoth(double x, double y); public void zoomInDomain(double x, double y); public void zoomInRange(double x, double y); public void zoomOutBoth(double x, double y); public void zoomOutDomain(double x, double y); public void zoomOutRange(double x, double y); public void zoom(Rectangle2D selection); public void restoreAutoBounds(); public void restoreAutoDomainBounds(); public void restoreAutoRangeBounds(); public Rectangle2D getScreenDataArea(); public Rectangle2D getScreenDataArea(int x, int y); public int getInitialDelay(); public int getReshowDelay(); public int getDismissDelay(); public void setInitialDelay(int delay); public void setReshowDelay(int delay); public void setDismissDelay(int delay); public double getZoomInFactor(); public void setZoomInFactor(double factor); public double getZoomOutFactor(); public void setZoomOutFactor(double factor); private void drawZoomRectangle(Graphics2D g2, boolean xor); private void drawSelectionShape(Graphics2D g2, boolean xor); public void doEditChartProperties(); public void doCopy(); public void doSaveAs() throws IOException; public void createChartPrintJob(); public int print(Graphics g, PageFormat pf, int pageIndex); public void addChartMouseListener(ChartMouseListener listener); public void removeChartMouseListener(ChartMouseListener listener); public EventListener[] getListeners(Class listenerType); protected JPopupMenu createPopupMenu(boolean properties, boolean save, boolean print, boolean zoom); protected JPopupMenu createPopupMenu(boolean properties, boolean copy, boolean save, boolean print, boolean zoom); protected void displayPopupMenu(int x, int y); public void updateUI(); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public Shape getSelectionShape(); public void setSelectionShape(Shape shape); public Paint getSelectionFillPaint(); public void setSelectionFillPaint(Paint paint); public Paint getSelectionOutlinePaint(); public void setSelectionOutlinePaint(Paint paint); public Stroke getSelectionOutlineStroke(); public void setSelectionOutlineStroke(Stroke stroke); public DatasetSelectionState getSelectionState(Dataset dataset); public void putSelectionState(Dataset dataset, DatasetSelectionState state); public Graphics2D createGraphics2D(); } // Abstract Java Test Class package org.jfree.chart.junit; import java.awt.geom.Rectangle2D; import java.util.EventListener; import java.util.List; import javax.swing.event.CaretListener; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultXYDataset; public class ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener { private List chartChangeEvents = new java.util.ArrayList(); public void chartChanged(ChartChangeEvent event); public static Test suite(); public ChartPanelTests(String name); public void testConstructor1(); public void testSetChart(); public void testGetListeners(); public void chartMouseClicked(ChartMouseEvent event); public void chartMouseMoved(ChartMouseEvent event); public void test2502355_zoom(); public void test2502355_zoomInBoth(); public void test2502355_zoomOutBoth(); public void test2502355_restoreAutoBounds(); public void test2502355_zoomInDomain(); public void test2502355_zoomInRange(); public void test2502355_zoomOutDomain(); public void test2502355_zoomOutRange(); public void test2502355_restoreAutoDomainBounds(); public void test2502355_restoreAutoRangeBounds(); public void testSetMouseWheelEnabled(); } ``` You are a professional Java test case writer, please create a test case named `test2502355_zoomOutDomain` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Checks that a call to the zoomOutDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */
272
// public int getZoomTriggerDistance(); // public void setZoomTriggerDistance(int distance); // public File getDefaultDirectoryForSaveAs(); // public void setDefaultDirectoryForSaveAs(File directory); // public boolean isEnforceFileExtensions(); // public void setEnforceFileExtensions(boolean enforce); // public boolean getZoomAroundAnchor(); // public void setZoomAroundAnchor(boolean zoomAroundAnchor); // public Paint getZoomFillPaint(); // public void setZoomFillPaint(Paint paint); // public Paint getZoomOutlinePaint(); // public void setZoomOutlinePaint(Paint paint); // public boolean isMouseWheelEnabled(); // public void setMouseWheelEnabled(boolean flag); // public void addOverlay(Overlay overlay); // public void removeOverlay(Overlay overlay); // public void overlayChanged(OverlayChangeEvent event); // public boolean getUseBuffer(); // public PlotOrientation getOrientation(); // public void addMouseHandler(AbstractMouseHandler handler); // public boolean removeMouseHandler(AbstractMouseHandler handler); // public void clearLiveMouseHandler(); // public ZoomHandler getZoomHandler(); // public Rectangle2D getZoomRectangle(); // public void setZoomRectangle(Rectangle2D rect); // public void setDisplayToolTips(boolean flag); // public String getToolTipText(MouseEvent e); // public Point translateJava2DToScreen(Point2D java2DPoint); // public Point2D translateScreenToJava2D(Point screenPoint); // public Rectangle2D scale(Rectangle2D rect); // public ChartEntity getEntityForPoint(int viewX, int viewY); // public boolean getRefreshBuffer(); // public void setRefreshBuffer(boolean flag); // public void paintComponent(Graphics g); // public void chartChanged(ChartChangeEvent event); // public void chartProgress(ChartProgressEvent event); // public void actionPerformed(ActionEvent event); // public void mouseEntered(MouseEvent e); // public void mouseExited(MouseEvent e); // public void mousePressed(MouseEvent e); // public void mouseDragged(MouseEvent e); // public void mouseReleased(MouseEvent e); // public void mouseClicked(MouseEvent event); // public void mouseMoved(MouseEvent e); // public void zoomInBoth(double x, double y); // public void zoomInDomain(double x, double y); // public void zoomInRange(double x, double y); // public void zoomOutBoth(double x, double y); // public void zoomOutDomain(double x, double y); // public void zoomOutRange(double x, double y); // public void zoom(Rectangle2D selection); // public void restoreAutoBounds(); // public void restoreAutoDomainBounds(); // public void restoreAutoRangeBounds(); // public Rectangle2D getScreenDataArea(); // public Rectangle2D getScreenDataArea(int x, int y); // public int getInitialDelay(); // public int getReshowDelay(); // public int getDismissDelay(); // public void setInitialDelay(int delay); // public void setReshowDelay(int delay); // public void setDismissDelay(int delay); // public double getZoomInFactor(); // public void setZoomInFactor(double factor); // public double getZoomOutFactor(); // public void setZoomOutFactor(double factor); // private void drawZoomRectangle(Graphics2D g2, boolean xor); // private void drawSelectionShape(Graphics2D g2, boolean xor); // public void doEditChartProperties(); // public void doCopy(); // public void doSaveAs() throws IOException; // public void createChartPrintJob(); // public int print(Graphics g, PageFormat pf, int pageIndex); // public void addChartMouseListener(ChartMouseListener listener); // public void removeChartMouseListener(ChartMouseListener listener); // public EventListener[] getListeners(Class listenerType); // protected JPopupMenu createPopupMenu(boolean properties, boolean save, // boolean print, boolean zoom); // protected JPopupMenu createPopupMenu(boolean properties, // boolean copy, boolean save, boolean print, boolean zoom); // protected void displayPopupMenu(int x, int y); // public void updateUI(); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public Shape getSelectionShape(); // public void setSelectionShape(Shape shape); // public Paint getSelectionFillPaint(); // public void setSelectionFillPaint(Paint paint); // public Paint getSelectionOutlinePaint(); // public void setSelectionOutlinePaint(Paint paint); // public Stroke getSelectionOutlineStroke(); // public void setSelectionOutlineStroke(Stroke stroke); // public DatasetSelectionState getSelectionState(Dataset dataset); // public void putSelectionState(Dataset dataset, // DatasetSelectionState state); // public Graphics2D createGraphics2D(); // } // // // Abstract Java Test Class // package org.jfree.chart.junit; // // import java.awt.geom.Rectangle2D; // import java.util.EventListener; // import java.util.List; // import javax.swing.event.CaretListener; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.ChartFactory; // import org.jfree.chart.ChartMouseEvent; // import org.jfree.chart.ChartMouseListener; // import org.jfree.chart.ChartPanel; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.event.ChartChangeEvent; // import org.jfree.chart.event.ChartChangeListener; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.XYPlot; // import org.jfree.data.xy.DefaultXYDataset; // // // // public class ChartPanelTests extends TestCase // implements ChartChangeListener, ChartMouseListener { // private List chartChangeEvents = new java.util.ArrayList(); // // public void chartChanged(ChartChangeEvent event); // public static Test suite(); // public ChartPanelTests(String name); // public void testConstructor1(); // public void testSetChart(); // public void testGetListeners(); // public void chartMouseClicked(ChartMouseEvent event); // public void chartMouseMoved(ChartMouseEvent event); // public void test2502355_zoom(); // public void test2502355_zoomInBoth(); // public void test2502355_zoomOutBoth(); // public void test2502355_restoreAutoBounds(); // public void test2502355_zoomInDomain(); // public void test2502355_zoomInRange(); // public void test2502355_zoomOutDomain(); // public void test2502355_zoomOutRange(); // public void test2502355_restoreAutoDomainBounds(); // public void test2502355_restoreAutoRangeBounds(); // public void testSetMouseWheelEnabled(); // } // You are a professional Java test case writer, please create a test case named `test2502355_zoomOutDomain` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Checks that a call to the zoomOutDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */ public void test2502355_zoomOutDomain() {
/** * Checks that a call to the zoomOutDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */
1
org.jfree.chart.ChartPanel
tests
```java public int getZoomTriggerDistance(); public void setZoomTriggerDistance(int distance); public File getDefaultDirectoryForSaveAs(); public void setDefaultDirectoryForSaveAs(File directory); public boolean isEnforceFileExtensions(); public void setEnforceFileExtensions(boolean enforce); public boolean getZoomAroundAnchor(); public void setZoomAroundAnchor(boolean zoomAroundAnchor); public Paint getZoomFillPaint(); public void setZoomFillPaint(Paint paint); public Paint getZoomOutlinePaint(); public void setZoomOutlinePaint(Paint paint); public boolean isMouseWheelEnabled(); public void setMouseWheelEnabled(boolean flag); public void addOverlay(Overlay overlay); public void removeOverlay(Overlay overlay); public void overlayChanged(OverlayChangeEvent event); public boolean getUseBuffer(); public PlotOrientation getOrientation(); public void addMouseHandler(AbstractMouseHandler handler); public boolean removeMouseHandler(AbstractMouseHandler handler); public void clearLiveMouseHandler(); public ZoomHandler getZoomHandler(); public Rectangle2D getZoomRectangle(); public void setZoomRectangle(Rectangle2D rect); public void setDisplayToolTips(boolean flag); public String getToolTipText(MouseEvent e); public Point translateJava2DToScreen(Point2D java2DPoint); public Point2D translateScreenToJava2D(Point screenPoint); public Rectangle2D scale(Rectangle2D rect); public ChartEntity getEntityForPoint(int viewX, int viewY); public boolean getRefreshBuffer(); public void setRefreshBuffer(boolean flag); public void paintComponent(Graphics g); public void chartChanged(ChartChangeEvent event); public void chartProgress(ChartProgressEvent event); public void actionPerformed(ActionEvent event); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseDragged(MouseEvent e); public void mouseReleased(MouseEvent e); public void mouseClicked(MouseEvent event); public void mouseMoved(MouseEvent e); public void zoomInBoth(double x, double y); public void zoomInDomain(double x, double y); public void zoomInRange(double x, double y); public void zoomOutBoth(double x, double y); public void zoomOutDomain(double x, double y); public void zoomOutRange(double x, double y); public void zoom(Rectangle2D selection); public void restoreAutoBounds(); public void restoreAutoDomainBounds(); public void restoreAutoRangeBounds(); public Rectangle2D getScreenDataArea(); public Rectangle2D getScreenDataArea(int x, int y); public int getInitialDelay(); public int getReshowDelay(); public int getDismissDelay(); public void setInitialDelay(int delay); public void setReshowDelay(int delay); public void setDismissDelay(int delay); public double getZoomInFactor(); public void setZoomInFactor(double factor); public double getZoomOutFactor(); public void setZoomOutFactor(double factor); private void drawZoomRectangle(Graphics2D g2, boolean xor); private void drawSelectionShape(Graphics2D g2, boolean xor); public void doEditChartProperties(); public void doCopy(); public void doSaveAs() throws IOException; public void createChartPrintJob(); public int print(Graphics g, PageFormat pf, int pageIndex); public void addChartMouseListener(ChartMouseListener listener); public void removeChartMouseListener(ChartMouseListener listener); public EventListener[] getListeners(Class listenerType); protected JPopupMenu createPopupMenu(boolean properties, boolean save, boolean print, boolean zoom); protected JPopupMenu createPopupMenu(boolean properties, boolean copy, boolean save, boolean print, boolean zoom); protected void displayPopupMenu(int x, int y); public void updateUI(); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; public Shape getSelectionShape(); public void setSelectionShape(Shape shape); public Paint getSelectionFillPaint(); public void setSelectionFillPaint(Paint paint); public Paint getSelectionOutlinePaint(); public void setSelectionOutlinePaint(Paint paint); public Stroke getSelectionOutlineStroke(); public void setSelectionOutlineStroke(Stroke stroke); public DatasetSelectionState getSelectionState(Dataset dataset); public void putSelectionState(Dataset dataset, DatasetSelectionState state); public Graphics2D createGraphics2D(); } // Abstract Java Test Class package org.jfree.chart.junit; import java.awt.geom.Rectangle2D; import java.util.EventListener; import java.util.List; import javax.swing.event.CaretListener; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultXYDataset; public class ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener { private List chartChangeEvents = new java.util.ArrayList(); public void chartChanged(ChartChangeEvent event); public static Test suite(); public ChartPanelTests(String name); public void testConstructor1(); public void testSetChart(); public void testGetListeners(); public void chartMouseClicked(ChartMouseEvent event); public void chartMouseMoved(ChartMouseEvent event); public void test2502355_zoom(); public void test2502355_zoomInBoth(); public void test2502355_zoomOutBoth(); public void test2502355_restoreAutoBounds(); public void test2502355_zoomInDomain(); public void test2502355_zoomInRange(); public void test2502355_zoomOutDomain(); public void test2502355_zoomOutRange(); public void test2502355_restoreAutoDomainBounds(); public void test2502355_restoreAutoRangeBounds(); public void testSetMouseWheelEnabled(); } ``` You are a professional Java test case writer, please create a test case named `test2502355_zoomOutDomain` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Checks that a call to the zoomOutDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */ public void test2502355_zoomOutDomain() { ```
public class ChartPanel extends JPanel implements ChartChangeListener, ChartProgressListener, ActionListener, MouseListener, MouseMotionListener, OverlayChangeListener, RenderingSource, Printable, Serializable
package org.jfree.chart.junit; import java.awt.geom.Rectangle2D; import java.util.EventListener; import java.util.List; import javax.swing.event.CaretListener; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultXYDataset;
public void chartChanged(ChartChangeEvent event); public static Test suite(); public ChartPanelTests(String name); public void testConstructor1(); public void testSetChart(); public void testGetListeners(); public void chartMouseClicked(ChartMouseEvent event); public void chartMouseMoved(ChartMouseEvent event); public void test2502355_zoom(); public void test2502355_zoomInBoth(); public void test2502355_zoomOutBoth(); public void test2502355_restoreAutoBounds(); public void test2502355_zoomInDomain(); public void test2502355_zoomInRange(); public void test2502355_zoomOutDomain(); public void test2502355_zoomOutRange(); public void test2502355_restoreAutoDomainBounds(); public void test2502355_restoreAutoRangeBounds(); public void testSetMouseWheelEnabled();
d03f00b10aef927f1691eedb38478d23448508a9d5637591954e03bf4961219f
[ "org.jfree.chart.junit.ChartPanelTests::test2502355_zoomOutDomain" ]
private static final long serialVersionUID = 6046366297214274674L; public static final boolean DEFAULT_BUFFER_USED = true; public static final int DEFAULT_WIDTH = 680; public static final int DEFAULT_HEIGHT = 420; public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300; public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200; public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 1024; public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 768; public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10; public static final String PROPERTIES_COMMAND = "PROPERTIES"; public static final String COPY_COMMAND = "COPY"; public static final String SAVE_COMMAND = "SAVE"; public static final String PRINT_COMMAND = "PRINT"; public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH"; public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN"; public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE"; public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH"; public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH"; public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH"; public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH"; public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN"; public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE"; private JFreeChart chart; private transient EventListenerList chartMouseListeners; private boolean useBuffer; private boolean refreshBuffer; private transient Image chartBuffer; private int chartBufferHeight; private int chartBufferWidth; private int minimumDrawWidth; private int minimumDrawHeight; private int maximumDrawWidth; private int maximumDrawHeight; private JPopupMenu popup; private ChartRenderingInfo info; private Point2D anchor; private double scaleX; private double scaleY; private PlotOrientation orientation = PlotOrientation.VERTICAL; private boolean domainZoomable = false; private boolean rangeZoomable = false; private Point2D zoomPoint = null; private transient Rectangle2D zoomRectangle = null; private boolean fillZoomRectangle = true; private int zoomTriggerDistance; private JMenuItem zoomInBothMenuItem; private JMenuItem zoomInDomainMenuItem; private JMenuItem zoomInRangeMenuItem; private JMenuItem zoomOutBothMenuItem; private JMenuItem zoomOutDomainMenuItem; private JMenuItem zoomOutRangeMenuItem; private JMenuItem zoomResetBothMenuItem; private JMenuItem zoomResetDomainMenuItem; private JMenuItem zoomResetRangeMenuItem; private File defaultDirectoryForSaveAs; private boolean enforceFileExtensions; private boolean ownToolTipDelaysActive; private int originalToolTipInitialDelay; private int originalToolTipReshowDelay; private int originalToolTipDismissDelay; private int ownToolTipInitialDelay; private int ownToolTipReshowDelay; private int ownToolTipDismissDelay; private double zoomInFactor = 0.5; private double zoomOutFactor = 2.0; private boolean zoomAroundAnchor; private transient Paint zoomOutlinePaint; private transient Paint zoomFillPaint; protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.LocalizationBundle"); private List overlays; private List availableMouseHandlers; private AbstractMouseHandler liveMouseHandler; private List auxiliaryMouseHandlers; private ZoomHandler zoomHandler; private List selectionStates = new java.util.ArrayList(); private Shape selectionShape; private Paint selectionFillPaint; private Paint selectionOutlinePaint = Color.darkGray; private Stroke selectionOutlineStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 4.0f, new float[] {3.0f, 3.0f}, 0.0f); private MouseWheelHandler mouseWheelHandler;
public void test2502355_zoomOutDomain()
private List chartChangeEvents = new java.util.ArrayList();
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2009, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ChartPanelTests.java * -------------------- * (C) Copyright 2004-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Jul-2004 : Version 1 (DG); * 12-Jan-2009 : Added test2502355() (DG); * 08-Jun-2009 : Added testSetMouseWheelEnabled() (DG); */ package org.jfree.chart.junit; import java.awt.geom.Rectangle2D; import java.util.EventListener; import java.util.List; import javax.swing.event.CaretListener; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultXYDataset; /** * Tests for the {@link ChartPanel} class. */ public class ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener { private List chartChangeEvents = new java.util.ArrayList(); /** * Receives a chart change event and stores it in a list for later * inspection. * * @param event the event. */ public void chartChanged(ChartChangeEvent event) { this.chartChangeEvents.add(event); } /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ChartPanelTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ChartPanelTests(String name) { super(name); } /** * Test that the constructor will accept a null chart. */ public void testConstructor1() { ChartPanel panel = new ChartPanel(null); assertEquals(null, panel.getChart()); } /** * Test that it is possible to set the panel's chart to null. */ public void testSetChart() { JFreeChart chart = new JFreeChart(new XYPlot()); ChartPanel panel = new ChartPanel(chart); panel.setChart(null); assertEquals(null, panel.getChart()); } /** * Check the behaviour of the getListeners() method. */ public void testGetListeners() { ChartPanel p = new ChartPanel(null); p.addChartMouseListener(this); EventListener[] listeners = p.getListeners(ChartMouseListener.class); assertEquals(1, listeners.length); assertEquals(this, listeners[0]); // try a listener type that isn't registered listeners = p.getListeners(CaretListener.class); assertEquals(0, listeners.length); p.removeChartMouseListener(this); listeners = p.getListeners(ChartMouseListener.class); assertEquals(0, listeners.length); // try a null argument boolean pass = false; try { listeners = p.getListeners((Class) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); // try a class that isn't a listener pass = false; try { listeners = p.getListeners(Integer.class); } catch (ClassCastException e) { pass = true; } assertTrue(pass); } /** * Ignores a mouse click event. * * @param event the event. */ public void chartMouseClicked(ChartMouseEvent event) { // ignore } /** * Ignores a mouse move event. * * @param event the event. */ public void chartMouseMoved(ChartMouseEvent event) { // ignore } /** * Checks that a call to the zoom() method generates just one * ChartChangeEvent. */ public void test2502355_zoom() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoom(new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0)); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the zoomInBoth() method generates just one * ChartChangeEvent. */ public void test2502355_zoomInBoth() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoomInBoth(1.0, 2.0); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the zoomOutBoth() method generates just one * ChartChangeEvent. */ public void test2502355_zoomOutBoth() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoomOutBoth(1.0, 2.0); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the restoreAutoBounds() method generates just one * ChartChangeEvent. */ public void test2502355_restoreAutoBounds() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.restoreAutoBounds(); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the zoomInDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */ public void test2502355_zoomInDomain() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainAxis(1, new NumberAxis("X2")); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoomInDomain(1.0, 2.0); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the zoomInRange() method, for a plot with more * than one range axis, generates just one ChartChangeEvent. */ public void test2502355_zoomInRange() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeAxis(1, new NumberAxis("X2")); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoomInRange(1.0, 2.0); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the zoomOutDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */ public void test2502355_zoomOutDomain() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainAxis(1, new NumberAxis("X2")); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoomOutDomain(1.0, 2.0); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the zoomOutRange() method, for a plot with more * than one range axis, generates just one ChartChangeEvent. */ public void test2502355_zoomOutRange() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeAxis(1, new NumberAxis("X2")); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.zoomOutRange(1.0, 2.0); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the restoreAutoDomainBounds() method, for a plot * with more than one range axis, generates just one ChartChangeEvent. */ public void test2502355_restoreAutoDomainBounds() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainAxis(1, new NumberAxis("X2")); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.restoreAutoDomainBounds(); assertEquals(1, this.chartChangeEvents.size()); } /** * Checks that a call to the restoreAutoRangeBounds() method, for a plot * with more than one range axis, generates just one ChartChangeEvent. */ public void test2502355_restoreAutoRangeBounds() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeAxis(1, new NumberAxis("X2")); ChartPanel panel = new ChartPanel(chart); chart.addChangeListener(this); this.chartChangeEvents.clear(); panel.restoreAutoRangeBounds(); assertEquals(1, this.chartChangeEvents.size()); } /** * In version 1.0.13 there is a bug where enabling the mouse wheel handler * twice would in fact disable it. */ public void testSetMouseWheelEnabled() { DefaultXYDataset dataset = new DefaultXYDataset(); JFreeChart chart = ChartFactory.createXYLineChart("TestChart", "X", "Y", dataset, false); ChartPanel panel = new ChartPanel(chart); panel.setMouseWheelEnabled(true); assertTrue(panel.isMouseWheelEnabled()); panel.setMouseWheelEnabled(true); assertTrue(panel.isMouseWheelEnabled()); panel.setMouseWheelEnabled(false); assertFalse(panel.isMouseWheelEnabled()); } }
[ { "be_test_class_file": "org/jfree/chart/ChartPanel.java", "be_test_class_name": "org.jfree.chart.ChartPanel", "be_test_function_name": "chartChanged", "be_test_function_signature": "(Lorg/jfree/chart/event/ChartChangeEvent;)V", "line_numbers": [ "1746", "1747", "1748", "1749", "1750", "1752", "1753" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/ChartPanel.java", "be_test_class_name": "org.jfree.chart.ChartPanel", "be_test_function_name": "createPopupMenu", "be_test_function_signature": "(ZZZZZ)Ljavax/swing/JPopupMenu;", "line_numbers": [ "2733", "2734", "2736", "2737", "2739", "2740", "2741", "2742", "2745", "2746", "2747", "2748", "2750", "2752", "2753", "2754", "2755", "2758", "2759", "2760", "2761", "2763", "2765", "2766", "2767", "2768", "2771", "2772", "2773", "2774", "2776", "2778", "2779", "2780", "2781", "2784", "2785", "2786", "2787", "2790", "2793", "2795", "2796", "2797", "2799", "2801", "2803", "2804", "2805", "2807", "2809", "2810", "2811", "2813", "2815", "2818", "2820", "2821", "2822", "2824", "2826", "2828", "2830", "2831", "2833", "2835", "2836", "2837", "2839", "2841", "2844", "2846", "2848", "2849", "2851", "2852", "2854", "2856", "2857", "2859", "2861", "2863", "2864", "2866", "2867", "2871" ], "method_line_rate": 0.9767441860465116 }, { "be_test_class_file": "org/jfree/chart/ChartPanel.java", "be_test_class_name": "org.jfree.chart.ChartPanel", "be_test_function_name": "setChart", "be_test_function_signature": "(Lorg/jfree/chart/JFreeChart;)V", "line_numbers": [ "824", "825", "826", "830", "831", "832", "833", "834", "835", "836", "837", "838", "839", "840", "841", "843", "845", "846", "848", "849", "851", "853" ], "method_line_rate": 0.7727272727272727 }, { "be_test_class_file": "org/jfree/chart/ChartPanel.java", "be_test_class_name": "org.jfree.chart.ChartPanel", "be_test_function_name": "setDisplayToolTips", "be_test_function_signature": "(Z)V", "line_numbers": [ "1472", "1473", "1476", "1478" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/jfree/chart/ChartPanel.java", "be_test_class_name": "org.jfree.chart.ChartPanel", "be_test_function_name": "translateScreenToJava2D", "be_test_function_signature": "(Ljava/awt/Point;)Ljava/awt/geom/Point2D;", "line_numbers": [ "1529", "1530", "1531", "1532" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/ChartPanel.java", "be_test_class_name": "org.jfree.chart.ChartPanel", "be_test_function_name": "updateUI", "be_test_function_signature": "()V", "line_numbers": [ "2942", "2943", "2945", "2946" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/jfree/chart/ChartPanel.java", "be_test_class_name": "org.jfree.chart.ChartPanel", "be_test_function_name": "zoomOutDomain", "be_test_function_signature": "(DD)V", "line_numbers": [ "2184", "2185", "2189", "2190", "2191", "2192", "2195", "2197" ], "method_line_rate": 1 } ]
public class BeanUtilTest extends BaseMapTest
public void testNameMangle() { assertEquals("foo", BeanUtil.legacyManglePropertyName("getFoo", 3)); assertEquals("foo", BeanUtil.stdManglePropertyName("getFoo", 3)); assertEquals("url", BeanUtil.legacyManglePropertyName("getURL", 3)); assertEquals("URL", BeanUtil.stdManglePropertyName("getURL", 3)); }
// // Abstract Java Tested Class // package com.fasterxml.jackson.databind.util; // // import java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import com.fasterxml.jackson.annotation.JsonInclude; // import com.fasterxml.jackson.databind.JavaType; // import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; // // // // public class BeanUtil // { // // // public static String okNameForGetter(AnnotatedMethod am, boolean stdNaming); // public static String okNameForRegularGetter(AnnotatedMethod am, String name, // boolean stdNaming); // public static String okNameForIsGetter(AnnotatedMethod am, String name, // boolean stdNaming); // @Deprecated // since 2.9, not used any more // public static String okNameForSetter(AnnotatedMethod am, boolean stdNaming); // public static String okNameForMutator(AnnotatedMethod am, String prefix, // boolean stdNaming); // public static Object getDefaultValue(JavaType type); // protected static boolean isCglibGetCallbacks(AnnotatedMethod am); // protected static boolean isGroovyMetaClassSetter(AnnotatedMethod am); // protected static boolean isGroovyMetaClassGetter(AnnotatedMethod am); // protected static String legacyManglePropertyName(final String basename, final int offset); // protected static String stdManglePropertyName(final String basename, final int offset); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.util; // // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.annotation.JsonInclude; // import com.fasterxml.jackson.databind.BaseMapTest; // import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // public class BeanUtilTest extends BaseMapTest // { // // // public void testNameMangle(); // public void testGetDefaultValue(); // public void testIsGetter() throws Exception; // public void testOkNameForGetter() throws Exception; // public void testOkNameForSetter() throws Exception; // private void _testIsGetter(String name, String expName) throws Exception; // private void _testIsGetter(String name, String expName, boolean useStd) throws Exception; // private void _testOkNameForGetter(String name, String expName) throws Exception; // private void _testOkNameForGetter(String name, String expName, boolean useStd) throws Exception; // private void _testOkNameForSetter(String name, String expName) throws Exception; // @SuppressWarnings("deprecation") // private void _testOkNameForSetter(String name, String expName, boolean useStd) throws Exception; // private AnnotatedMethod _method(Class<?> cls, String name, Class<?>...parameterTypes) throws Exception; // public boolean isPrimitive(); // public Boolean isWrapper(); // public String isNotGetter(); // public boolean is(); // public String getCallbacks(); // public String getMetaClass(); // public boolean get(); // public void setFoo(); // public void notSetter(); // public void set(); // } // You are a professional Java test case writer, please create a test case named `testNameMangle` for the `BeanUtil` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/util/BeanUtilTest.java
package com.fasterxml.jackson.databind.util; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
public static String okNameForGetter(AnnotatedMethod am, boolean stdNaming); public static String okNameForRegularGetter(AnnotatedMethod am, String name, boolean stdNaming); public static String okNameForIsGetter(AnnotatedMethod am, String name, boolean stdNaming); @Deprecated // since 2.9, not used any more public static String okNameForSetter(AnnotatedMethod am, boolean stdNaming); public static String okNameForMutator(AnnotatedMethod am, String prefix, boolean stdNaming); public static Object getDefaultValue(JavaType type); protected static boolean isCglibGetCallbacks(AnnotatedMethod am); protected static boolean isGroovyMetaClassSetter(AnnotatedMethod am); protected static boolean isGroovyMetaClassGetter(AnnotatedMethod am); protected static String legacyManglePropertyName(final String basename, final int offset); protected static String stdManglePropertyName(final String basename, final int offset);
44
testNameMangle
```java // Abstract Java Tested Class package com.fasterxml.jackson.databind.util; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; public class BeanUtil { public static String okNameForGetter(AnnotatedMethod am, boolean stdNaming); public static String okNameForRegularGetter(AnnotatedMethod am, String name, boolean stdNaming); public static String okNameForIsGetter(AnnotatedMethod am, String name, boolean stdNaming); @Deprecated // since 2.9, not used any more public static String okNameForSetter(AnnotatedMethod am, boolean stdNaming); public static String okNameForMutator(AnnotatedMethod am, String prefix, boolean stdNaming); public static Object getDefaultValue(JavaType type); protected static boolean isCglibGetCallbacks(AnnotatedMethod am); protected static boolean isGroovyMetaClassSetter(AnnotatedMethod am); protected static boolean isGroovyMetaClassGetter(AnnotatedMethod am); protected static String legacyManglePropertyName(final String basename, final int offset); protected static String stdManglePropertyName(final String basename, final int offset); } // Abstract Java Test Class package com.fasterxml.jackson.databind.util; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.type.TypeFactory; public class BeanUtilTest extends BaseMapTest { public void testNameMangle(); public void testGetDefaultValue(); public void testIsGetter() throws Exception; public void testOkNameForGetter() throws Exception; public void testOkNameForSetter() throws Exception; private void _testIsGetter(String name, String expName) throws Exception; private void _testIsGetter(String name, String expName, boolean useStd) throws Exception; private void _testOkNameForGetter(String name, String expName) throws Exception; private void _testOkNameForGetter(String name, String expName, boolean useStd) throws Exception; private void _testOkNameForSetter(String name, String expName) throws Exception; @SuppressWarnings("deprecation") private void _testOkNameForSetter(String name, String expName, boolean useStd) throws Exception; private AnnotatedMethod _method(Class<?> cls, String name, Class<?>...parameterTypes) throws Exception; public boolean isPrimitive(); public Boolean isWrapper(); public String isNotGetter(); public boolean is(); public String getCallbacks(); public String getMetaClass(); public boolean get(); public void setFoo(); public void notSetter(); public void set(); } ``` You are a professional Java test case writer, please create a test case named `testNameMangle` for the `BeanUtil` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods /********************************************************** */
37
// // Abstract Java Tested Class // package com.fasterxml.jackson.databind.util; // // import java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import com.fasterxml.jackson.annotation.JsonInclude; // import com.fasterxml.jackson.databind.JavaType; // import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; // // // // public class BeanUtil // { // // // public static String okNameForGetter(AnnotatedMethod am, boolean stdNaming); // public static String okNameForRegularGetter(AnnotatedMethod am, String name, // boolean stdNaming); // public static String okNameForIsGetter(AnnotatedMethod am, String name, // boolean stdNaming); // @Deprecated // since 2.9, not used any more // public static String okNameForSetter(AnnotatedMethod am, boolean stdNaming); // public static String okNameForMutator(AnnotatedMethod am, String prefix, // boolean stdNaming); // public static Object getDefaultValue(JavaType type); // protected static boolean isCglibGetCallbacks(AnnotatedMethod am); // protected static boolean isGroovyMetaClassSetter(AnnotatedMethod am); // protected static boolean isGroovyMetaClassGetter(AnnotatedMethod am); // protected static String legacyManglePropertyName(final String basename, final int offset); // protected static String stdManglePropertyName(final String basename, final int offset); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.util; // // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.annotation.JsonInclude; // import com.fasterxml.jackson.databind.BaseMapTest; // import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // public class BeanUtilTest extends BaseMapTest // { // // // public void testNameMangle(); // public void testGetDefaultValue(); // public void testIsGetter() throws Exception; // public void testOkNameForGetter() throws Exception; // public void testOkNameForSetter() throws Exception; // private void _testIsGetter(String name, String expName) throws Exception; // private void _testIsGetter(String name, String expName, boolean useStd) throws Exception; // private void _testOkNameForGetter(String name, String expName) throws Exception; // private void _testOkNameForGetter(String name, String expName, boolean useStd) throws Exception; // private void _testOkNameForSetter(String name, String expName) throws Exception; // @SuppressWarnings("deprecation") // private void _testOkNameForSetter(String name, String expName, boolean useStd) throws Exception; // private AnnotatedMethod _method(Class<?> cls, String name, Class<?>...parameterTypes) throws Exception; // public boolean isPrimitive(); // public Boolean isWrapper(); // public String isNotGetter(); // public boolean is(); // public String getCallbacks(); // public String getMetaClass(); // public boolean get(); // public void setFoo(); // public void notSetter(); // public void set(); // } // You are a professional Java test case writer, please create a test case named `testNameMangle` for the `BeanUtil` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods /********************************************************** */ public void testNameMangle() {
/* /********************************************************** /* Test methods /********************************************************** */
112
com.fasterxml.jackson.databind.util.BeanUtil
src/test/java
```java // Abstract Java Tested Class package com.fasterxml.jackson.databind.util; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; public class BeanUtil { public static String okNameForGetter(AnnotatedMethod am, boolean stdNaming); public static String okNameForRegularGetter(AnnotatedMethod am, String name, boolean stdNaming); public static String okNameForIsGetter(AnnotatedMethod am, String name, boolean stdNaming); @Deprecated // since 2.9, not used any more public static String okNameForSetter(AnnotatedMethod am, boolean stdNaming); public static String okNameForMutator(AnnotatedMethod am, String prefix, boolean stdNaming); public static Object getDefaultValue(JavaType type); protected static boolean isCglibGetCallbacks(AnnotatedMethod am); protected static boolean isGroovyMetaClassSetter(AnnotatedMethod am); protected static boolean isGroovyMetaClassGetter(AnnotatedMethod am); protected static String legacyManglePropertyName(final String basename, final int offset); protected static String stdManglePropertyName(final String basename, final int offset); } // Abstract Java Test Class package com.fasterxml.jackson.databind.util; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.type.TypeFactory; public class BeanUtilTest extends BaseMapTest { public void testNameMangle(); public void testGetDefaultValue(); public void testIsGetter() throws Exception; public void testOkNameForGetter() throws Exception; public void testOkNameForSetter() throws Exception; private void _testIsGetter(String name, String expName) throws Exception; private void _testIsGetter(String name, String expName, boolean useStd) throws Exception; private void _testOkNameForGetter(String name, String expName) throws Exception; private void _testOkNameForGetter(String name, String expName, boolean useStd) throws Exception; private void _testOkNameForSetter(String name, String expName) throws Exception; @SuppressWarnings("deprecation") private void _testOkNameForSetter(String name, String expName, boolean useStd) throws Exception; private AnnotatedMethod _method(Class<?> cls, String name, Class<?>...parameterTypes) throws Exception; public boolean isPrimitive(); public Boolean isWrapper(); public String isNotGetter(); public boolean is(); public String getCallbacks(); public String getMetaClass(); public boolean get(); public void setFoo(); public void notSetter(); public void set(); } ``` You are a professional Java test case writer, please create a test case named `testNameMangle` for the `BeanUtil` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods /********************************************************** */ public void testNameMangle() { ```
public class BeanUtil
package com.fasterxml.jackson.databind.util; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.type.TypeFactory;
public void testNameMangle(); public void testGetDefaultValue(); public void testIsGetter() throws Exception; public void testOkNameForGetter() throws Exception; public void testOkNameForSetter() throws Exception; private void _testIsGetter(String name, String expName) throws Exception; private void _testIsGetter(String name, String expName, boolean useStd) throws Exception; private void _testOkNameForGetter(String name, String expName) throws Exception; private void _testOkNameForGetter(String name, String expName, boolean useStd) throws Exception; private void _testOkNameForSetter(String name, String expName) throws Exception; @SuppressWarnings("deprecation") private void _testOkNameForSetter(String name, String expName, boolean useStd) throws Exception; private AnnotatedMethod _method(Class<?> cls, String name, Class<?>...parameterTypes) throws Exception; public boolean isPrimitive(); public Boolean isWrapper(); public String isNotGetter(); public boolean is(); public String getCallbacks(); public String getMetaClass(); public boolean get(); public void setFoo(); public void notSetter(); public void set();
d2a8b55e34c76fa7d54a0a007cfc8696653fa9aecca00b6092a29f12c40c02e1
[ "com.fasterxml.jackson.databind.util.BeanUtilTest::testNameMangle" ]
public void testNameMangle()
JacksonDatabind
package com.fasterxml.jackson.databind.util; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.type.TypeFactory; public class BeanUtilTest extends BaseMapTest { static class IsGetters { public boolean isPrimitive() { return false; } public Boolean isWrapper() { return false; } public String isNotGetter() { return null; } public boolean is() { return false; } } static class Getters { public String getCallbacks() { return null; } public String getMetaClass() { return null; } public boolean get() { return false; } } static class Setters { public void setFoo() { } public void notSetter() { } public void set() { } } /* /********************************************************** /* Test methods /********************************************************** */ public void testNameMangle() { assertEquals("foo", BeanUtil.legacyManglePropertyName("getFoo", 3)); assertEquals("foo", BeanUtil.stdManglePropertyName("getFoo", 3)); assertEquals("url", BeanUtil.legacyManglePropertyName("getURL", 3)); assertEquals("URL", BeanUtil.stdManglePropertyName("getURL", 3)); } public void testGetDefaultValue() { TypeFactory tf = TypeFactory.defaultInstance(); // For collection/array/Map types, should give `NOT_EMPTY`: assertEquals(JsonInclude.Include.NON_EMPTY, BeanUtil.getDefaultValue(tf.constructType(Map.class))); assertEquals(JsonInclude.Include.NON_EMPTY, BeanUtil.getDefaultValue(tf.constructType(List.class))); assertEquals(JsonInclude.Include.NON_EMPTY, BeanUtil.getDefaultValue(tf.constructType(Object[].class))); // as well as ReferenceTypes, String assertEquals(JsonInclude.Include.NON_EMPTY, BeanUtil.getDefaultValue(tf.constructType(AtomicReference.class))); assertEquals("", BeanUtil.getDefaultValue(tf.constructType(String.class))); // primitive/wrappers have others assertEquals(Integer.valueOf(0), BeanUtil.getDefaultValue(tf.constructType(Integer.class))); // but POJOs have no real default assertNull(BeanUtil.getDefaultValue(tf.constructType(getClass()))); } public void testIsGetter() throws Exception { _testIsGetter("isPrimitive", "primitive"); _testIsGetter("isWrapper", "wrapper"); _testIsGetter("isNotGetter", null); _testIsGetter("is", null); } public void testOkNameForGetter() throws Exception { // mostly chosen to exercise groovy exclusion _testOkNameForGetter("getCallbacks", "callbacks"); _testOkNameForGetter("getMetaClass", "metaClass"); _testOkNameForGetter("get", null); } public void testOkNameForSetter() throws Exception { _testOkNameForSetter("setFoo", "foo"); _testOkNameForSetter("notSetter", null); _testOkNameForSetter("set", null); } /* /********************************************************** /* Helper methods /********************************************************** */ private void _testIsGetter(String name, String expName) throws Exception { _testIsGetter(name, expName, true); _testIsGetter(name, expName, false); } private void _testIsGetter(String name, String expName, boolean useStd) throws Exception { AnnotatedMethod m = _method(IsGetters.class, name); if (expName == null) { assertNull(BeanUtil.okNameForIsGetter(m, name, useStd)); } else { assertEquals(expName, BeanUtil.okNameForIsGetter(m, name, useStd)); } } private void _testOkNameForGetter(String name, String expName) throws Exception { _testOkNameForGetter(name, expName, true); _testOkNameForGetter(name, expName, false); } private void _testOkNameForGetter(String name, String expName, boolean useStd) throws Exception { AnnotatedMethod m = _method(Getters.class, name); if (expName == null) { assertNull(BeanUtil.okNameForGetter(m, useStd)); } else { assertEquals(expName, BeanUtil.okNameForGetter(m, useStd)); } } private void _testOkNameForSetter(String name, String expName) throws Exception { _testOkNameForSetter(name, expName, true); _testOkNameForSetter(name, expName, false); } @SuppressWarnings("deprecation") private void _testOkNameForSetter(String name, String expName, boolean useStd) throws Exception { AnnotatedMethod m = _method(Setters.class, name); if (expName == null) { assertNull(BeanUtil.okNameForSetter(m, useStd)); } else { assertEquals(expName, BeanUtil.okNameForSetter(m, useStd)); } } private AnnotatedMethod _method(Class<?> cls, String name, Class<?>...parameterTypes) throws Exception { return new AnnotatedMethod(null, cls.getMethod(name, parameterTypes), null, null); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/util/BeanUtil.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.BeanUtil", "be_test_function_name": "legacyManglePropertyName", "be_test_function_signature": "(Ljava/lang/String;I)Ljava/lang/String;", "line_numbers": [ "235", "236", "237", "240", "241", "243", "244", "247", "248", "249", "250", "251", "252", "253", "254", "255", "257", "259" ], "method_line_rate": 0.8888888888888888 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/BeanUtil.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.BeanUtil", "be_test_function_name": "stdManglePropertyName", "be_test_function_signature": "(Ljava/lang/String;I)Ljava/lang/String;", "line_numbers": [ "267", "268", "269", "272", "273", "274", "275", "280", "281", "282", "285", "286", "287", "288" ], "method_line_rate": 0.8571428571428571 } ]
public class TestTypeFactory extends BaseMapTest
public void testSimpleTypes() { Class<?>[] classes = new Class<?>[] { boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class, Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, Object.class, Calendar.class, Date.class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); assertSame(clz, tf.constructType(clz).getRawClass()); } }
// private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) // throws IllegalArgumentException; // private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); // public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); // public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; // public JavaType[] findTypeParameters(JavaType type, Class<?> expType); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); // public JavaType moreSpecificType(JavaType type1, JavaType type2); // public JavaType constructType(Type type); // public JavaType constructType(Type type, TypeBindings bindings); // public JavaType constructType(TypeReference<?> typeRef); // @Deprecated // public JavaType constructType(Type type, Class<?> contextClass); // @Deprecated // public JavaType constructType(Type type, JavaType contextType); // public ArrayType constructArrayType(Class<?> elementType); // public ArrayType constructArrayType(JavaType elementType); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // Class<?> elementClass); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // JavaType elementType); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); // public MapType constructMapType(Class<? extends Map> mapClass, // Class<?> keyClass, Class<?> valueClass); // public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); // public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); // public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); // public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); // @Deprecated // public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, // JavaType[] parameterTypes); // public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); // @Deprecated // since 2.8 // public JavaType uncheckedSimpleType(Class<?> cls); // public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); // public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // Class<?>... parameterClasses); // public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); // public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); // public MapType constructRawMapType(Class<? extends Map> mapClass); // public MapLikeType constructRawMapLikeType(Class<?> mapClass); // private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _unknownType(); // protected JavaType _findWellKnownSimple(Class<?> clz); // protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); // protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); // protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, // TypeBindings parentBindings); // protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); // protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); // protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.type; // // import java.lang.reflect.Field; // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.core.type.TypeReference; // import com.fasterxml.jackson.databind.*; // // // // public class TestTypeFactory // extends BaseMapTest // { // // // public void testSimpleTypes(); // public void testArrays(); // public void testProperties(); // public void testIterator(); // @SuppressWarnings("deprecation") // public void testParametricTypes(); // public void testCanonicalNames(); // @SuppressWarnings("serial") // public void testCanonicalWithSpaces(); // public void testCollections(); // public void testCollectionTypesRefined(); // public void testMaps(); // public void testMapTypesRefined(); // public void testTypeGeneralization(); // public void testMapTypesRaw(); // public void testMapTypesAdvanced(); // public void testMapTypesSneaky(); // public void testSneakyFieldTypes() throws Exception; // public void testSneakyBeanProperties() throws Exception; // public void testSneakySelfRefs() throws Exception; // public void testAtomicArrayRefParameters(); // public void testMapEntryResolution(); // public void testRawCollections(); // public void testRawMaps(); // public void testMoreSpecificType(); // public void testCacheClearing(); // public void testRawMapType(); // public <T extends Comparable<T>> T getFoobar(); // } // You are a professional Java test case writer, please create a test case named `testSimpleTypes` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/type/TestTypeFactory.java
package com.fasterxml.jackson.databind.type; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.lang.reflect.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.util.ArrayBuilders; import com.fasterxml.jackson.databind.util.ClassUtil; import com.fasterxml.jackson.databind.util.LRUMap;
private TypeFactory(); protected TypeFactory(LRUMap<Object,JavaType> typeCache); protected TypeFactory(LRUMap<Object,JavaType> typeCache, TypeParser p, TypeModifier[] mods, ClassLoader classLoader); public TypeFactory withModifier(TypeModifier mod); public TypeFactory withClassLoader(ClassLoader classLoader); public TypeFactory withCache(LRUMap<Object,JavaType> cache); public static TypeFactory defaultInstance(); public void clearCache(); public ClassLoader getClassLoader(); public static JavaType unknownType(); public static Class<?> rawClass(Type t); public Class<?> findClass(String className) throws ClassNotFoundException; protected Class<?> classForName(String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException; protected Class<?> classForName(String name) throws ClassNotFoundException; protected Class<?> _findPrimitive(String className); public JavaType constructSpecializedType(JavaType baseType, Class<?> subclass); private TypeBindings _bindingsForSubtype(JavaType baseType, int typeParamCount, Class<?> subclass); private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) throws IllegalArgumentException; private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; public JavaType[] findTypeParameters(JavaType type, Class<?> expType); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); public JavaType moreSpecificType(JavaType type1, JavaType type2); public JavaType constructType(Type type); public JavaType constructType(Type type, TypeBindings bindings); public JavaType constructType(TypeReference<?> typeRef); @Deprecated public JavaType constructType(Type type, Class<?> contextClass); @Deprecated public JavaType constructType(Type type, JavaType contextType); public ArrayType constructArrayType(Class<?> elementType); public ArrayType constructArrayType(JavaType elementType); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); public MapType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass); public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); @Deprecated public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, JavaType[] parameterTypes); public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); @Deprecated // since 2.8 public JavaType uncheckedSimpleType(Class<?> cls); public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, Class<?>... parameterClasses); public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); public MapType constructRawMapType(Class<? extends Map> mapClass); public MapLikeType constructRawMapLikeType(Class<?> mapClass); private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _unknownType(); protected JavaType _findWellKnownSimple(Class<?> clz); protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, TypeBindings parentBindings); protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings);
106
testSimpleTypes
```java private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) throws IllegalArgumentException; private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; public JavaType[] findTypeParameters(JavaType type, Class<?> expType); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); public JavaType moreSpecificType(JavaType type1, JavaType type2); public JavaType constructType(Type type); public JavaType constructType(Type type, TypeBindings bindings); public JavaType constructType(TypeReference<?> typeRef); @Deprecated public JavaType constructType(Type type, Class<?> contextClass); @Deprecated public JavaType constructType(Type type, JavaType contextType); public ArrayType constructArrayType(Class<?> elementType); public ArrayType constructArrayType(JavaType elementType); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); public MapType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass); public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); @Deprecated public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, JavaType[] parameterTypes); public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); @Deprecated // since 2.8 public JavaType uncheckedSimpleType(Class<?> cls); public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, Class<?>... parameterClasses); public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); public MapType constructRawMapType(Class<? extends Map> mapClass); public MapLikeType constructRawMapLikeType(Class<?> mapClass); private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _unknownType(); protected JavaType _findWellKnownSimple(Class<?> clz); protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, TypeBindings parentBindings); protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); } // Abstract Java Test Class package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; public class TestTypeFactory extends BaseMapTest { public void testSimpleTypes(); public void testArrays(); public void testProperties(); public void testIterator(); @SuppressWarnings("deprecation") public void testParametricTypes(); public void testCanonicalNames(); @SuppressWarnings("serial") public void testCanonicalWithSpaces(); public void testCollections(); public void testCollectionTypesRefined(); public void testMaps(); public void testMapTypesRefined(); public void testTypeGeneralization(); public void testMapTypesRaw(); public void testMapTypesAdvanced(); public void testMapTypesSneaky(); public void testSneakyFieldTypes() throws Exception; public void testSneakyBeanProperties() throws Exception; public void testSneakySelfRefs() throws Exception; public void testAtomicArrayRefParameters(); public void testMapEntryResolution(); public void testRawCollections(); public void testRawMaps(); public void testMoreSpecificType(); public void testCacheClearing(); public void testRawMapType(); public <T extends Comparable<T>> T getFoobar(); } ``` You are a professional Java test case writer, please create a test case named `testSimpleTypes` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests /********************************************************** */
83
// private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) // throws IllegalArgumentException; // private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); // public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); // public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; // public JavaType[] findTypeParameters(JavaType type, Class<?> expType); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); // @Deprecated // since 2.7 // public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); // public JavaType moreSpecificType(JavaType type1, JavaType type2); // public JavaType constructType(Type type); // public JavaType constructType(Type type, TypeBindings bindings); // public JavaType constructType(TypeReference<?> typeRef); // @Deprecated // public JavaType constructType(Type type, Class<?> contextClass); // @Deprecated // public JavaType constructType(Type type, JavaType contextType); // public ArrayType constructArrayType(Class<?> elementType); // public ArrayType constructArrayType(JavaType elementType); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // Class<?> elementClass); // public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, // JavaType elementType); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); // public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); // public MapType constructMapType(Class<? extends Map> mapClass, // Class<?> keyClass, Class<?> valueClass); // public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); // public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); // public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); // public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); // @Deprecated // public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, // JavaType[] parameterTypes); // public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); // @Deprecated // since 2.8 // public JavaType uncheckedSimpleType(Class<?> cls); // public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); // public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // JavaType... parameterTypes); // @Deprecated // public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, // Class<?>... parameterClasses); // public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); // public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); // public MapType constructRawMapType(Class<? extends Map> mapClass); // public MapLikeType constructRawMapLikeType(Class<?> mapClass); // private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _unknownType(); // protected JavaType _findWellKnownSimple(Class<?> clz); // protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); // protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); // protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); // protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, // TypeBindings parentBindings); // protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); // protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); // protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.type; // // import java.lang.reflect.Field; // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.core.type.TypeReference; // import com.fasterxml.jackson.databind.*; // // // // public class TestTypeFactory // extends BaseMapTest // { // // // public void testSimpleTypes(); // public void testArrays(); // public void testProperties(); // public void testIterator(); // @SuppressWarnings("deprecation") // public void testParametricTypes(); // public void testCanonicalNames(); // @SuppressWarnings("serial") // public void testCanonicalWithSpaces(); // public void testCollections(); // public void testCollectionTypesRefined(); // public void testMaps(); // public void testMapTypesRefined(); // public void testTypeGeneralization(); // public void testMapTypesRaw(); // public void testMapTypesAdvanced(); // public void testMapTypesSneaky(); // public void testSneakyFieldTypes() throws Exception; // public void testSneakyBeanProperties() throws Exception; // public void testSneakySelfRefs() throws Exception; // public void testAtomicArrayRefParameters(); // public void testMapEntryResolution(); // public void testRawCollections(); // public void testRawMaps(); // public void testMoreSpecificType(); // public void testCacheClearing(); // public void testRawMapType(); // public <T extends Comparable<T>> T getFoobar(); // } // You are a professional Java test case writer, please create a test case named `testSimpleTypes` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests /********************************************************** */ public void testSimpleTypes() {
/* /********************************************************** /* Unit tests /********************************************************** */
112
com.fasterxml.jackson.databind.type.TypeFactory
src/test/java
```java private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType) throws IllegalArgumentException; private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act); public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass); public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException; public JavaType[] findTypeParameters(JavaType type, Class<?> expType); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType, TypeBindings bindings); @Deprecated // since 2.7 public JavaType[] findTypeParameters(Class<?> clz, Class<?> expType); public JavaType moreSpecificType(JavaType type1, JavaType type2); public JavaType constructType(Type type); public JavaType constructType(Type type, TypeBindings bindings); public JavaType constructType(TypeReference<?> typeRef); @Deprecated public JavaType constructType(Type type, Class<?> contextClass); @Deprecated public JavaType constructType(Type type, JavaType contextType); public ArrayType constructArrayType(Class<?> elementType); public ArrayType constructArrayType(JavaType elementType); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass); public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass); public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType); public MapType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass); public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType); public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass); public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType); public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes); @Deprecated public JavaType constructSimpleType(Class<?> rawType, Class<?> parameterTarget, JavaType[] parameterTypes); public JavaType constructReferenceType(Class<?> rawType, JavaType referredType); @Deprecated // since 2.8 public JavaType uncheckedSimpleType(Class<?> cls); public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses); public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, JavaType... parameterTypes); @Deprecated public JavaType constructParametrizedType(Class<?> parametrized, Class<?> parametersFor, Class<?>... parameterClasses); public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass); public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass); public MapType constructRawMapType(Class<? extends Map> mapClass); public MapLikeType constructRawMapLikeType(Class<?> mapClass); private JavaType _mapType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); private JavaType _referenceType(Class<?> rawClass, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _unknownType(); protected JavaType _findWellKnownSimple(Class<?> clz); protected JavaType _fromAny(ClassStack context, Type type, TypeBindings bindings); protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings); protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType[] _resolveSuperInterfaces(ClassStack context, Class<?> rawType, TypeBindings parentBindings); protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); protected JavaType _fromParamType(ClassStack context, ParameterizedType ptype, TypeBindings parentBindings); protected JavaType _fromArrayType(ClassStack context, GenericArrayType type, TypeBindings bindings); protected JavaType _fromVariable(ClassStack context, TypeVariable<?> var, TypeBindings bindings); protected JavaType _fromWildcard(ClassStack context, WildcardType type, TypeBindings bindings); } // Abstract Java Test Class package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; public class TestTypeFactory extends BaseMapTest { public void testSimpleTypes(); public void testArrays(); public void testProperties(); public void testIterator(); @SuppressWarnings("deprecation") public void testParametricTypes(); public void testCanonicalNames(); @SuppressWarnings("serial") public void testCanonicalWithSpaces(); public void testCollections(); public void testCollectionTypesRefined(); public void testMaps(); public void testMapTypesRefined(); public void testTypeGeneralization(); public void testMapTypesRaw(); public void testMapTypesAdvanced(); public void testMapTypesSneaky(); public void testSneakyFieldTypes() throws Exception; public void testSneakyBeanProperties() throws Exception; public void testSneakySelfRefs() throws Exception; public void testAtomicArrayRefParameters(); public void testMapEntryResolution(); public void testRawCollections(); public void testRawMaps(); public void testMoreSpecificType(); public void testCacheClearing(); public void testRawMapType(); public <T extends Comparable<T>> T getFoobar(); } ``` You are a professional Java test case writer, please create a test case named `testSimpleTypes` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests /********************************************************** */ public void testSimpleTypes() { ```
@SuppressWarnings({"rawtypes" }) public final class TypeFactory implements java.io.Serializable
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*;
public void testSimpleTypes(); public void testArrays(); public void testProperties(); public void testIterator(); @SuppressWarnings("deprecation") public void testParametricTypes(); public void testCanonicalNames(); @SuppressWarnings("serial") public void testCanonicalWithSpaces(); public void testCollections(); public void testCollectionTypesRefined(); public void testMaps(); public void testMapTypesRefined(); public void testTypeGeneralization(); public void testMapTypesRaw(); public void testMapTypesAdvanced(); public void testMapTypesSneaky(); public void testSneakyFieldTypes() throws Exception; public void testSneakyBeanProperties() throws Exception; public void testSneakySelfRefs() throws Exception; public void testAtomicArrayRefParameters(); public void testMapEntryResolution(); public void testRawCollections(); public void testRawMaps(); public void testMoreSpecificType(); public void testCacheClearing(); public void testRawMapType(); public <T extends Comparable<T>> T getFoobar();
d55b8b4a9e2f30749242902fd5c41596b22e8a1ab9470e6c4097279088b645b1
[ "com.fasterxml.jackson.databind.type.TestTypeFactory::testSimpleTypes" ]
private static final long serialVersionUID = 1L; private final static JavaType[] NO_TYPES = new JavaType[0]; protected final static TypeFactory instance = new TypeFactory(); protected final static TypeBindings EMPTY_BINDINGS = TypeBindings.emptyBindings(); private final static Class<?> CLS_STRING = String.class; private final static Class<?> CLS_OBJECT = Object.class; private final static Class<?> CLS_COMPARABLE = Comparable.class; private final static Class<?> CLS_CLASS = Class.class; private final static Class<?> CLS_ENUM = Enum.class; private final static Class<?> CLS_BOOL = Boolean.TYPE; private final static Class<?> CLS_INT = Integer.TYPE; private final static Class<?> CLS_LONG = Long.TYPE; protected final static SimpleType CORE_TYPE_BOOL = new SimpleType(CLS_BOOL); protected final static SimpleType CORE_TYPE_INT = new SimpleType(CLS_INT); protected final static SimpleType CORE_TYPE_LONG = new SimpleType(CLS_LONG); protected final static SimpleType CORE_TYPE_STRING = new SimpleType(CLS_STRING); protected final static SimpleType CORE_TYPE_OBJECT = new SimpleType(CLS_OBJECT); protected final static SimpleType CORE_TYPE_COMPARABLE = new SimpleType(CLS_COMPARABLE); protected final static SimpleType CORE_TYPE_ENUM = new SimpleType(CLS_ENUM); protected final static SimpleType CORE_TYPE_CLASS = new SimpleType(CLS_CLASS); protected final LRUMap<Object,JavaType> _typeCache; protected final TypeModifier[] _modifiers; protected final TypeParser _parser; protected final ClassLoader _classLoader;
public void testSimpleTypes()
JacksonDatabind
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; /** * Simple tests to verify that the {@link TypeFactory} constructs * type information as expected. */ public class TestTypeFactory extends BaseMapTest { /* /********************************************************** /* Helper types /********************************************************** */ enum EnumForCanonical { YES, NO; } static class SingleArgGeneric<X> { } abstract static class MyMap extends IntermediateMap<String,Long> { } abstract static class IntermediateMap<K,V> implements Map<K,V> { } abstract static class MyList extends IntermediateList<Long> { } abstract static class IntermediateList<E> implements List<E> { } @SuppressWarnings("serial") static class GenericList<T> extends ArrayList<T> { } interface MapInterface extends Cloneable, IntermediateInterfaceMap<String> { } interface IntermediateInterfaceMap<FOO> extends Map<FOO, Integer> { } @SuppressWarnings("serial") static class MyStringIntMap extends MyStringXMap<Integer> { } @SuppressWarnings("serial") static class MyStringXMap<V> extends HashMap<String,V> { } // And one more, now with obfuscated type names; essentially it's just Map<Int,Long> static abstract class IntLongMap extends XLongMap<Integer> { } // trick here is that V now refers to key type, not value type static abstract class XLongMap<V> extends XXMap<V,Long> { } static abstract class XXMap<K,V> implements Map<K,V> { } static class SneakyBean { public IntLongMap intMap; public MyList longList; } static class SneakyBean2 { // self-reference; should be resolved as "Comparable<Object>" public <T extends Comparable<T>> T getFoobar() { return null; } } @SuppressWarnings("serial") public static class LongValuedMap<K> extends HashMap<K, Long> { } static class StringLongMapBean { public LongValuedMap<String> value; } static class StringListBean { public GenericList<String> value; } static class CollectionLike<E> { } static class MapLike<K,V> { } static class Wrapper1297<T> { public T content; } /* /********************************************************** /* Unit tests /********************************************************** */ public void testSimpleTypes() { Class<?>[] classes = new Class<?>[] { boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class, Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, Object.class, Calendar.class, Date.class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); assertSame(clz, tf.constructType(clz).getRawClass()); } } public void testArrays() { Class<?>[] classes = new Class<?>[] { boolean[].class, byte[].class, char[].class, short[].class, int[].class, long[].class, float[].class, double[].class, String[].class, Object[].class, Calendar[].class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); Class<?> elemType = clz.getComponentType(); assertSame(clz, tf.constructArrayType(elemType).getRawClass()); } } // [databind#810]: Fake Map type for Properties as <String,String> public void testProperties() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(Properties.class); assertEquals(MapType.class, t.getClass()); assertSame(Properties.class, t.getRawClass()); MapType mt = (MapType) t; // so far so good. But how about parameterization? assertSame(String.class, mt.getKeyType().getRawClass()); assertSame(String.class, mt.getContentType().getRawClass()); } public void testIterator() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(new TypeReference<Iterator<String>>() { }); assertEquals(SimpleType.class, t.getClass()); assertSame(Iterator.class, t.getRawClass()); assertEquals(1, t.containedTypeCount()); assertEquals(tf.constructType(String.class), t.containedType(0)); assertNull(t.containedType(1)); } /** * Test for verifying that parametric types can be constructed * programmatically */ @SuppressWarnings("deprecation") public void testParametricTypes() { TypeFactory tf = TypeFactory.defaultInstance(); // first, simple class based JavaType t = tf.constructParametrizedType(ArrayList.class, Collection.class, String.class); // ArrayList<String> assertEquals(CollectionType.class, t.getClass()); JavaType strC = tf.constructType(String.class); assertEquals(1, t.containedTypeCount()); assertEquals(strC, t.containedType(0)); assertNull(t.containedType(1)); // Then using JavaType JavaType t2 = tf.constructParametrizedType(Map.class, Map.class, strC, t); // Map<String,ArrayList<String>> // should actually produce a MapType assertEquals(MapType.class, t2.getClass()); assertEquals(2, t2.containedTypeCount()); assertEquals(strC, t2.containedType(0)); assertEquals(t, t2.containedType(1)); assertNull(t2.containedType(2)); // and then custom generic type as well JavaType custom = tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, String.class); assertEquals(SimpleType.class, custom.getClass()); assertEquals(1, custom.containedTypeCount()); assertEquals(strC, custom.containedType(0)); assertNull(custom.containedType(1)); // should also be able to access variable name: assertEquals("X", custom.containedTypeName(0)); // And finally, ensure that we can't create invalid combinations try { // Maps must take 2 type parameters, not just one tf.constructParametrizedType(Map.class, Map.class, strC); } catch (IllegalArgumentException e) { verifyException(e, "Cannot create TypeBindings for class java.util.Map"); } try { // Type only accepts one type param tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, strC, strC); } catch (IllegalArgumentException e) { verifyException(e, "Cannot create TypeBindings for class "); } } /** * Test for checking that canonical name handling works ok */ public void testCanonicalNames() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(java.util.Calendar.class); String can = t.toCanonical(); assertEquals("java.util.Calendar", can); assertEquals(t, tf.constructFromCanonical(can)); // Generic maps and collections will default to Object.class if type-erased t = tf.constructType(java.util.ArrayList.class); can = t.toCanonical(); assertEquals("java.util.ArrayList<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); t = tf.constructType(java.util.TreeMap.class); can = t.toCanonical(); assertEquals("java.util.TreeMap<java.lang.Object,java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); // And then EnumMap (actual use case for us) t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class); can = t.toCanonical(); assertEquals("java.util.EnumMap<com.fasterxml.jackson.databind.type.TestTypeFactory$EnumForCanonical,java.lang.String>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#2109]: also ReferenceTypes t = tf.constructType(new TypeReference<AtomicReference<Long>>() { }); can = t.toCanonical(); assertEquals("java.util.concurrent.atomic.AtomicReference<java.lang.Long>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#1941]: allow "raw" types too t = tf.constructFromCanonical("java.util.List"); assertEquals(List.class, t.getRawClass()); assertEquals(CollectionType.class, t.getClass()); // 01-Mar-2018, tatu: not 100% should we expect type parameters here... // But currently we do NOT get any /* assertEquals(1, t.containedTypeCount()); assertEquals(Object.class, t.containedType(0).getRawClass()); */ assertEquals(Object.class, t.getContentType().getRawClass()); can = t.toCanonical(); assertEquals("java.util.List<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); } // [databind#1768] @SuppressWarnings("serial") public void testCanonicalWithSpaces() { TypeFactory tf = TypeFactory.defaultInstance(); Object objects = new TreeMap<Object, Object>() { }; // to get subtype String reflectTypeName = objects.getClass().getGenericSuperclass().toString(); JavaType t1 = tf.constructType(objects.getClass().getGenericSuperclass()); // This will throw an Exception if you don't remove all white spaces from the String. JavaType t2 = tf.constructFromCanonical(reflectTypeName); assertNotNull(t2); assertEquals(t2, t1); } /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */ public void testCollections() { // Ok, first: let's test what happens when we pass 'raw' Collection: TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(ArrayList.class); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); // And then the proper way t = tf.constructType(new TypeReference<ArrayList<String>>() { }); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); JavaType elemType = ((CollectionType) t).getContentType(); assertNotNull(elemType); assertSame(SimpleType.class, elemType.getClass()); assertSame(String.class, elemType.getRawClass()); // And alternate method too t = tf.constructCollectionType(ArrayList.class, String.class); assertEquals(CollectionType.class, t.getClass()); assertSame(String.class, ((CollectionType) t).getContentType().getRawClass()); } // since 2.7 public void testCollectionTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<List<Long>>() { }); assertEquals(List.class, type.getRawClass()); assertEquals(Long.class, type.getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, ArrayList.class); assertEquals(ArrayList.class, subtype.getRawClass()); assertEquals(Long.class, subtype.getContentType().getRawClass()); // but with refinement, should have non-null super class JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(AbstractList.class, superType.getRawClass()); } /* /********************************************************** /* Unit tests: map type parameter resolution /********************************************************** */ public void testMaps() { TypeFactory tf = newTypeFactory(); // Ok, first: let's test what happens when we pass 'raw' Map: JavaType t = tf.constructType(HashMap.class); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); // Then explicit construction t = tf.constructMapType(TreeMap.class, String.class, Integer.class); assertEquals(MapType.class, t.getClass()); assertSame(String.class, ((MapType) t).getKeyType().getRawClass()); assertSame(Integer.class, ((MapType) t).getContentType().getRawClass()); // And then with TypeReference t = tf.constructType(new TypeReference<HashMap<String,Integer>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); MapType mt = (MapType) t; assertEquals(tf.constructType(String.class), mt.getKeyType()); assertEquals(tf.constructType(Integer.class), mt.getContentType()); t = tf.constructType(new TypeReference<LongValuedMap<Boolean>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(LongValuedMap.class, t.getRawClass()); mt = (MapType) t; assertEquals(tf.constructType(Boolean.class), mt.getKeyType()); assertEquals(tf.constructType(Long.class), mt.getContentType()); JavaType type = tf.constructType(new TypeReference<Map<String,Boolean>>() { }); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Boolean.class), mapType.getContentType()); } // since 2.7 public void testMapTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<Map<String,List<Integer>>>() { }); MapType mapType = (MapType) type; assertEquals(Map.class, mapType.getRawClass()); assertEquals(String.class, mapType.getKeyType().getRawClass()); assertEquals(List.class, mapType.getContentType().getRawClass()); assertEquals(Integer.class, mapType.getContentType().getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, LinkedHashMap.class); assertEquals(LinkedHashMap.class, subtype.getRawClass()); assertEquals(String.class, subtype.getKeyType().getRawClass()); assertEquals(List.class, subtype.getContentType().getRawClass()); assertEquals(Integer.class, subtype.getContentType().getContentType().getRawClass()); // but with refinement, should have non-null super class JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(HashMap.class, superType.getRawClass()); // which also should have proper typing assertEquals(String.class, superType.getKeyType().getRawClass()); assertEquals(List.class, superType.getContentType().getRawClass()); assertEquals(Integer.class, superType.getContentType().getContentType().getRawClass()); } public void testTypeGeneralization() { TypeFactory tf = newTypeFactory(); MapType t = tf.constructMapType(HashMap.class, String.class, Long.class); JavaType superT = tf.constructGeneralizedType(t, Map.class); assertEquals(String.class, superT.getKeyType().getRawClass()); assertEquals(Long.class, superT.getContentType().getRawClass()); assertSame(t, tf.constructGeneralizedType(t, HashMap.class)); // plus check there is super/sub relationship try { tf.constructGeneralizedType(t, TreeMap.class); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "not a super-type of"); } } public void testMapTypesRaw() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(HashMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Object.class), mapType.getKeyType()); assertEquals(tf.constructType(Object.class), mapType.getContentType()); } public void testMapTypesAdvanced() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(MyMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); type = tf.constructType(MapInterface.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); type = tf.constructType(MyStringIntMap.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); } /** * Specific test to verify that complicate name mangling schemes * do not fool type resolver */ public void testMapTypesSneaky() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(IntLongMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); } /** * Plus sneaky types may be found via introspection as well. */ public void testSneakyFieldTypes() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Field field = SneakyBean.class.getDeclaredField("intMap"); JavaType type = tf.constructType(field.getGenericType()); assertTrue(type instanceof MapType); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); field = SneakyBean.class.getDeclaredField("longList"); type = tf.constructType(field.getGenericType()); assertTrue(type instanceof CollectionType); CollectionType collectionType = (CollectionType) type; assertEquals(tf.constructType(Long.class), collectionType.getContentType()); } /** * Looks like type handling actually differs for properties, too. */ public void testSneakyBeanProperties() throws Exception { ObjectMapper mapper = new ObjectMapper(); StringLongMapBean bean = mapper.readValue("{\"value\":{\"a\":123}}", StringLongMapBean.class); assertNotNull(bean); Map<String,Long> map = bean.value; assertEquals(1, map.size()); assertEquals(Long.valueOf(123), map.get("a")); StringListBean bean2 = mapper.readValue("{\"value\":[\"...\"]}", StringListBean.class); assertNotNull(bean2); List<String> list = bean2.value; assertSame(GenericList.class, list.getClass()); assertEquals(1, list.size()); assertEquals("...", list.get(0)); } public void testSneakySelfRefs() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(new SneakyBean2()); assertEquals("{\"foobar\":null}", json); } /* /********************************************************** /* Unit tests: handling of specific JDK types /********************************************************** */ public void testAtomicArrayRefParameters() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(new TypeReference<AtomicReference<long[]>>() { }); JavaType[] params = tf.findTypeParameters(type, AtomicReference.class); assertNotNull(params); assertEquals(1, params.length); assertEquals(tf.constructType(long[].class), params[0]); } static abstract class StringIntMapEntry implements Map.Entry<String,Integer> { } public void testMapEntryResolution() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(StringIntMapEntry.class); JavaType mapEntryType = t.findSuperType(Map.Entry.class); assertNotNull(mapEntryType); assertTrue(mapEntryType.hasGenericTypes()); assertEquals(2, mapEntryType.containedTypeCount()); assertEquals(String.class, mapEntryType.containedType(0).getRawClass()); assertEquals(Integer.class, mapEntryType.containedType(1).getRawClass()); } /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */ public void testRawCollections() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawCollectionType(ArrayList.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawCollectionLikeType(CollectionLike.class); // must have type vars assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawCollectionLikeType(String.class); assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } public void testRawMaps() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawMapType(HashMap.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawMapLikeType(MapLike.class); // must have type vars assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawMapLikeType(String.class); assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } /* /********************************************************** /* Unit tests: other /********************************************************** */ public void testMoreSpecificType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t1 = tf.constructCollectionType(Collection.class, Object.class); JavaType t2 = tf.constructCollectionType(List.class, Object.class); assertSame(t2, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); t1 = tf.constructType(Double.class); t2 = tf.constructType(Number.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t1, tf.moreSpecificType(t2, t1)); // and then unrelated, return first t1 = tf.constructType(Double.class); t2 = tf.constructType(String.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); } // [databind#489] public void testCacheClearing() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); assertEquals(0, tf._typeCache.size()); tf.constructType(getClass()); // 19-Oct-2015, tatu: This is pretty fragile but assertEquals(6, tf._typeCache.size()); tf.clearCache(); assertEquals(0, tf._typeCache.size()); } // for [databind#1297] public void testRawMapType() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); // to get a new copy JavaType type = tf.constructParametricType(Wrapper1297.class, Map.class); assertNotNull(type); assertEquals(Wrapper1297.class, type.getRawClass()); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_findWellKnownSimple", "be_test_function_signature": "(Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1188", "1189", "1190", "1191", "1193", "1194", "1196" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromAny", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/reflect/Type;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1215", "1217", "1220", "1221", "1223", "1225", "1227", "1228", "1230", "1231", "1233", "1234", "1237", "1242", "1243", "1244", "1245", "1247", "1248", "1249", "1250", "1254", "1257" ], "method_line_rate": 0.2608695652173913 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromClass", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1267", "1268", "1269", "1273", "1274", "1276", "1278", "1279", "1280", "1284", "1285", "1287", "1288", "1290", "1291", "1292", "1295", "1299", "1300", "1308", "1309", "1310", "1313", "1314", "1318", "1319", "1324", "1325", "1328", "1329", "1330", "1331", "1332", "1334", "1339", "1342", "1343", "1345" ], "method_line_rate": 0.8421052631578947 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromParamType", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/reflect/ParameterizedType;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1426", "1430", "1431", "1433", "1434", "1436", "1437", "1443", "1444", "1447", "1448", "1450", "1451", "1452", "1454", "1456" ], "method_line_rate": 0.25 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromWellKnownClass", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;Lcom/fasterxml/jackson/databind/JavaType;[Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1380", "1381", "1385", "1386", "1388", "1389", "1392", "1393", "1399" ], "method_line_rate": 0.5555555555555556 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_fromWellKnownInterface", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;Lcom/fasterxml/jackson/databind/JavaType;[Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1407", "1409", "1410", "1411", "1412", "1415" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_newSimpleType", "be_test_function_signature": "(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;Lcom/fasterxml/jackson/databind/JavaType;[Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1168" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_resolveSuperClass", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1350", "1351", "1352", "1354" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "_resolveSuperInterfaces", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/type/ClassStack;Ljava/lang/Class;Lcom/fasterxml/jackson/databind/type/TypeBindings;)[Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1359", "1360", "1361", "1363", "1364", "1365", "1366", "1367", "1369" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "constructType", "be_test_function_signature": "(Ljava/lang/reflect/Type;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "631" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/type/TypeFactory.java", "be_test_class_name": "com.fasterxml.jackson.databind.type.TypeFactory", "be_test_function_name": "defaultInstance", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/type/TypeFactory;", "line_numbers": [ "211" ], "method_line_rate": 1 } ]
public class SerialUtilitiesTests extends TestCase
public void testRectangle2DDoubleSerialization() { Rectangle2D r1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); Rectangle2D r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(r1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); r2 = (Rectangle2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(r1, r2)); }
// // Abstract Java Tested Class // package org.jfree.chart.util; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Graphics2D; // import java.awt.Image; // import java.awt.Paint; // import java.awt.Shape; // import java.awt.Stroke; // import java.awt.geom.Arc2D; // import java.awt.geom.Ellipse2D; // import java.awt.geom.GeneralPath; // import java.awt.geom.Line2D; // import java.awt.geom.PathIterator; // import java.awt.geom.Point2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.io.Serializable; // import java.text.AttributedCharacterIterator; // import java.text.AttributedString; // import java.text.CharacterIterator; // import java.util.HashMap; // import java.util.Map; // import javax.imageio.ImageIO; // import org.jfree.chart.encoders.EncoderUtil; // import org.jfree.chart.encoders.ImageFormat; // // // // public class SerialUtilities { // // // private SerialUtilities(); // public static boolean isSerializable(Class c); // public static Paint readPaint(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public static void writePaint(Paint paint, ObjectOutputStream stream) // throws IOException; // public static Stroke readStroke(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public static void writeStroke(Stroke stroke, ObjectOutputStream stream) // throws IOException; // public static Shape readShape(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public static void writeShape(Shape shape, ObjectOutputStream stream) // throws IOException; // public static Point2D readPoint2D(ObjectInputStream stream) // throws IOException; // public static void writePoint2D(Point2D p, ObjectOutputStream stream) // throws IOException; // public static AttributedString readAttributedString( // ObjectInputStream stream) throws IOException, // ClassNotFoundException; // public static void writeAttributedString(AttributedString as, // ObjectOutputStream stream) throws IOException; // public static Image readImage(ObjectInputStream stream) // throws IOException; // public static void writeImage(Image image, ObjectOutputStream stream) // throws IOException; // } // // // Abstract Java Test Class // package org.jfree.chart.util.junit; // // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Paint; // import java.awt.TexturePaint; // import java.awt.font.TextAttribute; // import java.awt.geom.Arc2D; // import java.awt.geom.GeneralPath; // import java.awt.geom.Line2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.text.AttributedString; // import javax.swing.UIManager; // import javax.swing.plaf.ColorUIResource; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.util.AttributedStringUtilities; // import org.jfree.chart.util.SerialUtilities; // import org.jfree.chart.util.ShapeUtilities; // // // // public class SerialUtilitiesTests extends TestCase { // // // public static Test suite(); // public SerialUtilitiesTests(final String name); // public void testIsSerializable(); // public void testColorSerialization(); // public void testColorUIResourceSerialization(); // public void testGradientPaintSerialization(); // public void testTexturePaintSerialization(); // public void testLine2DFloatSerialization(); // public void testLine2DDoubleSerialization(); // public void testRectangle2DFloatSerialization(); // public void testRectangle2DDoubleSerialization(); // public void testArc2DFloatSerialization(); // public void testArc2DDoubleSerialization(); // public void testGeneralPathSerialization(); // public void testAttributedStringSerialization1(); // public void testAttributedStringSerialization2(); // public void testAttributedStringSerialization3(); // } // You are a professional Java test case writer, please create a test case named `testRectangle2DDoubleSerialization` for the `SerialUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Serialize a <code>Rectangle2D.Double</code> instance and check that it * can be deserialized correctly. */
tests/org/jfree/chart/util/junit/SerialUtilitiesTests.java
package org.jfree.chart.util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.jfree.chart.encoders.EncoderUtil; import org.jfree.chart.encoders.ImageFormat;
private SerialUtilities(); public static boolean isSerializable(Class c); public static Paint readPaint(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writePaint(Paint paint, ObjectOutputStream stream) throws IOException; public static Stroke readStroke(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeStroke(Stroke stroke, ObjectOutputStream stream) throws IOException; public static Shape readShape(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeShape(Shape shape, ObjectOutputStream stream) throws IOException; public static Point2D readPoint2D(ObjectInputStream stream) throws IOException; public static void writePoint2D(Point2D p, ObjectOutputStream stream) throws IOException; public static AttributedString readAttributedString( ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeAttributedString(AttributedString as, ObjectOutputStream stream) throws IOException; public static Image readImage(ObjectInputStream stream) throws IOException; public static void writeImage(Image image, ObjectOutputStream stream) throws IOException;
324
testRectangle2DDoubleSerialization
```java // Abstract Java Tested Class package org.jfree.chart.util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.jfree.chart.encoders.EncoderUtil; import org.jfree.chart.encoders.ImageFormat; public class SerialUtilities { private SerialUtilities(); public static boolean isSerializable(Class c); public static Paint readPaint(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writePaint(Paint paint, ObjectOutputStream stream) throws IOException; public static Stroke readStroke(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeStroke(Stroke stroke, ObjectOutputStream stream) throws IOException; public static Shape readShape(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeShape(Shape shape, ObjectOutputStream stream) throws IOException; public static Point2D readPoint2D(ObjectInputStream stream) throws IOException; public static void writePoint2D(Point2D p, ObjectOutputStream stream) throws IOException; public static AttributedString readAttributedString( ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeAttributedString(AttributedString as, ObjectOutputStream stream) throws IOException; public static Image readImage(ObjectInputStream stream) throws IOException; public static void writeImage(Image image, ObjectOutputStream stream) throws IOException; } // Abstract Java Test Class package org.jfree.chart.util.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.awt.TexturePaint; import java.awt.font.TextAttribute; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.AttributedString; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.util.AttributedStringUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.ShapeUtilities; public class SerialUtilitiesTests extends TestCase { public static Test suite(); public SerialUtilitiesTests(final String name); public void testIsSerializable(); public void testColorSerialization(); public void testColorUIResourceSerialization(); public void testGradientPaintSerialization(); public void testTexturePaintSerialization(); public void testLine2DFloatSerialization(); public void testLine2DDoubleSerialization(); public void testRectangle2DFloatSerialization(); public void testRectangle2DDoubleSerialization(); public void testArc2DFloatSerialization(); public void testArc2DDoubleSerialization(); public void testGeneralPathSerialization(); public void testAttributedStringSerialization1(); public void testAttributedStringSerialization2(); public void testAttributedStringSerialization3(); } ``` You are a professional Java test case writer, please create a test case named `testRectangle2DDoubleSerialization` for the `SerialUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Serialize a <code>Rectangle2D.Double</code> instance and check that it * can be deserialized correctly. */
305
// // Abstract Java Tested Class // package org.jfree.chart.util; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Graphics2D; // import java.awt.Image; // import java.awt.Paint; // import java.awt.Shape; // import java.awt.Stroke; // import java.awt.geom.Arc2D; // import java.awt.geom.Ellipse2D; // import java.awt.geom.GeneralPath; // import java.awt.geom.Line2D; // import java.awt.geom.PathIterator; // import java.awt.geom.Point2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.io.Serializable; // import java.text.AttributedCharacterIterator; // import java.text.AttributedString; // import java.text.CharacterIterator; // import java.util.HashMap; // import java.util.Map; // import javax.imageio.ImageIO; // import org.jfree.chart.encoders.EncoderUtil; // import org.jfree.chart.encoders.ImageFormat; // // // // public class SerialUtilities { // // // private SerialUtilities(); // public static boolean isSerializable(Class c); // public static Paint readPaint(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public static void writePaint(Paint paint, ObjectOutputStream stream) // throws IOException; // public static Stroke readStroke(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public static void writeStroke(Stroke stroke, ObjectOutputStream stream) // throws IOException; // public static Shape readShape(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // public static void writeShape(Shape shape, ObjectOutputStream stream) // throws IOException; // public static Point2D readPoint2D(ObjectInputStream stream) // throws IOException; // public static void writePoint2D(Point2D p, ObjectOutputStream stream) // throws IOException; // public static AttributedString readAttributedString( // ObjectInputStream stream) throws IOException, // ClassNotFoundException; // public static void writeAttributedString(AttributedString as, // ObjectOutputStream stream) throws IOException; // public static Image readImage(ObjectInputStream stream) // throws IOException; // public static void writeImage(Image image, ObjectOutputStream stream) // throws IOException; // } // // // Abstract Java Test Class // package org.jfree.chart.util.junit; // // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Paint; // import java.awt.TexturePaint; // import java.awt.font.TextAttribute; // import java.awt.geom.Arc2D; // import java.awt.geom.GeneralPath; // import java.awt.geom.Line2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.text.AttributedString; // import javax.swing.UIManager; // import javax.swing.plaf.ColorUIResource; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.util.AttributedStringUtilities; // import org.jfree.chart.util.SerialUtilities; // import org.jfree.chart.util.ShapeUtilities; // // // // public class SerialUtilitiesTests extends TestCase { // // // public static Test suite(); // public SerialUtilitiesTests(final String name); // public void testIsSerializable(); // public void testColorSerialization(); // public void testColorUIResourceSerialization(); // public void testGradientPaintSerialization(); // public void testTexturePaintSerialization(); // public void testLine2DFloatSerialization(); // public void testLine2DDoubleSerialization(); // public void testRectangle2DFloatSerialization(); // public void testRectangle2DDoubleSerialization(); // public void testArc2DFloatSerialization(); // public void testArc2DDoubleSerialization(); // public void testGeneralPathSerialization(); // public void testAttributedStringSerialization1(); // public void testAttributedStringSerialization2(); // public void testAttributedStringSerialization3(); // } // You are a professional Java test case writer, please create a test case named `testRectangle2DDoubleSerialization` for the `SerialUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Serialize a <code>Rectangle2D.Double</code> instance and check that it * can be deserialized correctly. */ public void testRectangle2DDoubleSerialization() {
/** * Serialize a <code>Rectangle2D.Double</code> instance and check that it * can be deserialized correctly. */
1
org.jfree.chart.util.SerialUtilities
tests
```java // Abstract Java Tested Class package org.jfree.chart.util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.jfree.chart.encoders.EncoderUtil; import org.jfree.chart.encoders.ImageFormat; public class SerialUtilities { private SerialUtilities(); public static boolean isSerializable(Class c); public static Paint readPaint(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writePaint(Paint paint, ObjectOutputStream stream) throws IOException; public static Stroke readStroke(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeStroke(Stroke stroke, ObjectOutputStream stream) throws IOException; public static Shape readShape(ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeShape(Shape shape, ObjectOutputStream stream) throws IOException; public static Point2D readPoint2D(ObjectInputStream stream) throws IOException; public static void writePoint2D(Point2D p, ObjectOutputStream stream) throws IOException; public static AttributedString readAttributedString( ObjectInputStream stream) throws IOException, ClassNotFoundException; public static void writeAttributedString(AttributedString as, ObjectOutputStream stream) throws IOException; public static Image readImage(ObjectInputStream stream) throws IOException; public static void writeImage(Image image, ObjectOutputStream stream) throws IOException; } // Abstract Java Test Class package org.jfree.chart.util.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.awt.TexturePaint; import java.awt.font.TextAttribute; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.AttributedString; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.util.AttributedStringUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.ShapeUtilities; public class SerialUtilitiesTests extends TestCase { public static Test suite(); public SerialUtilitiesTests(final String name); public void testIsSerializable(); public void testColorSerialization(); public void testColorUIResourceSerialization(); public void testGradientPaintSerialization(); public void testTexturePaintSerialization(); public void testLine2DFloatSerialization(); public void testLine2DDoubleSerialization(); public void testRectangle2DFloatSerialization(); public void testRectangle2DDoubleSerialization(); public void testArc2DFloatSerialization(); public void testArc2DDoubleSerialization(); public void testGeneralPathSerialization(); public void testAttributedStringSerialization1(); public void testAttributedStringSerialization2(); public void testAttributedStringSerialization3(); } ``` You are a professional Java test case writer, please create a test case named `testRectangle2DDoubleSerialization` for the `SerialUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Serialize a <code>Rectangle2D.Double</code> instance and check that it * can be deserialized correctly. */ public void testRectangle2DDoubleSerialization() { ```
public class SerialUtilities
package org.jfree.chart.util.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.awt.TexturePaint; import java.awt.font.TextAttribute; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.AttributedString; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.util.AttributedStringUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.ShapeUtilities;
public static Test suite(); public SerialUtilitiesTests(final String name); public void testIsSerializable(); public void testColorSerialization(); public void testColorUIResourceSerialization(); public void testGradientPaintSerialization(); public void testTexturePaintSerialization(); public void testLine2DFloatSerialization(); public void testLine2DDoubleSerialization(); public void testRectangle2DFloatSerialization(); public void testRectangle2DDoubleSerialization(); public void testArc2DFloatSerialization(); public void testArc2DDoubleSerialization(); public void testGeneralPathSerialization(); public void testAttributedStringSerialization1(); public void testAttributedStringSerialization2(); public void testAttributedStringSerialization3();
d5eebc1a9a5c82af6f930170bdea3ca2b66187cdd0fbfac6b3f0fa9b68a82379
[ "org.jfree.chart.util.junit.SerialUtilitiesTests::testRectangle2DDoubleSerialization" ]
public void testRectangle2DDoubleSerialization()
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * SerialUtilitiesTests.java * ------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 02-Jun-2008 : Copied from JCommon (DG); * */ package org.jfree.chart.util.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.awt.TexturePaint; import java.awt.font.TextAttribute; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.AttributedString; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.util.AttributedStringUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.ShapeUtilities; /** * Tests for the {@link SerialUtilities} class. */ public class SerialUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(SerialUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public SerialUtilitiesTests(final String name) { super(name); } /** * Tests the isSerializable(Class) method for some common cases. */ public void testIsSerializable() { assertTrue(SerialUtilities.isSerializable(Color.class)); assertTrue(SerialUtilities.isSerializable(ColorUIResource.class)); assertFalse(SerialUtilities.isSerializable(GradientPaint.class)); assertFalse(SerialUtilities.isSerializable(TexturePaint.class)); } /** * Serialize a <code>Color</code> and check that it can be deserialized * correctly. */ public void testColorSerialization() { Paint p1 = Color.blue; Paint p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(p1, p2); } /** * Serialize a <code>ColorUIResource</code> and check that it can be * deserialized correctly. */ public void testColorUIResourceSerialization() { Paint p1 = UIManager.getColor("Panel.background"); Paint p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(p1, p2); } /** * Serialize a <code>GradientPaint</code>, restore it, and check for * equality. */ public void testGradientPaintSerialization() { Paint p1 = new GradientPaint(0.0f, 0.0f, Color.blue, 100.0f, 200.0f, Color.red); Paint p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { e.printStackTrace(); } // we want to check that the two objects are equal, but can't rely on // GradientPaint's equals() method because it is just the default // method inherited from Object... GradientPaint gp1 = (GradientPaint) p1; GradientPaint gp2 = (GradientPaint) p2; assertEquals(gp1.getColor1(), gp2.getColor1()); assertEquals(gp1.getPoint1(), gp2.getPoint1()); assertEquals(gp1.getColor2(), gp2.getColor2()); assertEquals(gp1.getPoint2(), gp2.getPoint2()); assertEquals(gp1.isCyclic(), gp2.isCyclic()); } /** * Serialize a <code>TexturePaint</code>, restore it, and check for * equality. Since this class is not serializable, we expect null as the * result. */ public void testTexturePaintSerialization() { Paint p1 = new TexturePaint( new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB), new Rectangle2D.Double(0, 0, 5, 5)); Paint p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertNull(p2); } /** * Serialize a <code>Line2D.Float</code> instance, and check that it can be * deserialized correctly. */ public void testLine2DFloatSerialization() { Line2D l1 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); Line2D l2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(l1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); l2 = (Line2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(l1, l2)); } /** * Serialize a <code>Line2D.Double</code> instance and check that it can be * deserialized correctly. */ public void testLine2DDoubleSerialization() { Line2D l1 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); Line2D l2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(l1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); l2 = (Line2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(l1, l2)); } /** * Serialize a <code>Rectangle2D.Float</code> instance, and check that it * can be deserialized correctly. */ public void testRectangle2DFloatSerialization() { Rectangle2D r1 = new Rectangle2D.Float(1.0f, 2.0f, 3.0f, 4.0f); Rectangle2D r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(r1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); r2 = (Rectangle2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(r1, r2)); } /** * Serialize a <code>Rectangle2D.Double</code> instance and check that it * can be deserialized correctly. */ public void testRectangle2DDoubleSerialization() { Rectangle2D r1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); Rectangle2D r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(r1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); r2 = (Rectangle2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(r1, r2)); } /** * Serialize an <code>Arc2D.Float</code> instance and check that it * can be deserialized correctly. */ public void testArc2DFloatSerialization() { Arc2D a1 = new Arc2D.Float(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, Arc2D.PIE); Arc2D a2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(a1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); a2 = (Arc2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(a1, a2)); } /** * Serialize an <code>Arc2D.Double</code> instance and check that it * can be deserialized correctly. */ public void testArc2DDoubleSerialization() { Arc2D a1 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); Arc2D a2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(a1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); a2 = (Arc2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(a1, a2)); } /** * Some checks for the serialization of a GeneralPath instance. */ public void testGeneralPathSerialization() { GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); GeneralPath g2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(g1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); g2 = (GeneralPath) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(g1, g2)); } /** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization1() { AttributedString s1 = new AttributedString(""); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); } /** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization2() { AttributedString s1 = new AttributedString("ABC"); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); } /** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization3() { AttributedString s1 = new AttributedString("ABC"); s1.addAttribute(TextAttribute.LANGUAGE, "English"); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); } }
[ { "be_test_class_file": "org/jfree/chart/util/SerialUtilities.java", "be_test_class_name": "org.jfree.chart.util.SerialUtilities", "be_test_function_name": "class$", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/Class;", "line_numbers": [ "101" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/util/SerialUtilities.java", "be_test_class_name": "org.jfree.chart.util.SerialUtilities", "be_test_function_name": "readShape", "be_test_function_signature": "(Ljava/io/ObjectInputStream;)Ljava/awt/Shape;", "line_numbers": [ "272", "273", "275", "276", "277", "278", "279", "280", "281", "282", "283", "284", "285", "286", "287", "288", "289", "290", "291", "292", "293", "294", "295", "296", "297", "298", "299", "300", "301", "302", "303", "304", "305", "306", "307", "308", "309", "310", "311", "312", "313", "314", "315", "316", "317", "319", "321", "322", "324", "325", "327", "329", "331", "332", "334", "335", "337", "340", "341", "342", "343", "344", "346", "349" ], "method_line_rate": 0.21875 }, { "be_test_class_file": "org/jfree/chart/util/SerialUtilities.java", "be_test_class_name": "org.jfree.chart.util.SerialUtilities", "be_test_function_name": "writeShape", "be_test_function_signature": "(Ljava/awt/Shape;Ljava/io/ObjectOutputStream;)V", "line_numbers": [ "364", "365", "367", "368", "369", "370", "371", "372", "373", "374", "375", "376", "377", "378", "379", "380", "381", "382", "383", "384", "385", "386", "387", "388", "389", "390", "391", "392", "393", "394", "395", "396", "397", "398", "399", "400", "401", "402", "403", "404", "405", "406", "407", "408", "409", "410", "411", "414", "415", "417", "418", "419", "420", "421", "423", "424", "428", "430" ], "method_line_rate": 0.22413793103448276 } ]
public class PowellOptimizerTest
@Test public void testRelativeToleranceOnScaledValues() { final MultivariateFunction func = new MultivariateFunction() { public double value(double[] x) { final double a = x[0] - 1; final double b = x[1] - 1; return a * a * FastMath.sqrt(FastMath.abs(a)) + b * b + 1; } }; int dim = 2; final double[] minPoint = new double[dim]; for (int i = 0; i < dim; i++) { minPoint[i] = 1; } double[] init = new double[dim]; // Initial is far from minimum. for (int i = 0; i < dim; i++) { init[i] = minPoint[i] - 20; } final double relTol = 1e-10; final int maxEval = 1000; // Very small absolute tolerance to rely solely on the relative // tolerance as a stopping criterion final PowellOptimizer optim = new PowellOptimizer(relTol, 1e-100); final PointValuePair funcResult = optim.optimize(new MaxEval(maxEval), new ObjectiveFunction(func), GoalType.MINIMIZE, new InitialGuess(init)); final double funcValue = func.value(funcResult.getPoint()); final int funcEvaluations = optim.getEvaluations(); final double scale = 1e10; final MultivariateFunction funcScaled = new MultivariateFunction() { public double value(double[] x) { return scale * func.value(x); } }; final PointValuePair funcScaledResult = optim.optimize(new MaxEval(maxEval), new ObjectiveFunction(funcScaled), GoalType.MINIMIZE, new InitialGuess(init)); final double funcScaledValue = funcScaled.value(funcScaledResult.getPoint()); final int funcScaledEvaluations = optim.getEvaluations(); // Check that both minima provide the same objective funciton values, // within the relative function tolerance. Assert.assertEquals(1, funcScaledValue / (scale * funcValue), relTol); // Check that the numbers of evaluations are the same. Assert.assertEquals(funcEvaluations, funcScaledEvaluations); }
// // Abstract Java Tested Class // package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; // // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.MathArrays; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.exception.NumberIsTooSmallException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.MathUnsupportedOperationException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; // import org.apache.commons.math3.optim.MaxEval; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.optim.ConvergenceChecker; // import org.apache.commons.math3.optim.nonlinear.scalar.MultivariateOptimizer; // import org.apache.commons.math3.optim.univariate.BracketFinder; // import org.apache.commons.math3.optim.univariate.BrentOptimizer; // import org.apache.commons.math3.optim.univariate.UnivariatePointValuePair; // import org.apache.commons.math3.optim.univariate.SimpleUnivariateValueChecker; // import org.apache.commons.math3.optim.univariate.SearchInterval; // import org.apache.commons.math3.optim.univariate.UnivariateObjectiveFunction; // // // // public class PowellOptimizer // extends MultivariateOptimizer { // private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); // private final double relativeThreshold; // private final double absoluteThreshold; // private final LineSearch line; // // public PowellOptimizer(double rel, // double abs, // ConvergenceChecker<PointValuePair> checker); // public PowellOptimizer(double rel, // double abs, // double lineRel, // double lineAbs, // ConvergenceChecker<PointValuePair> checker); // public PowellOptimizer(double rel, // double abs); // public PowellOptimizer(double rel, // double abs, // double lineRel, // double lineAbs); // @Override // protected PointValuePair doOptimize(); // private double[][] newPointAndDirection(double[] p, // double[] d, // double optimum); // private void checkParameters(); // LineSearch(double rel, // double abs); // public UnivariatePointValuePair search(final double[] p, final double[] d); // public double value(double alpha); // } // // // Abstract Java Test Class // package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; // // import org.apache.commons.math3.analysis.MultivariateFunction; // import org.apache.commons.math3.analysis.SumSincFunction; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.optim.InitialGuess; // import org.apache.commons.math3.optim.MaxEval; // import org.apache.commons.math3.optim.SimpleBounds; // import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; // import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction; // import org.apache.commons.math3.exception.MathUnsupportedOperationException; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public class PowellOptimizerTest { // // // @Test(expected=MathUnsupportedOperationException.class) // public void testBoundsUnsupported(); // @Test // public void testSumSinc(); // @Test // public void testQuadratic(); // @Test // public void testMaximizeQuadratic(); // @Test // public void testRelativeToleranceOnScaledValues(); // private void doTest(MultivariateFunction func, // double[] optimum, // double[] init, // GoalType goal, // double fTol, // double pointTol); // private void doTest(MultivariateFunction func, // double[] optimum, // double[] init, // GoalType goal, // double fTol, // double fLineTol, // double pointTol); // public double value(double[] x); // public double value(double[] x); // public double value(double[] x); // public double value(double[] x); // } // You are a professional Java test case writer, please create a test case named `testRelativeToleranceOnScaledValues` for the `PowellOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Ensure that we do not increase the number of function evaluations when * the function values are scaled up. * Note that the tolerances parameters passed to the constructor must * still hold sensible values because they are used to set the line search * tolerances. */
src/test/java/org/apache/commons/math3/optim/nonlinear/scalar/noderiv/PowellOptimizerTest.java
package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.ConvergenceChecker; import org.apache.commons.math3.optim.nonlinear.scalar.MultivariateOptimizer; import org.apache.commons.math3.optim.univariate.BracketFinder; import org.apache.commons.math3.optim.univariate.BrentOptimizer; import org.apache.commons.math3.optim.univariate.UnivariatePointValuePair; import org.apache.commons.math3.optim.univariate.SimpleUnivariateValueChecker; import org.apache.commons.math3.optim.univariate.SearchInterval; import org.apache.commons.math3.optim.univariate.UnivariateObjectiveFunction;
public PowellOptimizer(double rel, double abs, ConvergenceChecker<PointValuePair> checker); public PowellOptimizer(double rel, double abs, double lineRel, double lineAbs, ConvergenceChecker<PointValuePair> checker); public PowellOptimizer(double rel, double abs); public PowellOptimizer(double rel, double abs, double lineRel, double lineAbs); @Override protected PointValuePair doOptimize(); private double[][] newPointAndDirection(double[] p, double[] d, double optimum); private void checkParameters(); LineSearch(double rel, double abs); public UnivariatePointValuePair search(final double[] p, final double[] d); public double value(double alpha);
202
testRelativeToleranceOnScaledValues
```java // Abstract Java Tested Class package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.ConvergenceChecker; import org.apache.commons.math3.optim.nonlinear.scalar.MultivariateOptimizer; import org.apache.commons.math3.optim.univariate.BracketFinder; import org.apache.commons.math3.optim.univariate.BrentOptimizer; import org.apache.commons.math3.optim.univariate.UnivariatePointValuePair; import org.apache.commons.math3.optim.univariate.SimpleUnivariateValueChecker; import org.apache.commons.math3.optim.univariate.SearchInterval; import org.apache.commons.math3.optim.univariate.UnivariateObjectiveFunction; public class PowellOptimizer extends MultivariateOptimizer { private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); private final double relativeThreshold; private final double absoluteThreshold; private final LineSearch line; public PowellOptimizer(double rel, double abs, ConvergenceChecker<PointValuePair> checker); public PowellOptimizer(double rel, double abs, double lineRel, double lineAbs, ConvergenceChecker<PointValuePair> checker); public PowellOptimizer(double rel, double abs); public PowellOptimizer(double rel, double abs, double lineRel, double lineAbs); @Override protected PointValuePair doOptimize(); private double[][] newPointAndDirection(double[] p, double[] d, double optimum); private void checkParameters(); LineSearch(double rel, double abs); public UnivariatePointValuePair search(final double[] p, final double[] d); public double value(double alpha); } // Abstract Java Test Class package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.analysis.SumSincFunction; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.InitialGuess; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.SimpleBounds; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public class PowellOptimizerTest { @Test(expected=MathUnsupportedOperationException.class) public void testBoundsUnsupported(); @Test public void testSumSinc(); @Test public void testQuadratic(); @Test public void testMaximizeQuadratic(); @Test public void testRelativeToleranceOnScaledValues(); private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double pointTol); private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double fLineTol, double pointTol); public double value(double[] x); public double value(double[] x); public double value(double[] x); public double value(double[] x); } ``` You are a professional Java test case writer, please create a test case named `testRelativeToleranceOnScaledValues` for the `PowellOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Ensure that we do not increase the number of function evaluations when * the function values are scaled up. * Note that the tolerances parameters passed to the constructor must * still hold sensible values because they are used to set the line search * tolerances. */
146
// // Abstract Java Tested Class // package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; // // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.MathArrays; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.exception.NumberIsTooSmallException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.MathUnsupportedOperationException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; // import org.apache.commons.math3.optim.MaxEval; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.optim.ConvergenceChecker; // import org.apache.commons.math3.optim.nonlinear.scalar.MultivariateOptimizer; // import org.apache.commons.math3.optim.univariate.BracketFinder; // import org.apache.commons.math3.optim.univariate.BrentOptimizer; // import org.apache.commons.math3.optim.univariate.UnivariatePointValuePair; // import org.apache.commons.math3.optim.univariate.SimpleUnivariateValueChecker; // import org.apache.commons.math3.optim.univariate.SearchInterval; // import org.apache.commons.math3.optim.univariate.UnivariateObjectiveFunction; // // // // public class PowellOptimizer // extends MultivariateOptimizer { // private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); // private final double relativeThreshold; // private final double absoluteThreshold; // private final LineSearch line; // // public PowellOptimizer(double rel, // double abs, // ConvergenceChecker<PointValuePair> checker); // public PowellOptimizer(double rel, // double abs, // double lineRel, // double lineAbs, // ConvergenceChecker<PointValuePair> checker); // public PowellOptimizer(double rel, // double abs); // public PowellOptimizer(double rel, // double abs, // double lineRel, // double lineAbs); // @Override // protected PointValuePair doOptimize(); // private double[][] newPointAndDirection(double[] p, // double[] d, // double optimum); // private void checkParameters(); // LineSearch(double rel, // double abs); // public UnivariatePointValuePair search(final double[] p, final double[] d); // public double value(double alpha); // } // // // Abstract Java Test Class // package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; // // import org.apache.commons.math3.analysis.MultivariateFunction; // import org.apache.commons.math3.analysis.SumSincFunction; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.optim.InitialGuess; // import org.apache.commons.math3.optim.MaxEval; // import org.apache.commons.math3.optim.SimpleBounds; // import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; // import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction; // import org.apache.commons.math3.exception.MathUnsupportedOperationException; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public class PowellOptimizerTest { // // // @Test(expected=MathUnsupportedOperationException.class) // public void testBoundsUnsupported(); // @Test // public void testSumSinc(); // @Test // public void testQuadratic(); // @Test // public void testMaximizeQuadratic(); // @Test // public void testRelativeToleranceOnScaledValues(); // private void doTest(MultivariateFunction func, // double[] optimum, // double[] init, // GoalType goal, // double fTol, // double pointTol); // private void doTest(MultivariateFunction func, // double[] optimum, // double[] init, // GoalType goal, // double fTol, // double fLineTol, // double pointTol); // public double value(double[] x); // public double value(double[] x); // public double value(double[] x); // public double value(double[] x); // } // You are a professional Java test case writer, please create a test case named `testRelativeToleranceOnScaledValues` for the `PowellOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Ensure that we do not increase the number of function evaluations when * the function values are scaled up. * Note that the tolerances parameters passed to the constructor must * still hold sensible values because they are used to set the line search * tolerances. */ @Test public void testRelativeToleranceOnScaledValues() {
/** * Ensure that we do not increase the number of function evaluations when * the function values are scaled up. * Note that the tolerances parameters passed to the constructor must * still hold sensible values because they are used to set the line search * tolerances. */
1
org.apache.commons.math3.optim.nonlinear.scalar.noderiv.PowellOptimizer
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.ConvergenceChecker; import org.apache.commons.math3.optim.nonlinear.scalar.MultivariateOptimizer; import org.apache.commons.math3.optim.univariate.BracketFinder; import org.apache.commons.math3.optim.univariate.BrentOptimizer; import org.apache.commons.math3.optim.univariate.UnivariatePointValuePair; import org.apache.commons.math3.optim.univariate.SimpleUnivariateValueChecker; import org.apache.commons.math3.optim.univariate.SearchInterval; import org.apache.commons.math3.optim.univariate.UnivariateObjectiveFunction; public class PowellOptimizer extends MultivariateOptimizer { private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); private final double relativeThreshold; private final double absoluteThreshold; private final LineSearch line; public PowellOptimizer(double rel, double abs, ConvergenceChecker<PointValuePair> checker); public PowellOptimizer(double rel, double abs, double lineRel, double lineAbs, ConvergenceChecker<PointValuePair> checker); public PowellOptimizer(double rel, double abs); public PowellOptimizer(double rel, double abs, double lineRel, double lineAbs); @Override protected PointValuePair doOptimize(); private double[][] newPointAndDirection(double[] p, double[] d, double optimum); private void checkParameters(); LineSearch(double rel, double abs); public UnivariatePointValuePair search(final double[] p, final double[] d); public double value(double alpha); } // Abstract Java Test Class package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.analysis.SumSincFunction; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.InitialGuess; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.SimpleBounds; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public class PowellOptimizerTest { @Test(expected=MathUnsupportedOperationException.class) public void testBoundsUnsupported(); @Test public void testSumSinc(); @Test public void testQuadratic(); @Test public void testMaximizeQuadratic(); @Test public void testRelativeToleranceOnScaledValues(); private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double pointTol); private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double fLineTol, double pointTol); public double value(double[] x); public double value(double[] x); public double value(double[] x); public double value(double[] x); } ``` You are a professional Java test case writer, please create a test case named `testRelativeToleranceOnScaledValues` for the `PowellOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Ensure that we do not increase the number of function evaluations when * the function values are scaled up. * Note that the tolerances parameters passed to the constructor must * still hold sensible values because they are used to set the line search * tolerances. */ @Test public void testRelativeToleranceOnScaledValues() { ```
public class PowellOptimizer extends MultivariateOptimizer
package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.analysis.SumSincFunction; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.InitialGuess; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.SimpleBounds; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test;
@Test(expected=MathUnsupportedOperationException.class) public void testBoundsUnsupported(); @Test public void testSumSinc(); @Test public void testQuadratic(); @Test public void testMaximizeQuadratic(); @Test public void testRelativeToleranceOnScaledValues(); private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double pointTol); private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double fLineTol, double pointTol); public double value(double[] x); public double value(double[] x); public double value(double[] x); public double value(double[] x);
d7277214b6da65cdff7c560aaf3249fb7cfc47ba30f5cd576fd6c92a9e34d1d8
[ "org.apache.commons.math3.optim.nonlinear.scalar.noderiv.PowellOptimizerTest::testRelativeToleranceOnScaledValues" ]
private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); private final double relativeThreshold; private final double absoluteThreshold; private final LineSearch line;
@Test public void testRelativeToleranceOnScaledValues()
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.optim.nonlinear.scalar.noderiv; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.analysis.SumSincFunction; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.InitialGuess; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.SimpleBounds; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Test for {@link PowellOptimizer}. */ public class PowellOptimizerTest { @Test(expected=MathUnsupportedOperationException.class) public void testBoundsUnsupported() { final MultivariateFunction func = new SumSincFunction(-1); final PowellOptimizer optim = new PowellOptimizer(1e-8, 1e-5, 1e-4, 1e-4); optim.optimize(new MaxEval(100), new ObjectiveFunction(func), GoalType.MINIMIZE, new InitialGuess(new double[] { -3, 0 }), new SimpleBounds(new double[] { -5, -1 }, new double[] { 5, 1 })); } @Test public void testSumSinc() { final MultivariateFunction func = new SumSincFunction(-1); int dim = 2; final double[] minPoint = new double[dim]; for (int i = 0; i < dim; i++) { minPoint[i] = 0; } double[] init = new double[dim]; // Initial is minimum. for (int i = 0; i < dim; i++) { init[i] = minPoint[i]; } doTest(func, minPoint, init, GoalType.MINIMIZE, 1e-9, 1e-9); // Initial is far from minimum. for (int i = 0; i < dim; i++) { init[i] = minPoint[i] + 3; } doTest(func, minPoint, init, GoalType.MINIMIZE, 1e-9, 1e-5); // More stringent line search tolerance enhances the precision // of the result. doTest(func, minPoint, init, GoalType.MINIMIZE, 1e-9, 1e-9, 1e-7); } @Test public void testQuadratic() { final MultivariateFunction func = new MultivariateFunction() { public double value(double[] x) { final double a = x[0] - 1; final double b = x[1] - 1; return a * a + b * b + 1; } }; int dim = 2; final double[] minPoint = new double[dim]; for (int i = 0; i < dim; i++) { minPoint[i] = 1; } double[] init = new double[dim]; // Initial is minimum. for (int i = 0; i < dim; i++) { init[i] = minPoint[i]; } doTest(func, minPoint, init, GoalType.MINIMIZE, 1e-9, 1e-8); // Initial is far from minimum. for (int i = 0; i < dim; i++) { init[i] = minPoint[i] - 20; } doTest(func, minPoint, init, GoalType.MINIMIZE, 1e-9, 1e-8); } @Test public void testMaximizeQuadratic() { final MultivariateFunction func = new MultivariateFunction() { public double value(double[] x) { final double a = x[0] - 1; final double b = x[1] - 1; return -a * a - b * b + 1; } }; int dim = 2; final double[] maxPoint = new double[dim]; for (int i = 0; i < dim; i++) { maxPoint[i] = 1; } double[] init = new double[dim]; // Initial is minimum. for (int i = 0; i < dim; i++) { init[i] = maxPoint[i]; } doTest(func, maxPoint, init, GoalType.MAXIMIZE, 1e-9, 1e-8); // Initial is far from minimum. for (int i = 0; i < dim; i++) { init[i] = maxPoint[i] - 20; } doTest(func, maxPoint, init, GoalType.MAXIMIZE, 1e-9, 1e-8); } /** * Ensure that we do not increase the number of function evaluations when * the function values are scaled up. * Note that the tolerances parameters passed to the constructor must * still hold sensible values because they are used to set the line search * tolerances. */ @Test public void testRelativeToleranceOnScaledValues() { final MultivariateFunction func = new MultivariateFunction() { public double value(double[] x) { final double a = x[0] - 1; final double b = x[1] - 1; return a * a * FastMath.sqrt(FastMath.abs(a)) + b * b + 1; } }; int dim = 2; final double[] minPoint = new double[dim]; for (int i = 0; i < dim; i++) { minPoint[i] = 1; } double[] init = new double[dim]; // Initial is far from minimum. for (int i = 0; i < dim; i++) { init[i] = minPoint[i] - 20; } final double relTol = 1e-10; final int maxEval = 1000; // Very small absolute tolerance to rely solely on the relative // tolerance as a stopping criterion final PowellOptimizer optim = new PowellOptimizer(relTol, 1e-100); final PointValuePair funcResult = optim.optimize(new MaxEval(maxEval), new ObjectiveFunction(func), GoalType.MINIMIZE, new InitialGuess(init)); final double funcValue = func.value(funcResult.getPoint()); final int funcEvaluations = optim.getEvaluations(); final double scale = 1e10; final MultivariateFunction funcScaled = new MultivariateFunction() { public double value(double[] x) { return scale * func.value(x); } }; final PointValuePair funcScaledResult = optim.optimize(new MaxEval(maxEval), new ObjectiveFunction(funcScaled), GoalType.MINIMIZE, new InitialGuess(init)); final double funcScaledValue = funcScaled.value(funcScaledResult.getPoint()); final int funcScaledEvaluations = optim.getEvaluations(); // Check that both minima provide the same objective funciton values, // within the relative function tolerance. Assert.assertEquals(1, funcScaledValue / (scale * funcValue), relTol); // Check that the numbers of evaluations are the same. Assert.assertEquals(funcEvaluations, funcScaledEvaluations); } /** * @param func Function to optimize. * @param optimum Expected optimum. * @param init Starting point. * @param goal Minimization or maximization. * @param fTol Tolerance (relative error on the objective function) for * "Powell" algorithm. * @param pointTol Tolerance for checking that the optimum is correct. */ private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double pointTol) { final PowellOptimizer optim = new PowellOptimizer(fTol, Math.ulp(1d)); final PointValuePair result = optim.optimize(new MaxEval(1000), new ObjectiveFunction(func), goal, new InitialGuess(init)); final double[] point = result.getPoint(); for (int i = 0, dim = optimum.length; i < dim; i++) { Assert.assertEquals("found[" + i + "]=" + point[i] + " value=" + result.getValue(), optimum[i], point[i], pointTol); } } /** * @param func Function to optimize. * @param optimum Expected optimum. * @param init Starting point. * @param goal Minimization or maximization. * @param fTol Tolerance (relative error on the objective function) for * "Powell" algorithm. * @param fLineTol Tolerance (relative error on the objective function) * for the internal line search algorithm. * @param pointTol Tolerance for checking that the optimum is correct. */ private void doTest(MultivariateFunction func, double[] optimum, double[] init, GoalType goal, double fTol, double fLineTol, double pointTol) { final PowellOptimizer optim = new PowellOptimizer(fTol, Math.ulp(1d), fLineTol, Math.ulp(1d)); final PointValuePair result = optim.optimize(new MaxEval(1000), new ObjectiveFunction(func), goal, new InitialGuess(init)); final double[] point = result.getPoint(); for (int i = 0, dim = optimum.length; i < dim; i++) { Assert.assertEquals("found[" + i + "]=" + point[i] + " value=" + result.getValue(), optimum[i], point[i], pointTol); } Assert.assertTrue(optim.getIterations() > 0); } }
[ { "be_test_class_file": "org/apache/commons/math3/optim/nonlinear/scalar/noderiv/PowellOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optim.nonlinear.scalar.noderiv.PowellOptimizer", "be_test_function_name": "access$000", "be_test_function_signature": "(Lorg/apache/commons/math3/optim/nonlinear/scalar/noderiv/PowellOptimizer;[D)D", "line_numbers": [ "65" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/optim/nonlinear/scalar/noderiv/PowellOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optim.nonlinear.scalar.noderiv.PowellOptimizer", "be_test_function_name": "checkParameters", "be_test_function_signature": "()V", "line_numbers": [ "373", "375", "377" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/optim/nonlinear/scalar/noderiv/PowellOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optim.nonlinear.scalar.noderiv.PowellOptimizer", "be_test_function_name": "doOptimize", "be_test_function_signature": "()Lorg/apache/commons/math3/optim/PointValuePair;", "line_numbers": [ "174", "176", "177", "178", "180", "181", "182", "185", "188", "189", "190", "192", "194", "195", "196", "197", "198", "200", "201", "203", "205", "206", "207", "208", "209", "211", "212", "213", "218", "222", "223", "224", "225", "227", "228", "229", "231", "235", "236", "237", "238", "239", "242", "243", "245", "246", "247", "248", "249", "250", "252", "253", "254", "255", "256", "257", "259", "260", "261", "264" ], "method_line_rate": 0.9666666666666667 }, { "be_test_class_file": "org/apache/commons/math3/optim/nonlinear/scalar/noderiv/PowellOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optim.nonlinear.scalar.noderiv.PowellOptimizer", "be_test_function_name": "newPointAndDirection", "be_test_function_signature": "([D[DD)[[D", "line_numbers": [ "280", "281", "282", "283", "284", "285", "288", "289", "290", "292" ], "method_line_rate": 1 } ]
public class TypeCheckTest extends CompilerTypeTestCase
public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); }
// public void testLends3() throws Exception; // public void testLends4() throws Exception; // public void testLends5() throws Exception; // public void testLends6() throws Exception; // public void testLends7() throws Exception; // public void testLends8() throws Exception; // public void testLends9() throws Exception; // public void testLends10() throws Exception; // public void testLends11() throws Exception; // public void testDeclaredNativeTypeEquality() throws Exception; // public void testUndefinedVar() throws Exception; // public void testFlowScopeBug1() throws Exception; // public void testFlowScopeBug2() throws Exception; // public void testAddSingletonGetter(); // public void testTypeCheckStandaloneAST() throws Exception; // public void testUpdateParameterTypeOnClosure() throws Exception; // public void testTemplatedThisType1() throws Exception; // public void testTemplatedThisType2() throws Exception; // public void testTemplateType1() throws Exception; // public void testTemplateType2() throws Exception; // public void testTemplateType3() throws Exception; // public void testTemplateType4() throws Exception; // public void testTemplateType5() throws Exception; // public void testTemplateType6() throws Exception; // public void testTemplateType7() throws Exception; // public void testTemplateType8() throws Exception; // public void testTemplateType9() throws Exception; // public void testTemplateType10() throws Exception; // public void testTemplateType11() throws Exception; // public void testTemplateType12() throws Exception; // public void testTemplateType13() throws Exception; // public void testTemplateType14() throws Exception; // public void testTemplateType15() throws Exception; // public void testTemplateType16() throws Exception; // public void testTemplateType17() throws Exception; // public void testTemplateType18() throws Exception; // public void testTemplateType19() throws Exception; // public void testTemplateType20() throws Exception; // public void testTemplateTypeWithUnresolvedType() throws Exception; // public void testTemplateTypeWithTypeDef1a() throws Exception; // public void testTemplateTypeWithTypeDef1b() throws Exception; // public void testTemplateTypeWithTypeDef2a() throws Exception; // public void testTemplateTypeWithTypeDef2b() throws Exception; // public void testTemplateTypeWithTypeDef2c() throws Exception; // public void testTemplateTypeWithTypeDef2d() throws Exception; // public void testTemplatedFunctionInUnion1() throws Exception; // public void testTemplateTypeRecursion1() throws Exception; // public void testTemplateTypeRecursion2() throws Exception; // public void testTemplateTypeRecursion3() throws Exception; // public void disable_testBadTemplateType4() throws Exception; // public void disable_testBadTemplateType5() throws Exception; // public void disable_testFunctionLiteralUndefinedThisArgument() // throws Exception; // public void testFunctionLiteralDefinedThisArgument() throws Exception; // public void testFunctionLiteralDefinedThisArgument2() throws Exception; // public void testFunctionLiteralUnreadNullThisArgument() throws Exception; // public void testUnionTemplateThisType() throws Exception; // public void testActiveXObject() throws Exception; // public void testRecordType1() throws Exception; // public void testRecordType2() throws Exception; // public void testRecordType3() throws Exception; // public void testRecordType4() throws Exception; // public void testRecordType5() throws Exception; // public void testRecordType6() throws Exception; // public void testRecordType7() throws Exception; // public void testRecordType8() throws Exception; // public void testDuplicateRecordFields1() throws Exception; // public void testDuplicateRecordFields2() throws Exception; // public void testMultipleExtendsInterface1() throws Exception; // public void testMultipleExtendsInterface2() throws Exception; // public void testMultipleExtendsInterface3() throws Exception; // public void testMultipleExtendsInterface4() throws Exception; // public void testMultipleExtendsInterface5() throws Exception; // public void testMultipleExtendsInterface6() throws Exception; // public void testMultipleExtendsInterfaceAssignment() throws Exception; // public void testMultipleExtendsInterfaceParamPass() throws Exception; // public void testBadMultipleExtendsClass() throws Exception; // public void testInterfaceExtendsResolution() throws Exception; // public void testPropertyCanBeDefinedInObject() throws Exception; // private void checkObjectType(ObjectType objectType, String propertyName, // JSType expectedType); // public void testExtendedInterfacePropertiesCompatibility1() throws Exception; // public void testExtendedInterfacePropertiesCompatibility2() throws Exception; // public void testExtendedInterfacePropertiesCompatibility3() throws Exception; // public void testExtendedInterfacePropertiesCompatibility4() throws Exception; // public void testExtendedInterfacePropertiesCompatibility5() throws Exception; // public void testExtendedInterfacePropertiesCompatibility6() throws Exception; // public void testExtendedInterfacePropertiesCompatibility7() throws Exception; // public void testExtendedInterfacePropertiesCompatibility8() throws Exception; // public void testExtendedInterfacePropertiesCompatibility9() throws Exception; // public void testGenerics1() throws Exception; // public void testFilter0() // throws Exception; // public void testFilter1() // throws Exception; // public void testFilter2() // throws Exception; // public void testFilter3() // throws Exception; // public void testBackwardsInferenceGoogArrayFilter1() // throws Exception; // public void testBackwardsInferenceGoogArrayFilter2() throws Exception; // public void testBackwardsInferenceGoogArrayFilter3() throws Exception; // public void testBackwardsInferenceGoogArrayFilter4() throws Exception; // public void testCatchExpression1() throws Exception; // public void testCatchExpression2() throws Exception; // public void testTemplatized1() throws Exception; // public void testTemplatized2() throws Exception; // public void testTemplatized3() throws Exception; // public void testTemplatized4() throws Exception; // public void testTemplatized5() throws Exception; // public void testTemplatized6() throws Exception; // public void testTemplatized7() throws Exception; // public void disable_testTemplatized8() throws Exception; // public void testTemplatized9() throws Exception; // public void testTemplatized10() throws Exception; // public void testTemplatized11() throws Exception; // public void testIssue1058() throws Exception; // public void testUnknownTypeReport() throws Exception; // public void testUnknownForIn() throws Exception; // public void testUnknownTypeDisabledByDefault() throws Exception; // public void testTemplatizedTypeSubtypes2() throws Exception; // public void testNonexistentPropertyAccessOnStruct() throws Exception; // public void testNonexistentPropertyAccessOnStructOrObject() throws Exception; // public void testNonexistentPropertyAccessOnExternStruct() throws Exception; // public void testNonexistentPropertyAccessStructSubtype() throws Exception; // public void testNonexistentPropertyAccessStructSubtype2() throws Exception; // public void testIssue1024() throws Exception; // private void testTypes(String js) throws Exception; // private void testTypes(String js, String description) throws Exception; // private void testTypes(String js, DiagnosticType type) throws Exception; // private void testClosureTypes(String js, String description) // throws Exception; // private void testClosureTypesMultipleWarnings( // String js, List<String> descriptions) throws Exception; // void testTypes(String js, String description, boolean isError) // throws Exception; // void testTypes(String externs, String js, String description, boolean isError) // throws Exception; // private Node parseAndTypeCheck(String js); // private Node parseAndTypeCheck(String externs, String js); // private TypeCheckResult parseAndTypeCheckWithScope(String js); // private TypeCheckResult parseAndTypeCheckWithScope( // String externs, String js); // private Node typeCheck(Node n); // private TypeCheck makeTypeCheck(); // void testTypes(String js, String[] warnings) throws Exception; // String suppressMissingProperty(String ... props); // private TypeCheckResult(Node root, Scope scope); // } // You are a professional Java test case writer, please create a test case named `testBug592170` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */
test/com/google/javascript/jscomp/TypeCheckTest.java
package com.google.javascript.jscomp; import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.REGEXP_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ReverseAbstractInterpreter; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.EnumType; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.jstype.TemplateTypeMap; import com.google.javascript.rhino.jstype.TemplateTypeMapReplacer; import com.google.javascript.rhino.jstype.TernaryValue; import com.google.javascript.rhino.jstype.UnionType; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Set;
public TypeCheck(AbstractCompiler compiler, ReverseAbstractInterpreter reverseInterpreter, JSTypeRegistry typeRegistry, Scope topScope, MemoizedScopeCreator scopeCreator, CheckLevel reportMissingOverride); public TypeCheck(AbstractCompiler compiler, ReverseAbstractInterpreter reverseInterpreter, JSTypeRegistry typeRegistry, CheckLevel reportMissingOverride); TypeCheck(AbstractCompiler compiler, ReverseAbstractInterpreter reverseInterpreter, JSTypeRegistry typeRegistry); TypeCheck reportMissingProperties(boolean report); @Override public void process(Node externsRoot, Node jsRoot); public Scope processForTesting(Node externsRoot, Node jsRoot); public void check(Node node, boolean externs); private void checkNoTypeCheckSection(Node n, boolean enterSection); private void report(NodeTraversal t, Node n, DiagnosticType diagnosticType, String... arguments); @Override public boolean shouldTraverse( NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private void checkTypeofString(NodeTraversal t, Node n, String s); private void doPercentTypedAccounting(NodeTraversal t, Node n); private void visitAssign(NodeTraversal t, Node assign); private void checkPropCreation(NodeTraversal t, Node lvalue); private void checkPropertyInheritanceOnGetpropAssign( NodeTraversal t, Node assign, Node object, String property, JSDocInfo info, JSType propertyType); private void visitObjLitKey( NodeTraversal t, Node key, Node objlit, JSType litType); private static boolean propertyIsImplicitCast(ObjectType type, String prop); private void checkDeclaredPropertyInheritance( NodeTraversal t, Node n, FunctionType ctorType, String propertyName, JSDocInfo info, JSType propertyType); private static boolean hasUnknownOrEmptySupertype(FunctionType ctor); private void visitInterfaceGetprop(NodeTraversal t, Node assign, Node object, String property, Node lvalue, Node rvalue); boolean visitName(NodeTraversal t, Node n, Node parent); private void visitGetProp(NodeTraversal t, Node n, Node parent); private void checkPropertyAccess(JSType childType, String propName, NodeTraversal t, Node n); private void checkPropertyAccessHelper(JSType objectType, String propName, NodeTraversal t, Node n); private SuggestionPair getClosestPropertySuggestion( JSType objectType, String propName); private boolean isPropertyTest(Node getProp); private void visitGetElem(NodeTraversal t, Node n); private void visitVar(NodeTraversal t, Node n); private void visitNew(NodeTraversal t, Node n); private void checkInterfaceConflictProperties(NodeTraversal t, Node n, String functionName, HashMap<String, ObjectType> properties, HashMap<String, ObjectType> currentProperties, ObjectType interfaceType); private void visitFunction(NodeTraversal t, Node n); private void visitCall(NodeTraversal t, Node n); private void visitParameterList(NodeTraversal t, Node call, FunctionType functionType); private void visitReturn(NodeTraversal t, Node n); private void visitBinaryOperator(int op, NodeTraversal t, Node n); private void checkEnumAlias( NodeTraversal t, JSDocInfo declInfo, Node value); private JSType getJSType(Node n); private void ensureTyped(NodeTraversal t, Node n); private void ensureTyped(NodeTraversal t, Node n, JSTypeNative type); private void ensureTyped(NodeTraversal t, Node n, JSType type); double getTypedPercent(); private JSType getNativeType(JSTypeNative typeId); private SuggestionPair(String suggestion, int distance);
6,979
testBug592170
```java public void testLends3() throws Exception; public void testLends4() throws Exception; public void testLends5() throws Exception; public void testLends6() throws Exception; public void testLends7() throws Exception; public void testLends8() throws Exception; public void testLends9() throws Exception; public void testLends10() throws Exception; public void testLends11() throws Exception; public void testDeclaredNativeTypeEquality() throws Exception; public void testUndefinedVar() throws Exception; public void testFlowScopeBug1() throws Exception; public void testFlowScopeBug2() throws Exception; public void testAddSingletonGetter(); public void testTypeCheckStandaloneAST() throws Exception; public void testUpdateParameterTypeOnClosure() throws Exception; public void testTemplatedThisType1() throws Exception; public void testTemplatedThisType2() throws Exception; public void testTemplateType1() throws Exception; public void testTemplateType2() throws Exception; public void testTemplateType3() throws Exception; public void testTemplateType4() throws Exception; public void testTemplateType5() throws Exception; public void testTemplateType6() throws Exception; public void testTemplateType7() throws Exception; public void testTemplateType8() throws Exception; public void testTemplateType9() throws Exception; public void testTemplateType10() throws Exception; public void testTemplateType11() throws Exception; public void testTemplateType12() throws Exception; public void testTemplateType13() throws Exception; public void testTemplateType14() throws Exception; public void testTemplateType15() throws Exception; public void testTemplateType16() throws Exception; public void testTemplateType17() throws Exception; public void testTemplateType18() throws Exception; public void testTemplateType19() throws Exception; public void testTemplateType20() throws Exception; public void testTemplateTypeWithUnresolvedType() throws Exception; public void testTemplateTypeWithTypeDef1a() throws Exception; public void testTemplateTypeWithTypeDef1b() throws Exception; public void testTemplateTypeWithTypeDef2a() throws Exception; public void testTemplateTypeWithTypeDef2b() throws Exception; public void testTemplateTypeWithTypeDef2c() throws Exception; public void testTemplateTypeWithTypeDef2d() throws Exception; public void testTemplatedFunctionInUnion1() throws Exception; public void testTemplateTypeRecursion1() throws Exception; public void testTemplateTypeRecursion2() throws Exception; public void testTemplateTypeRecursion3() throws Exception; public void disable_testBadTemplateType4() throws Exception; public void disable_testBadTemplateType5() throws Exception; public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception; public void testFunctionLiteralDefinedThisArgument() throws Exception; public void testFunctionLiteralDefinedThisArgument2() throws Exception; public void testFunctionLiteralUnreadNullThisArgument() throws Exception; public void testUnionTemplateThisType() throws Exception; public void testActiveXObject() throws Exception; public void testRecordType1() throws Exception; public void testRecordType2() throws Exception; public void testRecordType3() throws Exception; public void testRecordType4() throws Exception; public void testRecordType5() throws Exception; public void testRecordType6() throws Exception; public void testRecordType7() throws Exception; public void testRecordType8() throws Exception; public void testDuplicateRecordFields1() throws Exception; public void testDuplicateRecordFields2() throws Exception; public void testMultipleExtendsInterface1() throws Exception; public void testMultipleExtendsInterface2() throws Exception; public void testMultipleExtendsInterface3() throws Exception; public void testMultipleExtendsInterface4() throws Exception; public void testMultipleExtendsInterface5() throws Exception; public void testMultipleExtendsInterface6() throws Exception; public void testMultipleExtendsInterfaceAssignment() throws Exception; public void testMultipleExtendsInterfaceParamPass() throws Exception; public void testBadMultipleExtendsClass() throws Exception; public void testInterfaceExtendsResolution() throws Exception; public void testPropertyCanBeDefinedInObject() throws Exception; private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType); public void testExtendedInterfacePropertiesCompatibility1() throws Exception; public void testExtendedInterfacePropertiesCompatibility2() throws Exception; public void testExtendedInterfacePropertiesCompatibility3() throws Exception; public void testExtendedInterfacePropertiesCompatibility4() throws Exception; public void testExtendedInterfacePropertiesCompatibility5() throws Exception; public void testExtendedInterfacePropertiesCompatibility6() throws Exception; public void testExtendedInterfacePropertiesCompatibility7() throws Exception; public void testExtendedInterfacePropertiesCompatibility8() throws Exception; public void testExtendedInterfacePropertiesCompatibility9() throws Exception; public void testGenerics1() throws Exception; public void testFilter0() throws Exception; public void testFilter1() throws Exception; public void testFilter2() throws Exception; public void testFilter3() throws Exception; public void testBackwardsInferenceGoogArrayFilter1() throws Exception; public void testBackwardsInferenceGoogArrayFilter2() throws Exception; public void testBackwardsInferenceGoogArrayFilter3() throws Exception; public void testBackwardsInferenceGoogArrayFilter4() throws Exception; public void testCatchExpression1() throws Exception; public void testCatchExpression2() throws Exception; public void testTemplatized1() throws Exception; public void testTemplatized2() throws Exception; public void testTemplatized3() throws Exception; public void testTemplatized4() throws Exception; public void testTemplatized5() throws Exception; public void testTemplatized6() throws Exception; public void testTemplatized7() throws Exception; public void disable_testTemplatized8() throws Exception; public void testTemplatized9() throws Exception; public void testTemplatized10() throws Exception; public void testTemplatized11() throws Exception; public void testIssue1058() throws Exception; public void testUnknownTypeReport() throws Exception; public void testUnknownForIn() throws Exception; public void testUnknownTypeDisabledByDefault() throws Exception; public void testTemplatizedTypeSubtypes2() throws Exception; public void testNonexistentPropertyAccessOnStruct() throws Exception; public void testNonexistentPropertyAccessOnStructOrObject() throws Exception; public void testNonexistentPropertyAccessOnExternStruct() throws Exception; public void testNonexistentPropertyAccessStructSubtype() throws Exception; public void testNonexistentPropertyAccessStructSubtype2() throws Exception; public void testIssue1024() throws Exception; private void testTypes(String js) throws Exception; private void testTypes(String js, String description) throws Exception; private void testTypes(String js, DiagnosticType type) throws Exception; private void testClosureTypes(String js, String description) throws Exception; private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception; void testTypes(String js, String description, boolean isError) throws Exception; void testTypes(String externs, String js, String description, boolean isError) throws Exception; private Node parseAndTypeCheck(String js); private Node parseAndTypeCheck(String externs, String js); private TypeCheckResult parseAndTypeCheckWithScope(String js); private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js); private Node typeCheck(Node n); private TypeCheck makeTypeCheck(); void testTypes(String js, String[] warnings) throws Exception; String suppressMissingProperty(String ... props); private TypeCheckResult(Node root, Scope scope); } ``` You are a professional Java test case writer, please create a test case named `testBug592170` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */
6,971
// public void testLends3() throws Exception; // public void testLends4() throws Exception; // public void testLends5() throws Exception; // public void testLends6() throws Exception; // public void testLends7() throws Exception; // public void testLends8() throws Exception; // public void testLends9() throws Exception; // public void testLends10() throws Exception; // public void testLends11() throws Exception; // public void testDeclaredNativeTypeEquality() throws Exception; // public void testUndefinedVar() throws Exception; // public void testFlowScopeBug1() throws Exception; // public void testFlowScopeBug2() throws Exception; // public void testAddSingletonGetter(); // public void testTypeCheckStandaloneAST() throws Exception; // public void testUpdateParameterTypeOnClosure() throws Exception; // public void testTemplatedThisType1() throws Exception; // public void testTemplatedThisType2() throws Exception; // public void testTemplateType1() throws Exception; // public void testTemplateType2() throws Exception; // public void testTemplateType3() throws Exception; // public void testTemplateType4() throws Exception; // public void testTemplateType5() throws Exception; // public void testTemplateType6() throws Exception; // public void testTemplateType7() throws Exception; // public void testTemplateType8() throws Exception; // public void testTemplateType9() throws Exception; // public void testTemplateType10() throws Exception; // public void testTemplateType11() throws Exception; // public void testTemplateType12() throws Exception; // public void testTemplateType13() throws Exception; // public void testTemplateType14() throws Exception; // public void testTemplateType15() throws Exception; // public void testTemplateType16() throws Exception; // public void testTemplateType17() throws Exception; // public void testTemplateType18() throws Exception; // public void testTemplateType19() throws Exception; // public void testTemplateType20() throws Exception; // public void testTemplateTypeWithUnresolvedType() throws Exception; // public void testTemplateTypeWithTypeDef1a() throws Exception; // public void testTemplateTypeWithTypeDef1b() throws Exception; // public void testTemplateTypeWithTypeDef2a() throws Exception; // public void testTemplateTypeWithTypeDef2b() throws Exception; // public void testTemplateTypeWithTypeDef2c() throws Exception; // public void testTemplateTypeWithTypeDef2d() throws Exception; // public void testTemplatedFunctionInUnion1() throws Exception; // public void testTemplateTypeRecursion1() throws Exception; // public void testTemplateTypeRecursion2() throws Exception; // public void testTemplateTypeRecursion3() throws Exception; // public void disable_testBadTemplateType4() throws Exception; // public void disable_testBadTemplateType5() throws Exception; // public void disable_testFunctionLiteralUndefinedThisArgument() // throws Exception; // public void testFunctionLiteralDefinedThisArgument() throws Exception; // public void testFunctionLiteralDefinedThisArgument2() throws Exception; // public void testFunctionLiteralUnreadNullThisArgument() throws Exception; // public void testUnionTemplateThisType() throws Exception; // public void testActiveXObject() throws Exception; // public void testRecordType1() throws Exception; // public void testRecordType2() throws Exception; // public void testRecordType3() throws Exception; // public void testRecordType4() throws Exception; // public void testRecordType5() throws Exception; // public void testRecordType6() throws Exception; // public void testRecordType7() throws Exception; // public void testRecordType8() throws Exception; // public void testDuplicateRecordFields1() throws Exception; // public void testDuplicateRecordFields2() throws Exception; // public void testMultipleExtendsInterface1() throws Exception; // public void testMultipleExtendsInterface2() throws Exception; // public void testMultipleExtendsInterface3() throws Exception; // public void testMultipleExtendsInterface4() throws Exception; // public void testMultipleExtendsInterface5() throws Exception; // public void testMultipleExtendsInterface6() throws Exception; // public void testMultipleExtendsInterfaceAssignment() throws Exception; // public void testMultipleExtendsInterfaceParamPass() throws Exception; // public void testBadMultipleExtendsClass() throws Exception; // public void testInterfaceExtendsResolution() throws Exception; // public void testPropertyCanBeDefinedInObject() throws Exception; // private void checkObjectType(ObjectType objectType, String propertyName, // JSType expectedType); // public void testExtendedInterfacePropertiesCompatibility1() throws Exception; // public void testExtendedInterfacePropertiesCompatibility2() throws Exception; // public void testExtendedInterfacePropertiesCompatibility3() throws Exception; // public void testExtendedInterfacePropertiesCompatibility4() throws Exception; // public void testExtendedInterfacePropertiesCompatibility5() throws Exception; // public void testExtendedInterfacePropertiesCompatibility6() throws Exception; // public void testExtendedInterfacePropertiesCompatibility7() throws Exception; // public void testExtendedInterfacePropertiesCompatibility8() throws Exception; // public void testExtendedInterfacePropertiesCompatibility9() throws Exception; // public void testGenerics1() throws Exception; // public void testFilter0() // throws Exception; // public void testFilter1() // throws Exception; // public void testFilter2() // throws Exception; // public void testFilter3() // throws Exception; // public void testBackwardsInferenceGoogArrayFilter1() // throws Exception; // public void testBackwardsInferenceGoogArrayFilter2() throws Exception; // public void testBackwardsInferenceGoogArrayFilter3() throws Exception; // public void testBackwardsInferenceGoogArrayFilter4() throws Exception; // public void testCatchExpression1() throws Exception; // public void testCatchExpression2() throws Exception; // public void testTemplatized1() throws Exception; // public void testTemplatized2() throws Exception; // public void testTemplatized3() throws Exception; // public void testTemplatized4() throws Exception; // public void testTemplatized5() throws Exception; // public void testTemplatized6() throws Exception; // public void testTemplatized7() throws Exception; // public void disable_testTemplatized8() throws Exception; // public void testTemplatized9() throws Exception; // public void testTemplatized10() throws Exception; // public void testTemplatized11() throws Exception; // public void testIssue1058() throws Exception; // public void testUnknownTypeReport() throws Exception; // public void testUnknownForIn() throws Exception; // public void testUnknownTypeDisabledByDefault() throws Exception; // public void testTemplatizedTypeSubtypes2() throws Exception; // public void testNonexistentPropertyAccessOnStruct() throws Exception; // public void testNonexistentPropertyAccessOnStructOrObject() throws Exception; // public void testNonexistentPropertyAccessOnExternStruct() throws Exception; // public void testNonexistentPropertyAccessStructSubtype() throws Exception; // public void testNonexistentPropertyAccessStructSubtype2() throws Exception; // public void testIssue1024() throws Exception; // private void testTypes(String js) throws Exception; // private void testTypes(String js, String description) throws Exception; // private void testTypes(String js, DiagnosticType type) throws Exception; // private void testClosureTypes(String js, String description) // throws Exception; // private void testClosureTypesMultipleWarnings( // String js, List<String> descriptions) throws Exception; // void testTypes(String js, String description, boolean isError) // throws Exception; // void testTypes(String externs, String js, String description, boolean isError) // throws Exception; // private Node parseAndTypeCheck(String js); // private Node parseAndTypeCheck(String externs, String js); // private TypeCheckResult parseAndTypeCheckWithScope(String js); // private TypeCheckResult parseAndTypeCheckWithScope( // String externs, String js); // private Node typeCheck(Node n); // private TypeCheck makeTypeCheck(); // void testTypes(String js, String[] warnings) throws Exception; // String suppressMissingProperty(String ... props); // private TypeCheckResult(Node root, Scope scope); // } // You are a professional Java test case writer, please create a test case named `testBug592170` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception {
/** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */
107
com.google.javascript.jscomp.TypeCheck
test
```java public void testLends3() throws Exception; public void testLends4() throws Exception; public void testLends5() throws Exception; public void testLends6() throws Exception; public void testLends7() throws Exception; public void testLends8() throws Exception; public void testLends9() throws Exception; public void testLends10() throws Exception; public void testLends11() throws Exception; public void testDeclaredNativeTypeEquality() throws Exception; public void testUndefinedVar() throws Exception; public void testFlowScopeBug1() throws Exception; public void testFlowScopeBug2() throws Exception; public void testAddSingletonGetter(); public void testTypeCheckStandaloneAST() throws Exception; public void testUpdateParameterTypeOnClosure() throws Exception; public void testTemplatedThisType1() throws Exception; public void testTemplatedThisType2() throws Exception; public void testTemplateType1() throws Exception; public void testTemplateType2() throws Exception; public void testTemplateType3() throws Exception; public void testTemplateType4() throws Exception; public void testTemplateType5() throws Exception; public void testTemplateType6() throws Exception; public void testTemplateType7() throws Exception; public void testTemplateType8() throws Exception; public void testTemplateType9() throws Exception; public void testTemplateType10() throws Exception; public void testTemplateType11() throws Exception; public void testTemplateType12() throws Exception; public void testTemplateType13() throws Exception; public void testTemplateType14() throws Exception; public void testTemplateType15() throws Exception; public void testTemplateType16() throws Exception; public void testTemplateType17() throws Exception; public void testTemplateType18() throws Exception; public void testTemplateType19() throws Exception; public void testTemplateType20() throws Exception; public void testTemplateTypeWithUnresolvedType() throws Exception; public void testTemplateTypeWithTypeDef1a() throws Exception; public void testTemplateTypeWithTypeDef1b() throws Exception; public void testTemplateTypeWithTypeDef2a() throws Exception; public void testTemplateTypeWithTypeDef2b() throws Exception; public void testTemplateTypeWithTypeDef2c() throws Exception; public void testTemplateTypeWithTypeDef2d() throws Exception; public void testTemplatedFunctionInUnion1() throws Exception; public void testTemplateTypeRecursion1() throws Exception; public void testTemplateTypeRecursion2() throws Exception; public void testTemplateTypeRecursion3() throws Exception; public void disable_testBadTemplateType4() throws Exception; public void disable_testBadTemplateType5() throws Exception; public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception; public void testFunctionLiteralDefinedThisArgument() throws Exception; public void testFunctionLiteralDefinedThisArgument2() throws Exception; public void testFunctionLiteralUnreadNullThisArgument() throws Exception; public void testUnionTemplateThisType() throws Exception; public void testActiveXObject() throws Exception; public void testRecordType1() throws Exception; public void testRecordType2() throws Exception; public void testRecordType3() throws Exception; public void testRecordType4() throws Exception; public void testRecordType5() throws Exception; public void testRecordType6() throws Exception; public void testRecordType7() throws Exception; public void testRecordType8() throws Exception; public void testDuplicateRecordFields1() throws Exception; public void testDuplicateRecordFields2() throws Exception; public void testMultipleExtendsInterface1() throws Exception; public void testMultipleExtendsInterface2() throws Exception; public void testMultipleExtendsInterface3() throws Exception; public void testMultipleExtendsInterface4() throws Exception; public void testMultipleExtendsInterface5() throws Exception; public void testMultipleExtendsInterface6() throws Exception; public void testMultipleExtendsInterfaceAssignment() throws Exception; public void testMultipleExtendsInterfaceParamPass() throws Exception; public void testBadMultipleExtendsClass() throws Exception; public void testInterfaceExtendsResolution() throws Exception; public void testPropertyCanBeDefinedInObject() throws Exception; private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType); public void testExtendedInterfacePropertiesCompatibility1() throws Exception; public void testExtendedInterfacePropertiesCompatibility2() throws Exception; public void testExtendedInterfacePropertiesCompatibility3() throws Exception; public void testExtendedInterfacePropertiesCompatibility4() throws Exception; public void testExtendedInterfacePropertiesCompatibility5() throws Exception; public void testExtendedInterfacePropertiesCompatibility6() throws Exception; public void testExtendedInterfacePropertiesCompatibility7() throws Exception; public void testExtendedInterfacePropertiesCompatibility8() throws Exception; public void testExtendedInterfacePropertiesCompatibility9() throws Exception; public void testGenerics1() throws Exception; public void testFilter0() throws Exception; public void testFilter1() throws Exception; public void testFilter2() throws Exception; public void testFilter3() throws Exception; public void testBackwardsInferenceGoogArrayFilter1() throws Exception; public void testBackwardsInferenceGoogArrayFilter2() throws Exception; public void testBackwardsInferenceGoogArrayFilter3() throws Exception; public void testBackwardsInferenceGoogArrayFilter4() throws Exception; public void testCatchExpression1() throws Exception; public void testCatchExpression2() throws Exception; public void testTemplatized1() throws Exception; public void testTemplatized2() throws Exception; public void testTemplatized3() throws Exception; public void testTemplatized4() throws Exception; public void testTemplatized5() throws Exception; public void testTemplatized6() throws Exception; public void testTemplatized7() throws Exception; public void disable_testTemplatized8() throws Exception; public void testTemplatized9() throws Exception; public void testTemplatized10() throws Exception; public void testTemplatized11() throws Exception; public void testIssue1058() throws Exception; public void testUnknownTypeReport() throws Exception; public void testUnknownForIn() throws Exception; public void testUnknownTypeDisabledByDefault() throws Exception; public void testTemplatizedTypeSubtypes2() throws Exception; public void testNonexistentPropertyAccessOnStruct() throws Exception; public void testNonexistentPropertyAccessOnStructOrObject() throws Exception; public void testNonexistentPropertyAccessOnExternStruct() throws Exception; public void testNonexistentPropertyAccessStructSubtype() throws Exception; public void testNonexistentPropertyAccessStructSubtype2() throws Exception; public void testIssue1024() throws Exception; private void testTypes(String js) throws Exception; private void testTypes(String js, String description) throws Exception; private void testTypes(String js, DiagnosticType type) throws Exception; private void testClosureTypes(String js, String description) throws Exception; private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception; void testTypes(String js, String description, boolean isError) throws Exception; void testTypes(String externs, String js, String description, boolean isError) throws Exception; private Node parseAndTypeCheck(String js); private Node parseAndTypeCheck(String externs, String js); private TypeCheckResult parseAndTypeCheckWithScope(String js); private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js); private Node typeCheck(Node n); private TypeCheck makeTypeCheck(); void testTypes(String js, String[] warnings) throws Exception; String suppressMissingProperty(String ... props); private TypeCheckResult(Node root, Scope scope); } ``` You are a professional Java test case writer, please create a test case named `testBug592170` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { ```
public class TypeCheck implements NodeTraversal.Callback, CompilerPass
package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set;
@Override public void setUp() throws Exception; public void testInitialTypingScope(); public void testPrivateType() throws Exception; public void testTypeCheck1() throws Exception; public void testTypeCheck2() throws Exception; public void testTypeCheck4() throws Exception; public void testTypeCheck5() throws Exception; public void testTypeCheck6() throws Exception; public void testTypeCheck8() throws Exception; public void testTypeCheck9() throws Exception; public void testTypeCheck10() throws Exception; public void testTypeCheck11() throws Exception; public void testTypeCheck12() throws Exception; public void testTypeCheck13() throws Exception; public void testTypeCheck14() throws Exception; public void testTypeCheck15() throws Exception; public void testTypeCheck16() throws Exception; public void testTypeCheck17() throws Exception; public void testTypeCheck18() throws Exception; public void testTypeCheck19() throws Exception; public void testTypeCheck20() throws Exception; public void testTypeCheckBasicDowncast() throws Exception; public void testTypeCheckNoDowncastToNumber() throws Exception; public void testTypeCheck21() throws Exception; public void testTypeCheck22() throws Exception; public void testTypeCheck23() throws Exception; public void testTypeCheck24() throws Exception; public void testTypeCheck25() throws Exception; public void testTypeCheck26() throws Exception; public void testTypeCheck27() throws Exception; public void testTypeCheck28() throws Exception; public void testTypeCheckInlineReturns() throws Exception; public void testTypeCheckDefaultExterns() throws Exception; public void testTypeCheckCustomExterns() throws Exception; public void testTypeCheckCustomExterns2() throws Exception; public void testTemplatizedArray1() throws Exception; public void testTemplatizedArray2() throws Exception; public void testTemplatizedArray3() throws Exception; public void testTemplatizedArray4() throws Exception; public void testTemplatizedArray5() throws Exception; public void testTemplatizedArray6() throws Exception; public void testTemplatizedArray7() throws Exception; public void testTemplatizedObject1() throws Exception; public void testTemplatizedObject2() throws Exception; public void testTemplatizedObject3() throws Exception; public void testTemplatizedObject4() throws Exception; public void testTemplatizedObject5() throws Exception; public void testUnionOfFunctionAndType() throws Exception; public void testOptionalParameterComparedToUndefined() throws Exception; public void testOptionalAllType() throws Exception; public void testOptionalUnknownNamedType() throws Exception; public void testOptionalArgFunctionParam() throws Exception; public void testOptionalArgFunctionParam2() throws Exception; public void testOptionalArgFunctionParam3() throws Exception; public void testOptionalArgFunctionParam4() throws Exception; public void testOptionalArgFunctionParamError() throws Exception; public void testOptionalNullableArgFunctionParam() throws Exception; public void testOptionalNullableArgFunctionParam2() throws Exception; public void testOptionalNullableArgFunctionParam3() throws Exception; public void testOptionalArgFunctionReturn() throws Exception; public void testOptionalArgFunctionReturn2() throws Exception; public void testBooleanType() throws Exception; public void testBooleanReduction1() throws Exception; public void testBooleanReduction2() throws Exception; public void testBooleanReduction3() throws Exception; public void testBooleanReduction4() throws Exception; public void testBooleanReduction5() throws Exception; public void testBooleanReduction6() throws Exception; public void testBooleanReduction7() throws Exception; public void testNullAnd() throws Exception; public void testNullOr() throws Exception; public void testBooleanPreservation1() throws Exception; public void testBooleanPreservation2() throws Exception; public void testBooleanPreservation3() throws Exception; public void testBooleanPreservation4() throws Exception; public void testTypeOfReduction1() throws Exception; public void testTypeOfReduction2() throws Exception; public void testTypeOfReduction3() throws Exception; public void testTypeOfReduction4() throws Exception; public void testTypeOfReduction5() throws Exception; public void testTypeOfReduction6() throws Exception; public void testTypeOfReduction7() throws Exception; public void testTypeOfReduction8() throws Exception; public void testTypeOfReduction9() throws Exception; public void testTypeOfReduction10() throws Exception; public void testTypeOfReduction11() throws Exception; public void testTypeOfReduction12() throws Exception; public void testTypeOfReduction13() throws Exception; public void testTypeOfReduction14() throws Exception; public void testTypeOfReduction15() throws Exception; public void testTypeOfReduction16() throws Exception; public void testQualifiedNameReduction1() throws Exception; public void testQualifiedNameReduction2() throws Exception; public void testQualifiedNameReduction3() throws Exception; public void testQualifiedNameReduction4() throws Exception; public void testQualifiedNameReduction5a() throws Exception; public void testQualifiedNameReduction5b() throws Exception; public void testQualifiedNameReduction5c() throws Exception; public void testQualifiedNameReduction6() throws Exception; public void testQualifiedNameReduction7() throws Exception; public void testQualifiedNameReduction7a() throws Exception; public void testQualifiedNameReduction8() throws Exception; public void testQualifiedNameReduction9() throws Exception; public void testQualifiedNameReduction10() throws Exception; public void testObjLitDef1a() throws Exception; public void testObjLitDef1b() throws Exception; public void testObjLitDef2a() throws Exception; public void testObjLitDef2b() throws Exception; public void testObjLitDef3a() throws Exception; public void testObjLitDef3b() throws Exception; public void testObjLitDef4() throws Exception; public void testObjLitDef5() throws Exception; public void testObjLitDef6() throws Exception; public void testObjLitDef7() throws Exception; public void testInstanceOfReduction1() throws Exception; public void testInstanceOfReduction2() throws Exception; public void testUndeclaredGlobalProperty1() throws Exception; public void testUndeclaredGlobalProperty2() throws Exception; public void testLocallyInferredGlobalProperty1() throws Exception; public void testPropertyInferredPropagation() throws Exception; public void testPropertyInference1() throws Exception; public void testPropertyInference2() throws Exception; public void testPropertyInference3() throws Exception; public void testPropertyInference4() throws Exception; public void testPropertyInference5() throws Exception; public void testPropertyInference6() throws Exception; public void testPropertyInference7() throws Exception; public void testPropertyInference8() throws Exception; public void testPropertyInference9() throws Exception; public void testPropertyInference10() throws Exception; public void testNoPersistentTypeInferenceForObjectProperties() throws Exception; public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception; public void testObjectPropertyTypeInferredInLocalScope1() throws Exception; public void testObjectPropertyTypeInferredInLocalScope2() throws Exception; public void testObjectPropertyTypeInferredInLocalScope3() throws Exception; public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception; public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception; public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception; public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception; public void testPropertyUsedBeforeDefinition1() throws Exception; public void testPropertyUsedBeforeDefinition2() throws Exception; public void testAdd1() throws Exception; public void testAdd2() throws Exception; public void testAdd3() throws Exception; public void testAdd4() throws Exception; public void testAdd5() throws Exception; public void testAdd6() throws Exception; public void testAdd7() throws Exception; public void testAdd8() throws Exception; public void testAdd9() throws Exception; public void testAdd10() throws Exception; public void testAdd11() throws Exception; public void testAdd12() throws Exception; public void testAdd13() throws Exception; public void testAdd14() throws Exception; public void testAdd15() throws Exception; public void testAdd16() throws Exception; public void testAdd17() throws Exception; public void testAdd18() throws Exception; public void testAdd19() throws Exception; public void testAdd20() throws Exception; public void testAdd21() throws Exception; public void testNumericComparison1() throws Exception; public void testNumericComparison2() throws Exception; public void testNumericComparison3() throws Exception; public void testNumericComparison4() throws Exception; public void testNumericComparison5() throws Exception; public void testNumericComparison6() throws Exception; public void testStringComparison1() throws Exception; public void testStringComparison2() throws Exception; public void testStringComparison3() throws Exception; public void testStringComparison4() throws Exception; public void testStringComparison5() throws Exception; public void testStringComparison6() throws Exception; public void testValueOfComparison1() throws Exception; public void testValueOfComparison2() throws Exception; public void testValueOfComparison3() throws Exception; public void testGenericRelationalExpression() throws Exception; public void testInstanceof1() throws Exception; public void testInstanceof2() throws Exception; public void testInstanceof3() throws Exception; public void testInstanceof4() throws Exception; public void testInstanceof5() throws Exception; public void testInstanceof6() throws Exception; public void testInstanceOfReduction3() throws Exception; public void testScoping1() throws Exception; public void testScoping2() throws Exception; public void testScoping3() throws Exception; public void testScoping4() throws Exception; public void testScoping5() throws Exception; public void testScoping6() throws Exception; public void testScoping7() throws Exception; public void testScoping8() throws Exception; public void testScoping9() throws Exception; public void testScoping10() throws Exception; public void testScoping11() throws Exception; public void testScoping12() throws Exception; public void testFunctionArguments1() throws Exception; public void testFunctionArguments2() throws Exception; public void testFunctionArguments3() throws Exception; public void testFunctionArguments4() throws Exception; public void testFunctionArguments5() throws Exception; public void testFunctionArguments6() throws Exception; public void testFunctionArguments7() throws Exception; public void testFunctionArguments8() throws Exception; public void testFunctionArguments9() throws Exception; public void testFunctionArguments10() throws Exception; public void testFunctionArguments11() throws Exception; public void testFunctionArguments12() throws Exception; public void testFunctionArguments13() throws Exception; public void testFunctionArguments14() throws Exception; public void testFunctionArguments15() throws Exception; public void testFunctionArguments16() throws Exception; public void testFunctionArguments17() throws Exception; public void testFunctionArguments18() throws Exception; public void testPrintFunctionName1() throws Exception; public void testPrintFunctionName2() throws Exception; public void testFunctionInference1() throws Exception; public void testFunctionInference2() throws Exception; public void testFunctionInference3() throws Exception; public void testFunctionInference4() throws Exception; public void testFunctionInference5() throws Exception; public void testFunctionInference6() throws Exception; public void testFunctionInference7() throws Exception; public void testFunctionInference8() throws Exception; public void testFunctionInference9() throws Exception; public void testFunctionInference10() throws Exception; public void testFunctionInference11() throws Exception; public void testFunctionInference12() throws Exception; public void testFunctionInference13() throws Exception; public void testFunctionInference14() throws Exception; public void testFunctionInference15() throws Exception; public void testFunctionInference16() throws Exception; public void testFunctionInference17() throws Exception; public void testFunctionInference18() throws Exception; public void testFunctionInference19() throws Exception; public void testFunctionInference20() throws Exception; public void testFunctionInference21() throws Exception; public void testFunctionInference22() throws Exception; public void testFunctionInference23() throws Exception; public void testInnerFunction1() throws Exception; public void testInnerFunction2() throws Exception; public void testInnerFunction3() throws Exception; public void testInnerFunction4() throws Exception; public void testInnerFunction5() throws Exception; public void testInnerFunction6() throws Exception; public void testInnerFunction7() throws Exception; public void testInnerFunction8() throws Exception; public void testInnerFunction9() throws Exception; public void testInnerFunction10() throws Exception; public void testInnerFunction11() throws Exception; public void testAbstractMethodHandling1() throws Exception; public void testAbstractMethodHandling2() throws Exception; public void testAbstractMethodHandling3() throws Exception; public void testAbstractMethodHandling4() throws Exception; public void testAbstractMethodHandling5() throws Exception; public void testAbstractMethodHandling6() throws Exception; public void testMethodInference1() throws Exception; public void testMethodInference2() throws Exception; public void testMethodInference3() throws Exception; public void testMethodInference4() throws Exception; public void testMethodInference5() throws Exception; public void testMethodInference6() throws Exception; public void testMethodInference7() throws Exception; public void testMethodInference8() throws Exception; public void testMethodInference9() throws Exception; public void testStaticMethodDeclaration1() throws Exception; public void testStaticMethodDeclaration2() throws Exception; public void testStaticMethodDeclaration3() throws Exception; public void testDuplicateStaticMethodDecl1() throws Exception; public void testDuplicateStaticMethodDecl2() throws Exception; public void testDuplicateStaticMethodDecl3() throws Exception; public void testDuplicateStaticMethodDecl4() throws Exception; public void testDuplicateStaticMethodDecl5() throws Exception; public void testDuplicateStaticMethodDecl6() throws Exception; public void testDuplicateStaticPropertyDecl1() throws Exception; public void testDuplicateStaticPropertyDecl2() throws Exception; public void testDuplicateStaticPropertyDecl3() throws Exception; public void testDuplicateStaticPropertyDecl4() throws Exception; public void testDuplicateStaticPropertyDecl5() throws Exception; public void testDuplicateStaticPropertyDecl6() throws Exception; public void testDuplicateStaticPropertyDecl7() throws Exception; public void testDuplicateStaticPropertyDecl8() throws Exception; public void testDuplicateStaticPropertyDecl9() throws Exception; public void testDuplicateStaticPropertyDec20() throws Exception; public void testDuplicateLocalVarDecl() throws Exception; public void testDuplicateInstanceMethod1() throws Exception; public void testDuplicateInstanceMethod2() throws Exception; public void testDuplicateInstanceMethod3() throws Exception; public void testDuplicateInstanceMethod4() throws Exception; public void testDuplicateInstanceMethod5() throws Exception; public void testDuplicateInstanceMethod6() throws Exception; public void testStubFunctionDeclaration1() throws Exception; public void testStubFunctionDeclaration2() throws Exception; public void testStubFunctionDeclaration3() throws Exception; public void testStubFunctionDeclaration4() throws Exception; public void testStubFunctionDeclaration5() throws Exception; public void testStubFunctionDeclaration6() throws Exception; public void testStubFunctionDeclaration7() throws Exception; public void testStubFunctionDeclaration8() throws Exception; public void testStubFunctionDeclaration9() throws Exception; public void testStubFunctionDeclaration10() throws Exception; public void testNestedFunctionInference1() throws Exception; private void testFunctionType(String functionDef, String functionType) throws Exception; private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception; private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception; public void testTypeRedefinition() throws Exception; public void testIn1() throws Exception; public void testIn2() throws Exception; public void testIn3() throws Exception; public void testIn4() throws Exception; public void testIn5() throws Exception; public void testIn6() throws Exception; public void testIn7() throws Exception; public void testForIn1() throws Exception; public void testForIn2() throws Exception; public void testForIn3() throws Exception; public void testForIn4() throws Exception; public void testForIn5() throws Exception; public void testComparison2() throws Exception; public void testComparison3() throws Exception; public void testComparison4() throws Exception; public void testComparison5() throws Exception; public void testComparison6() throws Exception; public void testComparison7() throws Exception; public void testComparison8() throws Exception; public void testComparison9() throws Exception; public void testComparison10() throws Exception; public void testComparison11() throws Exception; public void testComparison12() throws Exception; public void testComparison13() throws Exception; public void testComparison14() throws Exception; public void testComparison15() throws Exception; public void testDeleteOperator1() throws Exception; public void testDeleteOperator2() throws Exception; public void testEnumStaticMethod1() throws Exception; public void testEnumStaticMethod2() throws Exception; public void testEnum1() throws Exception; public void testEnum2() throws Exception; public void testEnum3() throws Exception; public void testEnum4() throws Exception; public void testEnum5() throws Exception; public void testEnum6() throws Exception; public void testEnum7() throws Exception; public void testEnum8() throws Exception; public void testEnum9() throws Exception; public void testEnum10() throws Exception; public void testEnum11() throws Exception; public void testEnum12() throws Exception; public void testEnum13() throws Exception; public void testEnum14() throws Exception; public void testEnum15() throws Exception; public void testEnum16() throws Exception; public void testEnum17() throws Exception; public void testEnum18() throws Exception; public void testEnum19() throws Exception; public void testEnum20() throws Exception; public void testEnum21() throws Exception; public void testEnum22() throws Exception; public void testEnum23() throws Exception; public void testEnum24() throws Exception; public void testEnum25() throws Exception; public void testEnum26() throws Exception; public void testEnum27() throws Exception; public void testEnum28() throws Exception; public void testEnum29() throws Exception; public void testEnum30() throws Exception; public void testEnum31() throws Exception; public void testEnum32() throws Exception; public void testEnum34() throws Exception; public void testEnum35() throws Exception; public void testEnum36() throws Exception; public void testEnum37() throws Exception; public void testEnum38() throws Exception; public void testEnum39() throws Exception; public void testEnum40() throws Exception; public void testEnum41() throws Exception; public void testEnum42() throws Exception; public void testAliasedEnum1() throws Exception; public void testAliasedEnum2() throws Exception; public void testAliasedEnum3() throws Exception; public void testAliasedEnum4() throws Exception; public void testAliasedEnum5() throws Exception; public void testBackwardsEnumUse1() throws Exception; public void testBackwardsEnumUse2() throws Exception; public void testBackwardsEnumUse3() throws Exception; public void testBackwardsEnumUse4() throws Exception; public void testBackwardsEnumUse5() throws Exception; public void testBackwardsTypedefUse2() throws Exception; public void testBackwardsTypedefUse4() throws Exception; public void testBackwardsTypedefUse6() throws Exception; public void testBackwardsTypedefUse7() throws Exception; public void testBackwardsTypedefUse8() throws Exception; public void testBackwardsTypedefUse9() throws Exception; public void testBackwardsTypedefUse10() throws Exception; public void testBackwardsConstructor1() throws Exception; public void testBackwardsConstructor2() throws Exception; public void testMinimalConstructorAnnotation() throws Exception; public void testGoodExtends1() throws Exception; public void testGoodExtends2() throws Exception; public void testGoodExtends3() throws Exception; public void testGoodExtends4() throws Exception; public void testGoodExtends5() throws Exception; public void testGoodExtends6() throws Exception; public void testGoodExtends7() throws Exception; public void testGoodExtends8() throws Exception; public void testGoodExtends9() throws Exception; public void testGoodExtends10() throws Exception; public void testGoodExtends11() throws Exception; public void testGoodExtends12() throws Exception; public void testGoodExtends13() throws Exception; public void testGoodExtends14() throws Exception; public void testGoodExtends15() throws Exception; public void testGoodExtends16() throws Exception; public void testGoodExtends17() throws Exception; public void testGoodExtends18() throws Exception; public void testGoodExtends19() throws Exception; public void testBadExtends1() throws Exception; public void testBadExtends2() throws Exception; public void testBadExtends3() throws Exception; public void testBadExtends4() throws Exception; public void testLateExtends() throws Exception; public void testSuperclassMatch() throws Exception; public void testSuperclassMatchWithMixin() throws Exception; public void testSuperclassMismatch1() throws Exception; public void testSuperclassMismatch2() throws Exception; public void testSuperClassDefinedAfterSubClass1() throws Exception; public void testSuperClassDefinedAfterSubClass2() throws Exception; public void testDirectPrototypeAssignment1() throws Exception; public void testDirectPrototypeAssignment2() throws Exception; public void testDirectPrototypeAssignment3() throws Exception; public void testGoodImplements1() throws Exception; public void testGoodImplements2() throws Exception; public void testGoodImplements3() throws Exception; public void testGoodImplements4() throws Exception; public void testGoodImplements5() throws Exception; public void testGoodImplements6() throws Exception; public void testGoodImplements7() throws Exception; public void testBadImplements1() throws Exception; public void testBadImplements2() throws Exception; public void testBadImplements3() throws Exception; public void testBadImplements4() throws Exception; public void testBadImplements5() throws Exception; public void testBadImplements6() throws Exception; public void testConstructorClassTemplate() throws Exception; public void testInterfaceExtends() throws Exception; public void testBadInterfaceExtends1() throws Exception; public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception; public void testBadInterfaceExtends2() throws Exception; public void testBadInterfaceExtends3() throws Exception; public void testBadInterfaceExtends4() throws Exception; public void testBadInterfaceExtends5() throws Exception; public void testBadImplementsAConstructor() throws Exception; public void testBadImplementsNonInterfaceType() throws Exception; public void testBadImplementsNonObjectType() throws Exception; public void testBadImplementsDuplicateInterface1() throws Exception; public void testBadImplementsDuplicateInterface2() throws Exception; public void testInterfaceAssignment1() throws Exception; public void testInterfaceAssignment2() throws Exception; public void testInterfaceAssignment3() throws Exception; public void testInterfaceAssignment4() throws Exception; public void testInterfaceAssignment5() throws Exception; public void testInterfaceAssignment6() throws Exception; public void testInterfaceAssignment7() throws Exception; public void testInterfaceAssignment8() throws Exception; public void testInterfaceAssignment9() throws Exception; public void testInterfaceAssignment10() throws Exception; public void testInterfaceAssignment11() throws Exception; public void testInterfaceAssignment12() throws Exception; public void testInterfaceAssignment13() throws Exception; public void testGetprop1() throws Exception; public void testGetprop2() throws Exception; public void testGetprop3() throws Exception; public void testGetprop4() throws Exception; public void testSetprop1() throws Exception; public void testSetprop2() throws Exception; public void testSetprop3() throws Exception; public void testSetprop4() throws Exception; public void testSetprop5() throws Exception; public void testSetprop6() throws Exception; public void testSetprop7() throws Exception; public void testSetprop8() throws Exception; public void testSetprop9() throws Exception; public void testSetprop10() throws Exception; public void testSetprop11() throws Exception; public void testSetprop12() throws Exception; public void testSetprop13() throws Exception; public void testSetprop14() throws Exception; public void testSetprop15() throws Exception; public void testGetpropDict1() throws Exception; public void testGetpropDict2() throws Exception; public void testGetpropDict3() throws Exception; public void testGetpropDict4() throws Exception; public void testGetpropDict5() throws Exception; public void testGetpropDict6() throws Exception; public void testGetpropDict7() throws Exception; public void testGetelemStruct1() throws Exception; public void testGetelemStruct2() throws Exception; public void testGetelemStruct3() throws Exception; public void testGetelemStruct4() throws Exception; public void testGetelemStruct5() throws Exception; public void testGetelemStruct6() throws Exception; public void testGetelemStruct7() throws Exception; public void testInOnStruct() throws Exception; public void testForinOnStruct() throws Exception; public void testArrayAccess1() throws Exception; public void testArrayAccess2() throws Exception; public void testArrayAccess3() throws Exception; public void testArrayAccess4() throws Exception; public void testArrayAccess6() throws Exception; public void testArrayAccess7() throws Exception; public void testArrayAccess8() throws Exception; public void testArrayAccess9() throws Exception; public void testPropAccess() throws Exception; public void testPropAccess2() throws Exception; public void testPropAccess3() throws Exception; public void testPropAccess4() throws Exception; public void testSwitchCase1() throws Exception; public void testSwitchCase2() throws Exception; public void testVar1() throws Exception; public void testVar2() throws Exception; public void testVar3() throws Exception; public void testVar4() throws Exception; public void testVar5() throws Exception; public void testVar6() throws Exception; public void testVar7() throws Exception; public void testVar8() throws Exception; public void testVar9() throws Exception; public void testVar10() throws Exception; public void testVar11() throws Exception; public void testVar12() throws Exception; public void testVar13() throws Exception; public void testVar14() throws Exception; public void testVar15() throws Exception; public void testAssign1() throws Exception; public void testAssign2() throws Exception; public void testAssign3() throws Exception; public void testAssign4() throws Exception; public void testAssignInference() throws Exception; public void testOr1() throws Exception; public void testOr2() throws Exception; public void testOr3() throws Exception; public void testOr4() throws Exception; public void testOr5() throws Exception; public void testAnd1() throws Exception; public void testAnd2() throws Exception; public void testAnd3() throws Exception; public void testAnd4() throws Exception; public void testAnd5() throws Exception; public void testAnd6() throws Exception; public void testAnd7() throws Exception; public void testHook() throws Exception; public void testHookRestrictsType1() throws Exception; public void testHookRestrictsType2() throws Exception; public void testHookRestrictsType3() throws Exception; public void testHookRestrictsType4() throws Exception; public void testHookRestrictsType5() throws Exception; public void testHookRestrictsType6() throws Exception; public void testHookRestrictsType7() throws Exception; public void testWhileRestrictsType1() throws Exception; public void testWhileRestrictsType2() throws Exception; public void testHigherOrderFunctions1() throws Exception; public void testHigherOrderFunctions2() throws Exception; public void testHigherOrderFunctions3() throws Exception; public void testHigherOrderFunctions4() throws Exception; public void testHigherOrderFunctions5() throws Exception; public void testConstructorAlias1() throws Exception; public void testConstructorAlias2() throws Exception; public void testConstructorAlias3() throws Exception; public void testConstructorAlias4() throws Exception; public void testConstructorAlias5() throws Exception; public void testConstructorAlias6() throws Exception; public void testConstructorAlias7() throws Exception; public void testConstructorAlias8() throws Exception; public void testConstructorAlias9() throws Exception; public void testConstructorAlias10() throws Exception; public void testClosure1() throws Exception; public void testClosure2() throws Exception; public void testClosure3() throws Exception; public void testClosure4() throws Exception; public void testClosure5() throws Exception; public void testClosure6() throws Exception; public void testClosure7() throws Exception; public void testReturn1() throws Exception; public void testReturn2() throws Exception; public void testReturn3() throws Exception; public void testReturn4() throws Exception; public void testReturn5() throws Exception; public void testReturn6() throws Exception; public void testReturn7() throws Exception; public void testReturn8() throws Exception; public void testInferredReturn1() throws Exception; public void testInferredReturn2() throws Exception; public void testInferredReturn3() throws Exception; public void testInferredReturn4() throws Exception; public void testInferredReturn5() throws Exception; public void testInferredReturn6() throws Exception; public void testInferredReturn7() throws Exception; public void testInferredReturn8() throws Exception; public void testInferredParam1() throws Exception; public void testInferredParam2() throws Exception; public void testInferredParam3() throws Exception; public void testInferredParam4() throws Exception; public void testInferredParam5() throws Exception; public void testInferredParam6() throws Exception; public void testInferredParam7() throws Exception; public void testOverriddenParams1() throws Exception; public void testOverriddenParams2() throws Exception; public void testOverriddenParams3() throws Exception; public void testOverriddenParams4() throws Exception; public void testOverriddenParams5() throws Exception; public void testOverriddenParams6() throws Exception; public void testOverriddenParams7() throws Exception; public void testOverriddenReturn1() throws Exception; public void testOverriddenReturn2() throws Exception; public void testOverriddenReturn3() throws Exception; public void testOverriddenReturn4() throws Exception; public void testThis1() throws Exception; public void testOverriddenProperty1() throws Exception; public void testOverriddenProperty2() throws Exception; public void testOverriddenProperty3() throws Exception; public void testOverriddenProperty4() throws Exception; public void testOverriddenProperty5() throws Exception; public void testOverriddenProperty6() throws Exception; public void testThis2() throws Exception; public void testThis3() throws Exception; public void testThis4() throws Exception; public void testThis5() throws Exception; public void testThis6() throws Exception; public void testThis7() throws Exception; public void testThis8() throws Exception; public void testThis9() throws Exception; public void testThis10() throws Exception; public void testThis11() throws Exception; public void testThis12() throws Exception; public void testThis13() throws Exception; public void testThis14() throws Exception; public void testThisTypeOfFunction1() throws Exception; public void testThisTypeOfFunction2() throws Exception; public void testThisTypeOfFunction3() throws Exception; public void testThisTypeOfFunction4() throws Exception; public void testGlobalThis1() throws Exception; public void testGlobalThis2() throws Exception; public void testGlobalThis2b() throws Exception; public void testGlobalThis3() throws Exception; public void testGlobalThis4() throws Exception; public void testGlobalThis5() throws Exception; public void testGlobalThis6() throws Exception; public void testGlobalThis7() throws Exception; public void testGlobalThis8() throws Exception; public void testGlobalThis9() throws Exception; public void testControlFlowRestrictsType1() throws Exception; public void testControlFlowRestrictsType2() throws Exception; public void testControlFlowRestrictsType3() throws Exception; public void testControlFlowRestrictsType4() throws Exception; public void testControlFlowRestrictsType5() throws Exception; public void testControlFlowRestrictsType6() throws Exception; public void testControlFlowRestrictsType7() throws Exception; public void testControlFlowRestrictsType8() throws Exception; public void testControlFlowRestrictsType9() throws Exception; public void testControlFlowRestrictsType10() throws Exception; public void testControlFlowRestrictsType11() throws Exception; public void testSwitchCase3() throws Exception; public void testSwitchCase4() throws Exception; public void testSwitchCase5() throws Exception; public void testSwitchCase6() throws Exception; public void testSwitchCase7() throws Exception; public void testSwitchCase8() throws Exception; public void testNoTypeCheck1() throws Exception; public void testNoTypeCheck2() throws Exception; public void testNoTypeCheck3() throws Exception; public void testNoTypeCheck4() throws Exception; public void testNoTypeCheck5() throws Exception; public void testNoTypeCheck6() throws Exception; public void testNoTypeCheck7() throws Exception; public void testNoTypeCheck8() throws Exception; public void testNoTypeCheck9() throws Exception; public void testNoTypeCheck10() throws Exception; public void testNoTypeCheck11() throws Exception; public void testNoTypeCheck12() throws Exception; public void testNoTypeCheck13() throws Exception; public void testNoTypeCheck14() throws Exception; public void testImplicitCast() throws Exception; public void testImplicitCastSubclassAccess() throws Exception; public void testImplicitCastNotInExterns() throws Exception; public void testNumberNode() throws Exception; public void testStringNode() throws Exception; public void testBooleanNodeTrue() throws Exception; public void testBooleanNodeFalse() throws Exception; public void testUndefinedNode() throws Exception; public void testNumberAutoboxing() throws Exception; public void testNumberUnboxing() throws Exception; public void testStringAutoboxing() throws Exception; public void testStringUnboxing() throws Exception; public void testBooleanAutoboxing() throws Exception; public void testBooleanUnboxing() throws Exception; public void testIIFE1() throws Exception; public void testIIFE2() throws Exception; public void testIIFE3() throws Exception; public void testIIFE4() throws Exception; public void testIIFE5() throws Exception; public void testNotIIFE1() throws Exception; public void testNamespaceType1() throws Exception; public void testNamespaceType2() throws Exception; public void testIssue61() throws Exception; public void testIssue61b() throws Exception; public void testIssue86() throws Exception; public void testIssue124() throws Exception; public void testIssue124b() throws Exception; public void testIssue259() throws Exception; public void testIssue301() throws Exception; public void testIssue368() throws Exception; public void testIssue380() throws Exception; public void testIssue483() throws Exception; public void testIssue537a() throws Exception; public void testIssue537b() throws Exception; public void testIssue537c() throws Exception; public void testIssue537d() throws Exception; public void testIssue586() throws Exception; public void testIssue635() throws Exception; public void testIssue635b() throws Exception; public void testIssue669() throws Exception; public void testIssue688() throws Exception; public void testIssue700() throws Exception; public void testIssue725() throws Exception; public void testIssue726() throws Exception; public void testIssue765() throws Exception; public void testIssue783() throws Exception; public void testIssue791() throws Exception; public void testIssue810() throws Exception; public void testIssue1002() throws Exception; public void testIssue1023() throws Exception; public void testIssue1047() throws Exception; public void testIssue1056() throws Exception; public void testIssue1072() throws Exception; public void testIssue1123() throws Exception; public void testEnums() throws Exception; public void testBug592170() throws Exception; public void testBug901455() throws Exception; public void testBug908701() throws Exception; public void testBug908625() throws Exception; public void testBug911118() throws Exception; public void testBug909000() throws Exception; public void testBug930117() throws Exception; public void testBug1484445() throws Exception; public void testBug1859535() throws Exception; public void testBug1940591() throws Exception; public void testBug1942972() throws Exception; public void testBug1943776() throws Exception; public void testBug1987544() throws Exception; public void testBug1940769() throws Exception; public void testBug2335992() throws Exception; public void testBug2341812() throws Exception; public void testBug7701884() throws Exception; public void testBug8017789() throws Exception; public void testTypedefBeforeUse() throws Exception; public void testScopedConstructors1() throws Exception; public void testScopedConstructors2() throws Exception; public void testQualifiedNameInference1() throws Exception; public void testQualifiedNameInference2() throws Exception; public void testQualifiedNameInference3() throws Exception; public void testQualifiedNameInference4() throws Exception; public void testQualifiedNameInference5() throws Exception; public void testQualifiedNameInference6() throws Exception; public void testQualifiedNameInference7() throws Exception; public void testQualifiedNameInference8() throws Exception; public void testQualifiedNameInference9() throws Exception; public void testQualifiedNameInference10() throws Exception; public void testQualifiedNameInference11() throws Exception; public void testQualifiedNameInference12() throws Exception; public void testQualifiedNameInference13() throws Exception; public void testSheqRefinedScope() throws Exception; public void testAssignToUntypedVariable() throws Exception; public void testAssignToUntypedProperty() throws Exception; public void testNew1() throws Exception; public void testNew2() throws Exception; public void testNew3() throws Exception; public void testNew4() throws Exception; public void testNew5() throws Exception; public void testNew6() throws Exception; public void testNew7() throws Exception; public void testNew8() throws Exception; public void testNew9() throws Exception; public void testNew10() throws Exception; public void testNew11() throws Exception; public void testNew12() throws Exception; public void testNew13() throws Exception; public void testNew14() throws Exception; public void testNew15() throws Exception; public void testNew16() throws Exception; public void testNew17() throws Exception; public void testNew18() throws Exception; public void testName1() throws Exception; public void testName2() throws Exception; public void testName3() throws Exception; public void testName4() throws Exception; public void testName5() throws Exception; private JSType testNameNode(String name); public void testBitOperation1() throws Exception; public void testBitOperation2() throws Exception; public void testBitOperation3() throws Exception; public void testBitOperation4() throws Exception; public void testBitOperation5() throws Exception; public void testBitOperation6() throws Exception; public void testBitOperation7() throws Exception; public void testBitOperation8() throws Exception; public void testBitOperation9() throws Exception; public void testCall1() throws Exception; public void testCall2() throws Exception; public void testCall3() throws Exception; public void testCall4() throws Exception; public void testCall5() throws Exception; public void testCall6() throws Exception; public void testCall7() throws Exception; public void testCall8() throws Exception; public void testCall9() throws Exception; public void testCall10() throws Exception; public void testCall11() throws Exception; public void testFunctionCall1() throws Exception; public void testFunctionCall2() throws Exception; public void testFunctionCall3() throws Exception; public void testFunctionCall4() throws Exception; public void testFunctionCall5() throws Exception; public void testFunctionCall6() throws Exception; public void testFunctionCall7() throws Exception; public void testFunctionCall8() throws Exception; public void testFunctionCall9() throws Exception; public void testFunctionBind1() throws Exception; public void testFunctionBind2() throws Exception; public void testFunctionBind3() throws Exception; public void testFunctionBind4() throws Exception; public void testFunctionBind5() throws Exception; public void testGoogBind1() throws Exception; public void testGoogBind2() throws Exception; public void testCast2() throws Exception; public void testCast3() throws Exception; public void testCast3a() throws Exception; public void testCast4() throws Exception; public void testCast5() throws Exception; public void testCast5a() throws Exception; public void testCast6() throws Exception; public void testCast7() throws Exception; public void testCast8() throws Exception; public void testCast9() throws Exception; public void testCast10() throws Exception; public void testCast11() throws Exception; public void testCast12() throws Exception; public void testCast13() throws Exception; public void testCast14() throws Exception; public void testCast15() throws Exception; public void testCast16() throws Exception; public void testCast17a() throws Exception; public void testCast17b() throws Exception; public void testCast19() throws Exception; public void testCast20() throws Exception; public void testCast21() throws Exception; public void testCast22() throws Exception; public void testCast23() throws Exception; public void testCast24() throws Exception; public void testCast25() throws Exception; public void testCast26() throws Exception; public void testCast27() throws Exception; public void testCast27a() throws Exception; public void testCast28() throws Exception; public void testCast28a() throws Exception; public void testCast29a() throws Exception; public void testCast29b() throws Exception; public void testCast29c() throws Exception; public void testCast30() throws Exception; public void testCast31() throws Exception; public void testCast32() throws Exception; public void testCast33() throws Exception; public void testCast34a() throws Exception; public void testCast34b() throws Exception; public void testUnnecessaryCastToSuperType() throws Exception; public void testUnnecessaryCastToSameType() throws Exception; public void testUnnecessaryCastToUnknown() throws Exception; public void testUnnecessaryCastFromUnknown() throws Exception; public void testUnnecessaryCastToAndFromUnknown() throws Exception; public void testUnnecessaryCastToNonNullType() throws Exception; public void testUnnecessaryCastToStar() throws Exception; public void testNoUnnecessaryCastNoResolvedType() throws Exception; public void testNestedCasts() throws Exception; public void testNativeCast1() throws Exception; public void testNativeCast2() throws Exception; public void testNativeCast3() throws Exception; public void testNativeCast4() throws Exception; public void testBadConstructorCall() throws Exception; public void testTypeof() throws Exception; public void testTypeof2() throws Exception; public void testTypeof3() throws Exception; public void testConstructorType1() throws Exception; public void testConstructorType2() throws Exception; public void testConstructorType3() throws Exception; public void testConstructorType4() throws Exception; public void testConstructorType5() throws Exception; public void testConstructorType6() throws Exception; public void testConstructorType7() throws Exception; public void testConstructorType8() throws Exception; public void testConstructorType9() throws Exception; public void testConstructorType10() throws Exception; public void testConstructorType11() throws Exception; public void testConstructorType12() throws Exception; public void testBadStruct() throws Exception; public void testBadDict() throws Exception; public void testAnonymousPrototype1() throws Exception; public void testAnonymousPrototype2() throws Exception; public void testAnonymousType1() throws Exception; public void testAnonymousType2() throws Exception; public void testAnonymousType3() throws Exception; public void testBang1() throws Exception; public void testBang2() throws Exception; public void testBang3() throws Exception; public void testBang4() throws Exception; public void testBang5() throws Exception; public void testBang6() throws Exception; public void testBang7() throws Exception; public void testDefinePropertyOnNullableObject1() throws Exception; public void testDefinePropertyOnNullableObject2() throws Exception; public void testUnknownConstructorInstanceType1() throws Exception; public void testUnknownConstructorInstanceType2() throws Exception; public void testUnknownConstructorInstanceType3() throws Exception; public void testUnknownPrototypeChain() throws Exception; public void testNamespacedConstructor() throws Exception; public void testComplexNamespace() throws Exception; public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception; public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception; public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception; private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p); public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception; public void testDontAddMethodsIfNoConstructor() throws Exception; public void testFunctionAssignement() throws Exception; public void testAddMethodsPrototypeTwoWays() throws Exception; public void testPrototypePropertyTypes() throws Exception; public void testValueTypeBuiltInPrototypePropertyType() throws Exception; public void testDeclareBuiltInConstructor() throws Exception; public void testExtendBuiltInType1() throws Exception; public void testExtendBuiltInType2() throws Exception; public void testExtendFunction1() throws Exception; public void testExtendFunction2() throws Exception; public void testInheritanceCheck1() throws Exception; public void testInheritanceCheck2() throws Exception; public void testInheritanceCheck3() throws Exception; public void testInheritanceCheck4() throws Exception; public void testInheritanceCheck5() throws Exception; public void testInheritanceCheck6() throws Exception; public void testInheritanceCheck7() throws Exception; public void testInheritanceCheck8() throws Exception; public void testInheritanceCheck9_1() throws Exception; public void testInheritanceCheck9_2() throws Exception; public void testInheritanceCheck9_3() throws Exception; public void testInheritanceCheck10_1() throws Exception; public void testInheritanceCheck10_2() throws Exception; public void testInheritanceCheck10_3() throws Exception; public void testInterfaceInheritanceCheck11() throws Exception; public void testInheritanceCheck12() throws Exception; public void testInheritanceCheck13() throws Exception; public void testInheritanceCheck14() throws Exception; public void testInheritanceCheck15() throws Exception; public void testInheritanceCheck16() throws Exception; public void testInheritanceCheck17() throws Exception; public void testInterfacePropertyOverride1() throws Exception; public void testInterfacePropertyOverride2() throws Exception; public void testInterfaceInheritanceCheck1() throws Exception; public void testInterfaceInheritanceCheck2() throws Exception; public void testInterfaceInheritanceCheck3() throws Exception; public void testInterfaceInheritanceCheck4() throws Exception; public void testInterfaceInheritanceCheck5() throws Exception; public void testInterfaceInheritanceCheck6() throws Exception; public void testInterfaceInheritanceCheck7() throws Exception; public void testInterfaceInheritanceCheck8() throws Exception; public void testInterfaceInheritanceCheck9() throws Exception; public void testInterfaceInheritanceCheck10() throws Exception; public void testInterfaceInheritanceCheck12() throws Exception; public void testInterfaceInheritanceCheck13() throws Exception; public void testInterfaceInheritanceCheck14() throws Exception; public void testInterfaceInheritanceCheck15() throws Exception; public void testInterfaceInheritanceCheck16() throws Exception; public void testInterfacePropertyNotImplemented() throws Exception; public void testInterfacePropertyNotImplemented2() throws Exception; public void testInterfacePropertyNotImplemented3() throws Exception; public void testStubConstructorImplementingInterface() throws Exception; public void testObjectLiteral() throws Exception; public void testObjectLiteralDeclaration1() throws Exception; public void testObjectLiteralDeclaration2() throws Exception; public void testObjectLiteralDeclaration3() throws Exception; public void testObjectLiteralDeclaration4() throws Exception; public void testObjectLiteralDeclaration5() throws Exception; public void testObjectLiteralDeclaration6() throws Exception; public void testObjectLiteralDeclaration7() throws Exception; public void testCallDateConstructorAsFunction() throws Exception; public void testCallErrorConstructorAsFunction() throws Exception; public void testCallArrayConstructorAsFunction() throws Exception; public void testPropertyTypeOfUnionType() throws Exception; public void testAnnotatedPropertyOnInterface1() throws Exception; public void testAnnotatedPropertyOnInterface2() throws Exception; public void testAnnotatedPropertyOnInterface3() throws Exception; public void testAnnotatedPropertyOnInterface4() throws Exception; public void testWarnUnannotatedPropertyOnInterface5() throws Exception; public void testWarnUnannotatedPropertyOnInterface6() throws Exception; public void testDataPropertyOnInterface1() throws Exception; public void testDataPropertyOnInterface2() throws Exception; public void testDataPropertyOnInterface3() throws Exception; public void testDataPropertyOnInterface4() throws Exception; public void testWarnDataPropertyOnInterface3() throws Exception; public void testWarnDataPropertyOnInterface4() throws Exception; public void testErrorMismatchingPropertyOnInterface4() throws Exception; public void testErrorMismatchingPropertyOnInterface5() throws Exception; public void testErrorMismatchingPropertyOnInterface6() throws Exception; public void testInterfaceNonEmptyFunction() throws Exception; public void testDoubleNestedInterface() throws Exception; public void testStaticDataPropertyOnNestedInterface() throws Exception; public void testInterfaceInstantiation() throws Exception; public void testPrototypeLoop() throws Exception; public void testImplementsLoop() throws Exception; public void testImplementsExtendsLoop() throws Exception; public void testInterfaceExtendsLoop() throws Exception; public void testConversionFromInterfaceToRecursiveConstructor() throws Exception; public void testDirectPrototypeAssign() throws Exception; public void testResolutionViaRegistry1() throws Exception; public void testResolutionViaRegistry2() throws Exception; public void testResolutionViaRegistry3() throws Exception; public void testResolutionViaRegistry4() throws Exception; public void testResolutionViaRegistry5() throws Exception; public void testGatherProperyWithoutAnnotation1() throws Exception; public void testGatherProperyWithoutAnnotation2() throws Exception; public void testFunctionMasksVariableBug() throws Exception; public void testDfa1() throws Exception; public void testDfa2() throws Exception; public void testDfa3() throws Exception; public void testDfa4() throws Exception; public void testDfa5() throws Exception; public void testDfa6() throws Exception; public void testDfa7() throws Exception; public void testDfa8() throws Exception; public void testDfa9() throws Exception; public void testDfa10() throws Exception; public void testDfa11() throws Exception; public void testDfa12() throws Exception; public void testDfa13() throws Exception; public void testTypeInferenceWithCast1() throws Exception; public void testTypeInferenceWithCast2() throws Exception; public void testTypeInferenceWithCast3() throws Exception; public void testTypeInferenceWithCast4() throws Exception; public void testTypeInferenceWithCast5() throws Exception; public void testTypeInferenceWithClosure1() throws Exception; public void testTypeInferenceWithClosure2() throws Exception; public void testTypeInferenceWithNoEntry1() throws Exception; public void testTypeInferenceWithNoEntry2() throws Exception; public void testForwardPropertyReference() throws Exception; public void testNoForwardTypeDeclaration() throws Exception; public void testNoForwardTypeDeclarationAndNoBraces() throws Exception; public void testForwardTypeDeclaration1() throws Exception; public void testForwardTypeDeclaration2() throws Exception; public void testForwardTypeDeclaration3() throws Exception; public void testForwardTypeDeclaration4() throws Exception; public void testForwardTypeDeclaration5() throws Exception; public void testForwardTypeDeclaration6() throws Exception; public void testForwardTypeDeclaration7() throws Exception; public void testForwardTypeDeclaration8() throws Exception; public void testForwardTypeDeclaration9() throws Exception; public void testForwardTypeDeclaration10() throws Exception; public void testForwardTypeDeclaration12() throws Exception; public void testForwardTypeDeclaration13() throws Exception; public void testDuplicateTypeDef() throws Exception; public void testTypeDef1() throws Exception; public void testTypeDef2() throws Exception; public void testTypeDef3() throws Exception; public void testTypeDef4() throws Exception; public void testTypeDef5() throws Exception; public void testCircularTypeDef() throws Exception; public void testGetTypedPercent1() throws Exception; public void testGetTypedPercent2() throws Exception; public void testGetTypedPercent3() throws Exception; public void testGetTypedPercent4() throws Exception; public void testGetTypedPercent5() throws Exception; public void testGetTypedPercent6() throws Exception; private double getTypedPercent(String js) throws Exception; private static ObjectType getInstanceType(Node js1Node); public void testPrototypePropertyReference() throws Exception; public void testResolvingNamedTypes() throws Exception; public void testMissingProperty1() throws Exception; public void testMissingProperty2() throws Exception; public void testMissingProperty3() throws Exception; public void testMissingProperty4() throws Exception; public void testMissingProperty5() throws Exception; public void testMissingProperty6() throws Exception; public void testMissingProperty7() throws Exception; public void testMissingProperty8() throws Exception; public void testMissingProperty9() throws Exception; public void testMissingProperty10() throws Exception; public void testMissingProperty11() throws Exception; public void testMissingProperty12() throws Exception; public void testMissingProperty13() throws Exception; public void testMissingProperty14() throws Exception; public void testMissingProperty15() throws Exception; public void testMissingProperty16() throws Exception; public void testMissingProperty17() throws Exception; public void testMissingProperty18() throws Exception; public void testMissingProperty19() throws Exception; public void testMissingProperty20() throws Exception; public void testMissingProperty21() throws Exception; public void testMissingProperty22() throws Exception; public void testMissingProperty23() throws Exception; public void testMissingProperty24() throws Exception; public void testMissingProperty25() throws Exception; public void testMissingProperty26() throws Exception; public void testMissingProperty27() throws Exception; public void testMissingProperty28() throws Exception; public void testMissingProperty29() throws Exception; public void testMissingProperty30() throws Exception; public void testMissingProperty31() throws Exception; public void testMissingProperty32() throws Exception; public void testMissingProperty33() throws Exception; public void testMissingProperty34() throws Exception; public void testMissingProperty35() throws Exception; public void testMissingProperty36() throws Exception; public void testMissingProperty37() throws Exception; public void testMissingProperty38() throws Exception; public void testMissingProperty39() throws Exception; public void testMissingProperty40() throws Exception; public void testMissingProperty41() throws Exception; public void testMissingProperty42() throws Exception; public void testMissingProperty43() throws Exception; public void testReflectObject1() throws Exception; public void testReflectObject2() throws Exception; public void testLends1() throws Exception; public void testLends2() throws Exception; public void testLends3() throws Exception; public void testLends4() throws Exception; public void testLends5() throws Exception; public void testLends6() throws Exception; public void testLends7() throws Exception; public void testLends8() throws Exception; public void testLends9() throws Exception; public void testLends10() throws Exception; public void testLends11() throws Exception; public void testDeclaredNativeTypeEquality() throws Exception; public void testUndefinedVar() throws Exception; public void testFlowScopeBug1() throws Exception; public void testFlowScopeBug2() throws Exception; public void testAddSingletonGetter(); public void testTypeCheckStandaloneAST() throws Exception; public void testUpdateParameterTypeOnClosure() throws Exception; public void testTemplatedThisType1() throws Exception; public void testTemplatedThisType2() throws Exception; public void testTemplateType1() throws Exception; public void testTemplateType2() throws Exception; public void testTemplateType3() throws Exception; public void testTemplateType4() throws Exception; public void testTemplateType5() throws Exception; public void testTemplateType6() throws Exception; public void testTemplateType7() throws Exception; public void testTemplateType8() throws Exception; public void testTemplateType9() throws Exception; public void testTemplateType10() throws Exception; public void testTemplateType11() throws Exception; public void testTemplateType12() throws Exception; public void testTemplateType13() throws Exception; public void testTemplateType14() throws Exception; public void testTemplateType15() throws Exception; public void testTemplateType16() throws Exception; public void testTemplateType17() throws Exception; public void testTemplateType18() throws Exception; public void testTemplateType19() throws Exception; public void testTemplateType20() throws Exception; public void testTemplateTypeWithUnresolvedType() throws Exception; public void testTemplateTypeWithTypeDef1a() throws Exception; public void testTemplateTypeWithTypeDef1b() throws Exception; public void testTemplateTypeWithTypeDef2a() throws Exception; public void testTemplateTypeWithTypeDef2b() throws Exception; public void testTemplateTypeWithTypeDef2c() throws Exception; public void testTemplateTypeWithTypeDef2d() throws Exception; public void testTemplatedFunctionInUnion1() throws Exception; public void testTemplateTypeRecursion1() throws Exception; public void testTemplateTypeRecursion2() throws Exception; public void testTemplateTypeRecursion3() throws Exception; public void disable_testBadTemplateType4() throws Exception; public void disable_testBadTemplateType5() throws Exception; public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception; public void testFunctionLiteralDefinedThisArgument() throws Exception; public void testFunctionLiteralDefinedThisArgument2() throws Exception; public void testFunctionLiteralUnreadNullThisArgument() throws Exception; public void testUnionTemplateThisType() throws Exception; public void testActiveXObject() throws Exception; public void testRecordType1() throws Exception; public void testRecordType2() throws Exception; public void testRecordType3() throws Exception; public void testRecordType4() throws Exception; public void testRecordType5() throws Exception; public void testRecordType6() throws Exception; public void testRecordType7() throws Exception; public void testRecordType8() throws Exception; public void testDuplicateRecordFields1() throws Exception; public void testDuplicateRecordFields2() throws Exception; public void testMultipleExtendsInterface1() throws Exception; public void testMultipleExtendsInterface2() throws Exception; public void testMultipleExtendsInterface3() throws Exception; public void testMultipleExtendsInterface4() throws Exception; public void testMultipleExtendsInterface5() throws Exception; public void testMultipleExtendsInterface6() throws Exception; public void testMultipleExtendsInterfaceAssignment() throws Exception; public void testMultipleExtendsInterfaceParamPass() throws Exception; public void testBadMultipleExtendsClass() throws Exception; public void testInterfaceExtendsResolution() throws Exception; public void testPropertyCanBeDefinedInObject() throws Exception; private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType); public void testExtendedInterfacePropertiesCompatibility1() throws Exception; public void testExtendedInterfacePropertiesCompatibility2() throws Exception; public void testExtendedInterfacePropertiesCompatibility3() throws Exception; public void testExtendedInterfacePropertiesCompatibility4() throws Exception; public void testExtendedInterfacePropertiesCompatibility5() throws Exception; public void testExtendedInterfacePropertiesCompatibility6() throws Exception; public void testExtendedInterfacePropertiesCompatibility7() throws Exception; public void testExtendedInterfacePropertiesCompatibility8() throws Exception; public void testExtendedInterfacePropertiesCompatibility9() throws Exception; public void testGenerics1() throws Exception; public void testFilter0() throws Exception; public void testFilter1() throws Exception; public void testFilter2() throws Exception; public void testFilter3() throws Exception; public void testBackwardsInferenceGoogArrayFilter1() throws Exception; public void testBackwardsInferenceGoogArrayFilter2() throws Exception; public void testBackwardsInferenceGoogArrayFilter3() throws Exception; public void testBackwardsInferenceGoogArrayFilter4() throws Exception; public void testCatchExpression1() throws Exception; public void testCatchExpression2() throws Exception; public void testTemplatized1() throws Exception; public void testTemplatized2() throws Exception; public void testTemplatized3() throws Exception; public void testTemplatized4() throws Exception; public void testTemplatized5() throws Exception; public void testTemplatized6() throws Exception; public void testTemplatized7() throws Exception; public void disable_testTemplatized8() throws Exception; public void testTemplatized9() throws Exception; public void testTemplatized10() throws Exception; public void testTemplatized11() throws Exception; public void testIssue1058() throws Exception; public void testUnknownTypeReport() throws Exception; public void testUnknownForIn() throws Exception; public void testUnknownTypeDisabledByDefault() throws Exception; public void testTemplatizedTypeSubtypes2() throws Exception; public void testNonexistentPropertyAccessOnStruct() throws Exception; public void testNonexistentPropertyAccessOnStructOrObject() throws Exception; public void testNonexistentPropertyAccessOnExternStruct() throws Exception; public void testNonexistentPropertyAccessStructSubtype() throws Exception; public void testNonexistentPropertyAccessStructSubtype2() throws Exception; public void testIssue1024() throws Exception; private void testTypes(String js) throws Exception; private void testTypes(String js, String description) throws Exception; private void testTypes(String js, DiagnosticType type) throws Exception; private void testClosureTypes(String js, String description) throws Exception; private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception; void testTypes(String js, String description, boolean isError) throws Exception; void testTypes(String externs, String js, String description, boolean isError) throws Exception; private Node parseAndTypeCheck(String js); private Node parseAndTypeCheck(String externs, String js); private TypeCheckResult parseAndTypeCheckWithScope(String js); private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js); private Node typeCheck(Node n); private TypeCheck makeTypeCheck(); void testTypes(String js, String[] warnings) throws Exception; String suppressMissingProperty(String ... props); private TypeCheckResult(Node root, Scope scope);
dc11a59fe0465d210a7ec1f1997dfc38caf807e21e29008f57ee98ecdc2d9fb5
[ "com.google.javascript.jscomp.TypeCheckTest::testBug592170" ]
static final DiagnosticType UNEXPECTED_TOKEN = DiagnosticType.error( "JSC_INTERNAL_ERROR_UNEXPECTED_TOKEN", "Internal Error: Don't know how to handle {0}"); protected static final String OVERRIDING_PROTOTYPE_WITH_NON_OBJECT = "overriding prototype with non-object"; static final DiagnosticType DETERMINISTIC_TEST = DiagnosticType.warning( "JSC_DETERMINISTIC_TEST", "condition always evaluates to {2}\n" + "left : {0}\n" + "right: {1}"); static final DiagnosticType INEXISTENT_ENUM_ELEMENT = DiagnosticType.warning( "JSC_INEXISTENT_ENUM_ELEMENT", "element {0} does not exist on this enum"); static final DiagnosticType INEXISTENT_PROPERTY = DiagnosticType.disabled( "JSC_INEXISTENT_PROPERTY", "Property {0} never defined on {1}"); static final DiagnosticType INEXISTENT_PROPERTY_WITH_SUGGESTION = DiagnosticType.disabled( "JSC_INEXISTENT_PROPERTY", "Property {0} never defined on {1}. Did you mean {2}?"); protected static final DiagnosticType NOT_A_CONSTRUCTOR = DiagnosticType.warning( "JSC_NOT_A_CONSTRUCTOR", "cannot instantiate non-constructor"); static final DiagnosticType BIT_OPERATION = DiagnosticType.warning( "JSC_BAD_TYPE_FOR_BIT_OPERATION", "operator {0} cannot be applied to {1}"); static final DiagnosticType NOT_CALLABLE = DiagnosticType.warning( "JSC_NOT_FUNCTION_TYPE", "{0} expressions are not callable"); static final DiagnosticType CONSTRUCTOR_NOT_CALLABLE = DiagnosticType.warning( "JSC_CONSTRUCTOR_NOT_CALLABLE", "Constructor {0} should be called with the \"new\" keyword"); static final DiagnosticType FUNCTION_MASKS_VARIABLE = DiagnosticType.warning( "JSC_FUNCTION_MASKS_VARIABLE", "function {0} masks variable (IE bug)"); static final DiagnosticType MULTIPLE_VAR_DEF = DiagnosticType.warning( "JSC_MULTIPLE_VAR_DEF", "declaration of multiple variables with shared type information"); static final DiagnosticType ENUM_DUP = DiagnosticType.error("JSC_ENUM_DUP", "enum element {0} already defined"); static final DiagnosticType ENUM_NOT_CONSTANT = DiagnosticType.warning("JSC_ENUM_NOT_CONSTANT", "enum key {0} must be a syntactic constant"); static final DiagnosticType INVALID_INTERFACE_MEMBER_DECLARATION = DiagnosticType.warning( "JSC_INVALID_INTERFACE_MEMBER_DECLARATION", "interface members can only be empty property declarations," + " empty functions{0}"); static final DiagnosticType INTERFACE_FUNCTION_NOT_EMPTY = DiagnosticType.warning( "JSC_INTERFACE_FUNCTION_NOT_EMPTY", "interface member functions must have an empty body"); static final DiagnosticType CONFLICTING_SHAPE_TYPE = DiagnosticType.warning( "JSC_CONFLICTING_SHAPE_TYPE", "{1} cannot extend this type; {0}s can only extend {0}s"); static final DiagnosticType CONFLICTING_EXTENDED_TYPE = DiagnosticType.warning( "JSC_CONFLICTING_EXTENDED_TYPE", "{1} cannot extend this type; {0}s can only extend {0}s"); static final DiagnosticType CONFLICTING_IMPLEMENTED_TYPE = DiagnosticType.warning( "JSC_CONFLICTING_IMPLEMENTED_TYPE", "{0} cannot implement this type; " + "an interface can only extend, but not implement interfaces"); static final DiagnosticType BAD_IMPLEMENTED_TYPE = DiagnosticType.warning( "JSC_IMPLEMENTS_NON_INTERFACE", "can only implement interfaces"); static final DiagnosticType HIDDEN_SUPERCLASS_PROPERTY = DiagnosticType.warning( "JSC_HIDDEN_SUPERCLASS_PROPERTY", "property {0} already defined on superclass {1}; " + "use @override to override it"); static final DiagnosticType HIDDEN_INTERFACE_PROPERTY = DiagnosticType.warning( "JSC_HIDDEN_INTERFACE_PROPERTY", "property {0} already defined on interface {1}; " + "use @override to override it"); static final DiagnosticType HIDDEN_SUPERCLASS_PROPERTY_MISMATCH = DiagnosticType.warning("JSC_HIDDEN_SUPERCLASS_PROPERTY_MISMATCH", "mismatch of the {0} property type and the type " + "of the property it overrides from superclass {1}\n" + "original: {2}\n" + "override: {3}"); static final DiagnosticType UNKNOWN_OVERRIDE = DiagnosticType.warning( "JSC_UNKNOWN_OVERRIDE", "property {0} not defined on any superclass of {1}"); static final DiagnosticType INTERFACE_METHOD_OVERRIDE = DiagnosticType.warning( "JSC_INTERFACE_METHOD_OVERRIDE", "property {0} is already defined by the {1} extended interface"); static final DiagnosticType UNKNOWN_EXPR_TYPE = DiagnosticType.disabled("JSC_UNKNOWN_EXPR_TYPE", "could not determine the type of this expression"); static final DiagnosticType UNRESOLVED_TYPE = DiagnosticType.warning("JSC_UNRESOLVED_TYPE", "could not resolve the name {0} to a type"); static final DiagnosticType WRONG_ARGUMENT_COUNT = DiagnosticType.warning( "JSC_WRONG_ARGUMENT_COUNT", "Function {0}: called with {1} argument(s). " + "Function requires at least {2} argument(s){3}."); static final DiagnosticType ILLEGAL_IMPLICIT_CAST = DiagnosticType.warning( "JSC_ILLEGAL_IMPLICIT_CAST", "Illegal annotation on {0}. @implicitCast may only be used in " + "externs."); static final DiagnosticType INCOMPATIBLE_EXTENDED_PROPERTY_TYPE = DiagnosticType.warning( "JSC_INCOMPATIBLE_EXTENDED_PROPERTY_TYPE", "Interface {0} has a property {1} with incompatible types in " + "its super interfaces {2} and {3}"); static final DiagnosticType EXPECTED_THIS_TYPE = DiagnosticType.warning( "JSC_EXPECTED_THIS_TYPE", "\"{0}\" must be called with a \"this\" type"); static final DiagnosticType IN_USED_WITH_STRUCT = DiagnosticType.warning("JSC_IN_USED_WITH_STRUCT", "Cannot use the IN operator with structs"); static final DiagnosticType ILLEGAL_PROPERTY_CREATION = DiagnosticType.warning("JSC_ILLEGAL_PROPERTY_CREATION", "Cannot add a property to a struct instance " + "after it is constructed."); static final DiagnosticType ILLEGAL_OBJLIT_KEY = DiagnosticType.warning( "ILLEGAL_OBJLIT_KEY", "Illegal key, the object literal is a {0}"); static final DiagnosticGroup ALL_DIAGNOSTICS = new DiagnosticGroup( DETERMINISTIC_TEST, INEXISTENT_ENUM_ELEMENT, INEXISTENT_PROPERTY, NOT_A_CONSTRUCTOR, BIT_OPERATION, NOT_CALLABLE, CONSTRUCTOR_NOT_CALLABLE, FUNCTION_MASKS_VARIABLE, MULTIPLE_VAR_DEF, ENUM_DUP, ENUM_NOT_CONSTANT, INVALID_INTERFACE_MEMBER_DECLARATION, INTERFACE_FUNCTION_NOT_EMPTY, CONFLICTING_SHAPE_TYPE, CONFLICTING_EXTENDED_TYPE, CONFLICTING_IMPLEMENTED_TYPE, BAD_IMPLEMENTED_TYPE, HIDDEN_SUPERCLASS_PROPERTY, HIDDEN_INTERFACE_PROPERTY, HIDDEN_SUPERCLASS_PROPERTY_MISMATCH, UNKNOWN_OVERRIDE, INTERFACE_METHOD_OVERRIDE, UNRESOLVED_TYPE, WRONG_ARGUMENT_COUNT, ILLEGAL_IMPLICIT_CAST, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE, EXPECTED_THIS_TYPE, IN_USED_WITH_STRUCT, ILLEGAL_PROPERTY_CREATION, ILLEGAL_OBJLIT_KEY, RhinoErrorReporter.TYPE_PARSE_ERROR, TypedScopeCreator.UNKNOWN_LENDS, TypedScopeCreator.LENDS_ON_NON_OBJECT, TypedScopeCreator.CTOR_INITIALIZER, TypedScopeCreator.IFACE_INITIALIZER, FunctionTypeBuilder.THIS_TYPE_NON_OBJECT); private final AbstractCompiler compiler; private final TypeValidator validator; private final ReverseAbstractInterpreter reverseInterpreter; private final JSTypeRegistry typeRegistry; private Scope topScope; private MemoizedScopeCreator scopeCreator; private final CheckLevel reportMissingOverride; private final boolean reportUnknownTypes; private boolean reportMissingProperties = true; private InferJSDocInfo inferJSDocInfo = null; private int typedCount = 0; private int nullCount = 0; private int unknownCount = 0; private boolean inExterns; private int noTypeCheckSection = 0; private Method editDistance;
public void testBug592170() throws Exception
private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n";
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheck25() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({b: 'abc'});", "actual parameter 1 of foo does not match formal parameter\n" + "found : {a: (number|undefined), b: string}\n" + "required: {a: number}"); } public void testTypeCheck26() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({a: 'abc'});", "actual parameter 1 of foo does not match formal parameter\n" + "found : {a: (number|string)}\n" + "required: {a: number}"); } public void testTypeCheck27() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({a: 123});"); } public void testTypeCheck28() throws Exception { testTypes("function foo(/** ? */ obj) {};" + "foo({a: 123});"); } public void testTypeCheckInlineReturns() throws Exception { testTypes( "function /** string */ foo(x) { return x; }" + "var /** number */ a = foo('abc');", "initializing variable\n" + "found : string\n" + "required: number"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = unknown;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = unknown;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = unknown;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testGoodExtends18() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor\n" + " * @template T */\n" + "function C() {}\n" + "/** @constructor\n" + " * @extends {C.<string>} */\n" + "function D() {};\n" + "goog.inherits(D, C);\n" + "(new D())"); } public void testGoodExtends19() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */\n" + "function C() {}\n" + "" + "/** @interface\n" + " * @template T */\n" + "function D() {}\n" + "/** @param {T} t */\n" + "D.prototype.method;\n" + "" + "/** @constructor\n" + " * @template T\n" + " * @extends {C}\n" + " * @implements {D.<T>} */\n" + "function E() {};\n" + "goog.inherits(E, C);\n" + "/** @override */\n" + "E.prototype.method = function(t) {};\n" + "" + "var e = /** @type {E.<string>} */ (new E());\n" + "e.method(3);", "actual parameter 1 of E.prototype.method does not match formal " + "parameter\n" + "found : number\n" + "required: string"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testSetprop15() throws Exception { // Create static property on struct testTypes( "/** @interface */\n" + "function Peelable() {};\n" + "/** @return {undefined} */\n" + "Peelable.prototype.peel;\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Fruit() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Fruit}\n" + " * @implements {Peelable}\n" + " */\n" + "function Banana() { };\n" + "function f() {};\n" + "/** @override */\n" + "Banana.prototype.peel = f;"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar())['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = unknown;" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = unknown;" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = unknown;" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testNamespaceType1() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @param {x.} y */ function f(y) {};", "Parse error. Namespaces not supported yet (x.)"); } public void testNamespaceType2() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @namespace */ x.y = {};" + "/** @param {x.y.} y */ function f(y) {}", "Parse error. Namespaces not supported yet (x.y.)"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } public void testIssue1023() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "(function () {" + " F.prototype = {" + " /** @param {string} x */" + " bar: function (x) { }" + " };" + "})();" + "(new F()).bar(true)", "actual parameter 1 of F.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testIssue1047() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " */\n" + "function C2() {}\n" + "\n" + "/**\n" + " * @constructor\n" + " */\n" + "function C3(c2) {\n" + " /**\n" + " * @type {C2} \n" + " * @private\n" + " */\n" + " this.c2_;\n" + "\n" + " var x = this.c2_.prop;\n" + "}", "Property prop never defined on C2"); } public void testIssue1056() throws Exception { testTypes( "/** @type {Array} */ var x = null;" + "x.push('hi');", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testIssue1072() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @return {number}\n" + " */\n" + "var f1 = function (x) {\n" + " return 3;\n" + "};\n" + "\n" + "/** Function */\n" + "var f2 = function (x) {\n" + " if (!x) throw new Error()\n" + " return /** @type {number} */ (f1('x'))\n" + "}\n" + "\n" + "/**\n" + " * @param {string} x\n" + " */\n" + "var f3 = function (x) {};\n" + "\n" + "f1(f3);", "actual parameter 1 of f1 does not match formal parameter\n" + "found : function (string): undefined\n" + "required: string"); } public void testIssue1123() throws Exception { testTypes( "/** @param {function(number)} g */ function f(g) {}" + "f(function(a, b) {})", "actual parameter 1 of f does not match formal parameter\n" + "found : function (?, ?): undefined\n" + "required: function (number): ?"); } public void testEnums() throws Exception { testTypes( "var outer = function() {" + " /** @enum {number} */" + " var Level = {" + " NONE: 0," + " };" + " /** @type {!Level} */" + " var l = Level.NONE;" + "}"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testUnnecessaryCastToSuperType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Base}\n" + " */\n" + "function Derived() {}\n" + "var d = new Derived();\n" + "var b = /** @type {!Base} */ (d);", "unnecessary cast\n" + "from: Derived\n" + "to : Base" ); } public void testUnnecessaryCastToSameType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var b = new Base();\n" + "var c = /** @type {!Base} */ (b);", "unnecessary cast\n" + "from: Base\n" + "to : Base" ); } /** * Checks that casts to unknown ({?}) are not marked as unnecessary. */ public void testUnnecessaryCastToUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var b = new Base();\n" + "var c = /** @type {?} */ (b);"); } /** * Checks that casts from unknown ({?}) are not marked as unnecessary. */ public void testUnnecessaryCastFromUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "/** @type {?} */ var x;\n" + "var y = /** @type {Base} */ (x);"); } public void testUnnecessaryCastToAndFromUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */ function A() {}\n" + "/** @constructor */ function B() {}\n" + "/** @type {!Array.<!A>} */ var x = " + "/** @type {!Array.<?>} */( /** @type {!Array.<!B>} */([]) );"); } /** * Checks that a cast from {?Base} to {!Base} is not considered unnecessary. */ public void testUnnecessaryCastToNonNullType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var c = /** @type {!Base} */ (random ? new Base() : null);" ); } public void testUnnecessaryCastToStar() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var c = /** @type {*} */ (new Base());", "unnecessary cast\n" + "from: Base\n" + "to : *" ); } public void testNoUnnecessaryCastNoResolvedType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testClosureTypes( "var goog = {};\n" + "goog.addDependency = function(a,b,c){};\n" + // A is NoResolvedType. "goog.addDependency('a.js', ['A'], []);\n" + // B is a normal type. "/** @constructor @struct */ function B() {}\n" + "/**\n" + " * @constructor\n" + " * @template T\n" + " */\n" + "function C() { this.t; }\n" + "/**\n" + " * @param {!C.<T>} c\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "function getT(c) { return c.t; }\n" + "/** @type {!C.<!A>} */\n" + "var c = new C();\n" + // Casting from NoResolvedType. "var b = /** @type {!B} */ (getT(c));\n" + // Casting to NoResolvedType. "var a = /** @type {!A} */ (new B());\n", null); // No warning expected. } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function() { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType15() throws Exception { testTypes( "/**" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType16() throws Exception { testTypes( "/** @constructor */ function C() {\n" + " /** @type {number} */ this.foo = 1\n" + "}\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn(new C());", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType17() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn(new C());", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType18() throws Exception { // Until template types can be restricted to exclude undefined, they // are always optional. testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({});"); } public void testTemplateType19() throws Exception { testTypes( "/**\n" + " * @param {T} t\n" + " * @param {U} u\n" + " * @return {{t:T, u:U}} \n" + " * @template T,U\n" + " */\n" + "function fn(t, u) { return {t:t, u:u}; }\n" + "/** @type {null} */ var x = fn(1, 'str');", "initializing variable\n" + "found : {t: number, u: string}\n" + "required: null"); } public void testTemplateType20() throws Exception { // "this" types is inferred when the parameters are declared. testTypes( "/** @constructor */ function C() {\n" + " /** @type {void} */ this.x;\n" + "}\n" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(new C, /** @param {number} a */ function(a) {this.x = a;});", "assignment to property x of C\n" + "found : number\n" + "required: undefined"); } public void testTemplateTypeWithUnresolvedType() throws Exception { testClosureTypes( "var goog = {};\n" + "goog.addDependency = function(a,b,c){};\n" + "goog.addDependency('a.js', ['Color'], []);\n" + "/** @interface @template T */ function C() {}\n" + "/** @return {!Color} */ C.prototype.method;\n" + "/** @constructor @implements {C} */ function D() {}\n" + "/** @override */ D.prototype.method = function() {};", null); // no warning expected. } public void testTemplateTypeWithTypeDef1a() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "" + "/** @type {Generic.<!Foo>} */ var x;\n" + "/** @type {Generic.<!Bar>} */ var y;\n" + "" + "x = y;\n" + // no warning "/** @type null */ var z1 = y;\n" + "", "initializing variable\n" + "found : (Generic.<Foo>|null)\n" + "required: null"); } public void testTemplateTypeWithTypeDef1b() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "" + "/** @type {Generic.<!Foo>} */ var x;\n" + "/** @type {Generic.<!Bar>} */ var y;\n" + "" + "y = x;\n" + // no warning. "/** @type null */ var z1 = x;\n" + "", "initializing variable\n" + "found : (Generic.<Foo>|null)\n" + "required: null"); } public void testTemplateTypeWithTypeDef2a() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Bar> */ x) {}\n" + "/** @type {Generic.<!Foo>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2b() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Bar> */ x) {}\n" + "/** @type {Generic.<!Bar>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2c() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Foo> */ x) {}\n" + "/** @type {Generic.<!Foo>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2d() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Foo> */ x) {}\n" + "/** @type {Generic.<!Bar>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplatedFunctionInUnion1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)|{fn:Function}} z\n" + "* @template T\n" + "*/\n" + "function f(x, z) {}\n" + "f([], function() { /** @type {string} */ var x = this });", "initializing variable\n" + "found : Array\n" + "required: string"); } public void testTemplateTypeRecursion1() throws Exception { testTypes( "/** @typedef {{a: D2}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void testTemplateTypeRecursion2() throws Exception { testTypes( "/** @typedef {{a: D2}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "/** @type {D1} */ var x;" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void testTemplateTypeRecursion3() throws Exception { testTypes( "/** @typedef {{a: function(D2)}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "/** @type {D1} */ var x;" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item; return false});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testTemplatized6() throws Exception { testTypes( "/** @interface */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "" + "/** @constructor \n" + " * @implements {I}\n" + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "" + "/** @type {null} */ var some = new C().method('str');", "initializing variable\n" + "found : string\n" + "required: null"); } public void testTemplatized7() throws Exception { testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @implements {I.<number>}\n" + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {null} */ var some = new C().method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void disable_testTemplatized8() throws Exception { // TODO(johnlenz): this should generate a warning but does not. testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @implements {I.<R>}\n" + " * @template R\n " + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {C.<number>} var x = new C();" + "/** @type {null} */ var some = x.method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void testTemplatized9() throws Exception { testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @param {R} a\n" + " * @implements {I.<R>}\n" + " * @template R\n " + " */ function C(a){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {null} */ var some = new C(1).method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void testTemplatized10() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " */\n" + "function Parent() {};\n" + "\n" + "/** @param {T} x */\n" + "Parent.prototype.method = function(x) {};\n" + "\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent.<string>}\n" + " */\n" + "function Child() {};\n" + "Child.prototype = new Parent();\n" + "\n" + "(new Child()).method(123); \n", "actual parameter 1 of Parent.prototype.method does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTemplatized11() throws Exception { testTypes( "/** \n" + " * @template T\n" + " * @constructor\n" + " */\n" + "function C() {}\n" + "\n" + "/**\n" + " * @param {T|K} a\n" + " * @return {T}\n" + " * @template K\n" + " */\n" + "C.prototype.method = function (a) {};\n" + "\n" + // method returns "?" "/** @type {void} */ var x = new C().method(1);"); } public void testIssue1058() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template CLASS\n" + " */\n" + "var Class = function() {};\n" + "\n" + "/**\n" + " * @param {function(CLASS):CLASS} a\n" + " * @template T\n" + " */\n" + "Class.prototype.foo = function(a) {\n" + " return 'string';\n" + "};\n" + "\n" + "/** @param {number} a\n" + " * @return {string} */\n" + "var a = function(a) { return '' };\n" + "\n" + "new Class().foo(a);"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownForIn() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("var x = {'a':1}; var y; \n for(\ny\n in x) {}"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};" + "" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {A}\n" + " */\n" + "var B = function() { this.bar = function(){}; };" + "" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype2() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " this.x = 123;\n" + "}\n" + "var objlit = /** @struct */ { y: 234 };\n" + "Foo.prototype = objlit;\n" + "var n = objlit.x;\n", "Property x never defined on Foo.prototype", false); } public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { compiler.initOptions(compiler.getOptions()); Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, false) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
[ { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "check", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Z)V", "line_numbers": [ "418", "420", "421", "422", "423", "424", "426", "428" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "checkDeclaredPropertyInheritance", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/jstype/FunctionType;Ljava/lang/String;Lcom/google/javascript/rhino/JSDocInfo;Lcom/google/javascript/rhino/jstype/JSType;)V", "line_numbers": [ "1170", "1171", "1174", "1175", "1177", "1181", "1182", "1183", "1184", "1185", "1188", "1191", "1193", "1195", "1196", "1198", "1199", "1201", "1203", "1205", "1207", "1209", "1211", "1216", "1220", "1223", "1227", "1230", "1232", "1236", "1242", "1248", "1250", "1252", "1254", "1255", "1259", "1260", "1265", "1267", "1268", "1269", "1271", "1272", "1274", "1281", "1282", "1286", "1290" ], "method_line_rate": 0.2653061224489796 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "checkEnumAlias", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/JSDocInfo;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1982", "1983", "1986", "1987", "1988", "1991", "1992", "1994", "1997" ], "method_line_rate": 0.2222222222222222 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "checkNoTypeCheckSection", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Z)V", "line_numbers": [ "432", "438", "439", "440", "441", "443", "446", "449" ], "method_line_rate": 0.625 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "checkPropCreation", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1025", "1026", "1027", "1028", "1029", "1032" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "checkPropertyAccess", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Ljava/lang/String;Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1441", "1442", "1443", "1444", "1445", "1449", "1452", "1453", "1455", "1460", "1463" ], "method_line_rate": 0.2727272727272727 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "checkPropertyInheritanceOnGetpropAssign", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;Ljava/lang/String;Lcom/google/javascript/rhino/JSDocInfo;Lcom/google/javascript/rhino/jstype/JSType;)V", "line_numbers": [ "1048", "1049", "1050", "1052", "1053", "1054", "1055", "1056", "1057", "1063" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "doPercentTypedAccounting", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "892", "893", "894", "895", "896", "897", "899", "901", "903" ], "method_line_rate": 0.5555555555555556 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "ensureTyped", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "2027", "2028" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "ensureTyped", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/jstype/JSType;)V", "line_numbers": [ "2054", "2058", "2059", "2060", "2061", "2063", "2068", "2069", "2071" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "ensureTyped", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/jstype/JSTypeNative;)V", "line_numbers": [ "2031", "2032" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "getJSType", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "2004", "2005", "2010", "2012" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "getNativeType", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSTypeNative;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "2083" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "hasUnknownOrEmptySupertype", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/FunctionType;)Z", "line_numbers": [ "1297", "1298", "1303", "1305", "1306", "1308", "1310", "1312", "1313", "1314", "1316", "1317" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "process", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "382", "383", "385", "386", "387", "390", "391", "393", "394" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "processForTesting", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)Lcom/google/javascript/jscomp/Scope;", "line_numbers": [ "398", "399", "401", "402", "404", "405", "407", "410", "411", "413" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "propertyIsImplicitCast", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/ObjectType;Ljava/lang/String;)Z", "line_numbers": [ "1150", "1151", "1152", "1153", "1156" ], "method_line_rate": 0.8 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "shouldTraverse", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)Z", "line_numbers": [ "461", "462", "465", "466", "467", "474", "482" ], "method_line_rate": 0.8571428571428571 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visit", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "501", "503", "505", "506", "507", "511", "512", "513", "515", "517", "518", "523", "524", "527", "528", "531", "532", "536", "537", "540", "541", "544", "545", "548", "549", "552", "553", "556", "557", "562", "565", "566", "569", "570", "573", "574", "576", "579", "583", "584", "587", "588", "589", "592", "593", "596", "597", "598", "601", "602", "603", "607", "608", "609", "610", "611", "614", "615", "618", "619", "622", "623", "626", "627", "628", "631", "632", "636", "637", "638", "639", "645", "646", "648", "649", "650", "652", "653", "656", "657", "668", "669", "671", "672", "673", "674", "675", "679", "681", "686", "687", "690", "691", "698", "699", "700", "701", "703", "704", "706", "713", "714", "715", "717", "718", "719", "722", "723", "726", "727", "728", "729", "730", "731", "732", "734", "735", "738", "739", "740", "741", "743", "745", "746", "749", "750", "751", "764", "778", "779", "782", "783", "786", "787", "788", "789", "790", "793", "794", "795", "796", "797", "801", "802", "819", "820", "826", "827", "830", "831", "832", "833", "836", "837", "844", "845", "848", "850", "852", "855", "856", "857", "858", "859", "860", "864", "865", "870", "872", "873", "876", "877" ], "method_line_rate": 0.18604651162790697 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visitAssign", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "914", "915", "916", "919", "920", "921", "922", "923", "927", "928", "929", "931", "935", "936", "942", "943", "944", "945", "946", "947", "950", "951", "952", "955", "963", "965", "966", "969", "970", "971", "974", "976", "983", "992", "993", "995", "996", "997", "998", "1001", "1004", "1007", "1008", "1014", "1015", "1016", "1018", "1020", "1022" ], "method_line_rate": 0.4489795918367347 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visitFunction", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1700", "1701", "1702", "1703", "1704", "1707", "1711", "1712", "1713", "1714", "1716", "1717", "1722", "1723", "1724", "1725", "1726", "1728", "1730", "1732", "1733", "1735", "1736", "1738", "1740", "1742", "1744", "1745", "1747", "1751", "1754", "1756", "1758", "1760", "1761", "1762", "1764", "1765", "1768" ], "method_line_rate": 0.3333333333333333 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visitGetProp", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1415", "1416", "1417", "1419", "1420", "1421", "1423", "1425", "1426" ], "method_line_rate": 0.8888888888888888 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visitName", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)Z", "line_numbers": [ "1374", "1375", "1379", "1383", "1384", "1387", "1388", "1389", "1390", "1391", "1392", "1393", "1394", "1398", "1399" ], "method_line_rate": 0.5333333333333333 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visitReturn", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1870", "1872", "1873", "1875", "1879", "1880", "1884", "1886", "1887", "1888", "1890", "1894", "1897" ], "method_line_rate": 0.7692307692307693 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visitVar", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1601", "1602", "1603", "1605", "1607", "1608", "1609", "1610", "1612", "1613", "1614", "1617", "1618", "1619", "1621", "1625", "1626" ], "method_line_rate": 0.4117647058823529 } ]
public class TestTokenBuffer extends BaseMapTest
public void testWithJsonParserSequenceSimple() throws IOException { // Let's join a TokenBuffer with JsonParser first TokenBuffer buf = new TokenBuffer(null, false); buf.writeStartArray(); buf.writeString("test"); JsonParser p = createParserUsingReader("[ true, null ]"); JsonParserSequence seq = JsonParserSequence.createFlattened(false, buf.asParser(), p); assertEquals(2, seq.containedParsersCount()); assertFalse(p.isClosed()); assertFalse(seq.hasCurrentToken()); assertNull(seq.getCurrentToken()); assertNull(seq.getCurrentName()); assertToken(JsonToken.START_ARRAY, seq.nextToken()); assertToken(JsonToken.VALUE_STRING, seq.nextToken()); assertEquals("test", seq.getText()); // end of first parser input, should switch over: assertToken(JsonToken.START_ARRAY, seq.nextToken()); assertToken(JsonToken.VALUE_TRUE, seq.nextToken()); assertToken(JsonToken.VALUE_NULL, seq.nextToken()); assertToken(JsonToken.END_ARRAY, seq.nextToken()); /* 17-Jan-2009, tatus: At this point, we may or may not get an * exception, depending on how underlying parsers work. * Ideally this should be fixed, probably by asking underlying * parsers to disable checking for balanced start/end markers. */ // for this particular case, we won't get an exception tho... assertNull(seq.nextToken()); // not an error to call again... assertNull(seq.nextToken()); // also: original parsers should be closed assertTrue(p.isClosed()); p.close(); buf.close(); seq.close(); }
// protected final void _appendValue(JsonToken type, Object value); // @Override // protected void _reportUnsupportedOperation(); // @Deprecated // since 2.9 // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds); // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds, // JsonStreamContext parentContext); // public void setLocation(JsonLocation l); // @Override // public ObjectCodec getCodec(); // @Override // public void setCodec(ObjectCodec c); // @Override // public Version version(); // public JsonToken peekNextToken() throws IOException; // @Override // public void close() throws IOException; // @Override // public JsonToken nextToken() throws IOException; // @Override // public String nextFieldName() throws IOException; // @Override // public boolean isClosed(); // @Override // public JsonStreamContext getParsingContext(); // @Override // public JsonLocation getTokenLocation(); // @Override // public JsonLocation getCurrentLocation(); // @Override // public String getCurrentName(); // @Override // public void overrideCurrentName(String name); // @Override // public String getText(); // @Override // public char[] getTextCharacters(); // @Override // public int getTextLength(); // @Override // public int getTextOffset(); // @Override // public boolean hasTextCharacters(); // @Override // public boolean isNaN(); // @Override // public BigInteger getBigIntegerValue() throws IOException; // @Override // public BigDecimal getDecimalValue() throws IOException; // @Override // public double getDoubleValue() throws IOException; // @Override // public float getFloatValue() throws IOException; // @Override // public int getIntValue() throws IOException; // @Override // public long getLongValue() throws IOException; // @Override // public NumberType getNumberType() throws IOException; // @Override // public final Number getNumberValue() throws IOException; // private final boolean _smallerThanInt(Number n); // private final boolean _smallerThanLong(Number n); // protected int _convertNumberToInt(Number n) throws IOException; // protected long _convertNumberToLong(Number n) throws IOException; // @Override // public Object getEmbeddedObject(); // @Override // @SuppressWarnings("resource") // public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; // @Override // public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; // @Override // public boolean canReadObjectId(); // @Override // public boolean canReadTypeId(); // @Override // public Object getTypeId(); // @Override // public Object getObjectId(); // protected final Object _currentObject(); // protected final void _checkIsNumber() throws JsonParseException; // @Override // protected void _handleEOF() throws JsonParseException; // public Segment(); // public JsonToken type(int index); // public int rawType(int index); // public Object get(int index); // public Segment next(); // public boolean hasIds(); // public Segment append(int index, JsonToken tokenType); // public Segment append(int index, JsonToken tokenType, // Object objectId, Object typeId); // public Segment append(int index, JsonToken tokenType, Object value); // public Segment append(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType); // private void set(int index, JsonToken tokenType, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType, Object value); // private void set(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private final void assignNativeIds(int index, Object objectId, Object typeId); // private Object findObjectId(int index); // private Object findTypeId(int index); // private final int _typeIdIndex(int i); // private final int _objectIdIndex(int i); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.util; // // import java.io.*; // import java.math.BigDecimal; // import java.math.BigInteger; // import java.util.UUID; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.JsonParser.NumberType; // import com.fasterxml.jackson.core.io.SerializedString; // import com.fasterxml.jackson.core.util.JsonParserSequence; // import com.fasterxml.jackson.databind.*; // // // // public class TestTokenBuffer extends BaseMapTest // { // private final ObjectMapper MAPPER = objectMapper(); // // public void testBasicConfig() throws IOException; // public void testSimpleWrites() throws IOException; // public void testSimpleNumberWrites() throws IOException; // public void testNumberOverflowInt() throws IOException; // public void testNumberOverflowLong() throws IOException; // public void testParentContext() throws IOException; // public void testSimpleArray() throws IOException; // public void testSimpleObject() throws IOException; // public void testWithJSONSampleDoc() throws Exception; // public void testAppend() throws IOException; // public void testWithUUID() throws IOException; // public void testOutputContext() throws IOException; // private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); // private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); // public void testParentSiblingContext() throws IOException; // public void testBasicSerialize() throws IOException; // public void testWithJsonParserSequenceSimple() throws IOException; // @SuppressWarnings("resource") // public void testWithMultipleJsonParserSequences() throws IOException; // public void testRawValues() throws Exception; // public void testEmbeddedObjectCoerceCheck() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testWithJsonParserSequenceSimple` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Tests to verify interaction of TokenBuffer and JsonParserSequence /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/util/TestTokenBuffer.java
package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.TreeMap; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.base.ParserMinimalBase; import com.fasterxml.jackson.core.json.JsonWriteContext; import com.fasterxml.jackson.core.util.ByteArrayBuilder; import com.fasterxml.jackson.databind.*;
public TokenBuffer(ObjectCodec codec, boolean hasNativeIds); public TokenBuffer(JsonParser p); public TokenBuffer(JsonParser p, DeserializationContext ctxt); public static TokenBuffer asCopyOfValue(JsonParser p) throws IOException; public TokenBuffer overrideParentContext(JsonStreamContext ctxt); public TokenBuffer forceUseOfBigDecimal(boolean b); @Override public Version version(); public JsonParser asParser(); public JsonParser asParserOnFirstToken() throws IOException; public JsonParser asParser(ObjectCodec codec); public JsonParser asParser(JsonParser src); public JsonToken firstToken(); @SuppressWarnings("resource") public TokenBuffer append(TokenBuffer other) throws IOException; public void serialize(JsonGenerator gen) throws IOException; public TokenBuffer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException; @Override @SuppressWarnings("resource") public String toString(); private final void _appendNativeIds(StringBuilder sb); @Override public JsonGenerator enable(Feature f); @Override public JsonGenerator disable(Feature f); @Override public boolean isEnabled(Feature f); @Override public int getFeatureMask(); @Override @Deprecated public JsonGenerator setFeatureMask(int mask); @Override public JsonGenerator overrideStdFeatures(int values, int mask); @Override public JsonGenerator useDefaultPrettyPrinter(); @Override public JsonGenerator setCodec(ObjectCodec oc); @Override public ObjectCodec getCodec(); @Override public final JsonWriteContext getOutputContext(); @Override public boolean canWriteBinaryNatively(); @Override public void flush() throws IOException; @Override public void close() throws IOException; @Override public boolean isClosed(); @Override public final void writeStartArray() throws IOException; @Override public final void writeEndArray() throws IOException; @Override public final void writeStartObject() throws IOException; @Override // since 2.8 public void writeStartObject(Object forValue) throws IOException; @Override public final void writeEndObject() throws IOException; @Override public final void writeFieldName(String name) throws IOException; @Override public void writeFieldName(SerializableString name) throws IOException; @Override public void writeString(String text) throws IOException; @Override public void writeString(char[] text, int offset, int len) throws IOException; @Override public void writeString(SerializableString text) throws IOException; @Override public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException; @Override public void writeUTF8String(byte[] text, int offset, int length) throws IOException; @Override public void writeRaw(String text) throws IOException; @Override public void writeRaw(String text, int offset, int len) throws IOException; @Override public void writeRaw(SerializableString text) throws IOException; @Override public void writeRaw(char[] text, int offset, int len) throws IOException; @Override public void writeRaw(char c) throws IOException; @Override public void writeRawValue(String text) throws IOException; @Override public void writeRawValue(String text, int offset, int len) throws IOException; @Override public void writeRawValue(char[] text, int offset, int len) throws IOException; @Override public void writeNumber(short i) throws IOException; @Override public void writeNumber(int i) throws IOException; @Override public void writeNumber(long l) throws IOException; @Override public void writeNumber(double d) throws IOException; @Override public void writeNumber(float f) throws IOException; @Override public void writeNumber(BigDecimal dec) throws IOException; @Override public void writeNumber(BigInteger v) throws IOException; @Override public void writeNumber(String encodedValue) throws IOException; @Override public void writeBoolean(boolean state) throws IOException; @Override public void writeNull() throws IOException; @Override public void writeObject(Object value) throws IOException; @Override public void writeTree(TreeNode node) throws IOException; @Override public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException; @Override public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength); @Override public boolean canWriteTypeId(); @Override public boolean canWriteObjectId(); @Override public void writeTypeId(Object id); @Override public void writeObjectId(Object id); @Override // since 2.8 public void writeEmbeddedObject(Object object) throws IOException; @Override public void copyCurrentEvent(JsonParser p) throws IOException; @Override public void copyCurrentStructure(JsonParser p) throws IOException; private final void _checkNativeIds(JsonParser jp) throws IOException; protected final void _append(JsonToken type); protected final void _append(JsonToken type, Object value); protected final void _appendValue(JsonToken type); protected final void _appendValue(JsonToken type, Object value); @Override protected void _reportUnsupportedOperation(); @Deprecated // since 2.9 public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds); public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds, JsonStreamContext parentContext); public void setLocation(JsonLocation l); @Override public ObjectCodec getCodec(); @Override public void setCodec(ObjectCodec c); @Override public Version version(); public JsonToken peekNextToken() throws IOException; @Override public void close() throws IOException; @Override public JsonToken nextToken() throws IOException; @Override public String nextFieldName() throws IOException; @Override public boolean isClosed(); @Override public JsonStreamContext getParsingContext(); @Override public JsonLocation getTokenLocation(); @Override public JsonLocation getCurrentLocation(); @Override public String getCurrentName(); @Override public void overrideCurrentName(String name); @Override public String getText(); @Override public char[] getTextCharacters(); @Override public int getTextLength(); @Override public int getTextOffset(); @Override public boolean hasTextCharacters(); @Override public boolean isNaN(); @Override public BigInteger getBigIntegerValue() throws IOException; @Override public BigDecimal getDecimalValue() throws IOException; @Override public double getDoubleValue() throws IOException; @Override public float getFloatValue() throws IOException; @Override public int getIntValue() throws IOException; @Override public long getLongValue() throws IOException; @Override public NumberType getNumberType() throws IOException; @Override public final Number getNumberValue() throws IOException; private final boolean _smallerThanInt(Number n); private final boolean _smallerThanLong(Number n); protected int _convertNumberToInt(Number n) throws IOException; protected long _convertNumberToLong(Number n) throws IOException; @Override public Object getEmbeddedObject(); @Override @SuppressWarnings("resource") public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; @Override public boolean canReadObjectId(); @Override public boolean canReadTypeId(); @Override public Object getTypeId(); @Override public Object getObjectId(); protected final Object _currentObject(); protected final void _checkIsNumber() throws JsonParseException; @Override protected void _handleEOF() throws JsonParseException; public Segment(); public JsonToken type(int index); public int rawType(int index); public Object get(int index); public Segment next(); public boolean hasIds(); public Segment append(int index, JsonToken tokenType); public Segment append(int index, JsonToken tokenType, Object objectId, Object typeId); public Segment append(int index, JsonToken tokenType, Object value); public Segment append(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private void set(int index, JsonToken tokenType); private void set(int index, JsonToken tokenType, Object objectId, Object typeId); private void set(int index, JsonToken tokenType, Object value); private void set(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private final void assignNativeIds(int index, Object objectId, Object typeId); private Object findObjectId(int index); private Object findTypeId(int index); private final int _typeIdIndex(int i); private final int _objectIdIndex(int i);
595
testWithJsonParserSequenceSimple
```java protected final void _appendValue(JsonToken type, Object value); @Override protected void _reportUnsupportedOperation(); @Deprecated // since 2.9 public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds); public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds, JsonStreamContext parentContext); public void setLocation(JsonLocation l); @Override public ObjectCodec getCodec(); @Override public void setCodec(ObjectCodec c); @Override public Version version(); public JsonToken peekNextToken() throws IOException; @Override public void close() throws IOException; @Override public JsonToken nextToken() throws IOException; @Override public String nextFieldName() throws IOException; @Override public boolean isClosed(); @Override public JsonStreamContext getParsingContext(); @Override public JsonLocation getTokenLocation(); @Override public JsonLocation getCurrentLocation(); @Override public String getCurrentName(); @Override public void overrideCurrentName(String name); @Override public String getText(); @Override public char[] getTextCharacters(); @Override public int getTextLength(); @Override public int getTextOffset(); @Override public boolean hasTextCharacters(); @Override public boolean isNaN(); @Override public BigInteger getBigIntegerValue() throws IOException; @Override public BigDecimal getDecimalValue() throws IOException; @Override public double getDoubleValue() throws IOException; @Override public float getFloatValue() throws IOException; @Override public int getIntValue() throws IOException; @Override public long getLongValue() throws IOException; @Override public NumberType getNumberType() throws IOException; @Override public final Number getNumberValue() throws IOException; private final boolean _smallerThanInt(Number n); private final boolean _smallerThanLong(Number n); protected int _convertNumberToInt(Number n) throws IOException; protected long _convertNumberToLong(Number n) throws IOException; @Override public Object getEmbeddedObject(); @Override @SuppressWarnings("resource") public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; @Override public boolean canReadObjectId(); @Override public boolean canReadTypeId(); @Override public Object getTypeId(); @Override public Object getObjectId(); protected final Object _currentObject(); protected final void _checkIsNumber() throws JsonParseException; @Override protected void _handleEOF() throws JsonParseException; public Segment(); public JsonToken type(int index); public int rawType(int index); public Object get(int index); public Segment next(); public boolean hasIds(); public Segment append(int index, JsonToken tokenType); public Segment append(int index, JsonToken tokenType, Object objectId, Object typeId); public Segment append(int index, JsonToken tokenType, Object value); public Segment append(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private void set(int index, JsonToken tokenType); private void set(int index, JsonToken tokenType, Object objectId, Object typeId); private void set(int index, JsonToken tokenType, Object value); private void set(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private final void assignNativeIds(int index, Object objectId, Object typeId); private Object findObjectId(int index); private Object findTypeId(int index); private final int _typeIdIndex(int i); private final int _objectIdIndex(int i); } // Abstract Java Test Class package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*; public class TestTokenBuffer extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); public void testBasicConfig() throws IOException; public void testSimpleWrites() throws IOException; public void testSimpleNumberWrites() throws IOException; public void testNumberOverflowInt() throws IOException; public void testNumberOverflowLong() throws IOException; public void testParentContext() throws IOException; public void testSimpleArray() throws IOException; public void testSimpleObject() throws IOException; public void testWithJSONSampleDoc() throws Exception; public void testAppend() throws IOException; public void testWithUUID() throws IOException; public void testOutputContext() throws IOException; private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); public void testParentSiblingContext() throws IOException; public void testBasicSerialize() throws IOException; public void testWithJsonParserSequenceSimple() throws IOException; @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException; public void testRawValues() throws Exception; public void testEmbeddedObjectCoerceCheck() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testWithJsonParserSequenceSimple` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Tests to verify interaction of TokenBuffer and JsonParserSequence /********************************************************** */
552
// protected final void _appendValue(JsonToken type, Object value); // @Override // protected void _reportUnsupportedOperation(); // @Deprecated // since 2.9 // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds); // public Parser(Segment firstSeg, ObjectCodec codec, // boolean hasNativeTypeIds, boolean hasNativeObjectIds, // JsonStreamContext parentContext); // public void setLocation(JsonLocation l); // @Override // public ObjectCodec getCodec(); // @Override // public void setCodec(ObjectCodec c); // @Override // public Version version(); // public JsonToken peekNextToken() throws IOException; // @Override // public void close() throws IOException; // @Override // public JsonToken nextToken() throws IOException; // @Override // public String nextFieldName() throws IOException; // @Override // public boolean isClosed(); // @Override // public JsonStreamContext getParsingContext(); // @Override // public JsonLocation getTokenLocation(); // @Override // public JsonLocation getCurrentLocation(); // @Override // public String getCurrentName(); // @Override // public void overrideCurrentName(String name); // @Override // public String getText(); // @Override // public char[] getTextCharacters(); // @Override // public int getTextLength(); // @Override // public int getTextOffset(); // @Override // public boolean hasTextCharacters(); // @Override // public boolean isNaN(); // @Override // public BigInteger getBigIntegerValue() throws IOException; // @Override // public BigDecimal getDecimalValue() throws IOException; // @Override // public double getDoubleValue() throws IOException; // @Override // public float getFloatValue() throws IOException; // @Override // public int getIntValue() throws IOException; // @Override // public long getLongValue() throws IOException; // @Override // public NumberType getNumberType() throws IOException; // @Override // public final Number getNumberValue() throws IOException; // private final boolean _smallerThanInt(Number n); // private final boolean _smallerThanLong(Number n); // protected int _convertNumberToInt(Number n) throws IOException; // protected long _convertNumberToLong(Number n) throws IOException; // @Override // public Object getEmbeddedObject(); // @Override // @SuppressWarnings("resource") // public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; // @Override // public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; // @Override // public boolean canReadObjectId(); // @Override // public boolean canReadTypeId(); // @Override // public Object getTypeId(); // @Override // public Object getObjectId(); // protected final Object _currentObject(); // protected final void _checkIsNumber() throws JsonParseException; // @Override // protected void _handleEOF() throws JsonParseException; // public Segment(); // public JsonToken type(int index); // public int rawType(int index); // public Object get(int index); // public Segment next(); // public boolean hasIds(); // public Segment append(int index, JsonToken tokenType); // public Segment append(int index, JsonToken tokenType, // Object objectId, Object typeId); // public Segment append(int index, JsonToken tokenType, Object value); // public Segment append(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType); // private void set(int index, JsonToken tokenType, // Object objectId, Object typeId); // private void set(int index, JsonToken tokenType, Object value); // private void set(int index, JsonToken tokenType, Object value, // Object objectId, Object typeId); // private final void assignNativeIds(int index, Object objectId, Object typeId); // private Object findObjectId(int index); // private Object findTypeId(int index); // private final int _typeIdIndex(int i); // private final int _objectIdIndex(int i); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.util; // // import java.io.*; // import java.math.BigDecimal; // import java.math.BigInteger; // import java.util.UUID; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.JsonParser.NumberType; // import com.fasterxml.jackson.core.io.SerializedString; // import com.fasterxml.jackson.core.util.JsonParserSequence; // import com.fasterxml.jackson.databind.*; // // // // public class TestTokenBuffer extends BaseMapTest // { // private final ObjectMapper MAPPER = objectMapper(); // // public void testBasicConfig() throws IOException; // public void testSimpleWrites() throws IOException; // public void testSimpleNumberWrites() throws IOException; // public void testNumberOverflowInt() throws IOException; // public void testNumberOverflowLong() throws IOException; // public void testParentContext() throws IOException; // public void testSimpleArray() throws IOException; // public void testSimpleObject() throws IOException; // public void testWithJSONSampleDoc() throws Exception; // public void testAppend() throws IOException; // public void testWithUUID() throws IOException; // public void testOutputContext() throws IOException; // private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); // private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); // public void testParentSiblingContext() throws IOException; // public void testBasicSerialize() throws IOException; // public void testWithJsonParserSequenceSimple() throws IOException; // @SuppressWarnings("resource") // public void testWithMultipleJsonParserSequences() throws IOException; // public void testRawValues() throws Exception; // public void testEmbeddedObjectCoerceCheck() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testWithJsonParserSequenceSimple` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Tests to verify interaction of TokenBuffer and JsonParserSequence /********************************************************** */ public void testWithJsonParserSequenceSimple() throws IOException {
/* /********************************************************** /* Tests to verify interaction of TokenBuffer and JsonParserSequence /********************************************************** */
112
com.fasterxml.jackson.databind.util.TokenBuffer
src/test/java
```java protected final void _appendValue(JsonToken type, Object value); @Override protected void _reportUnsupportedOperation(); @Deprecated // since 2.9 public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds); public Parser(Segment firstSeg, ObjectCodec codec, boolean hasNativeTypeIds, boolean hasNativeObjectIds, JsonStreamContext parentContext); public void setLocation(JsonLocation l); @Override public ObjectCodec getCodec(); @Override public void setCodec(ObjectCodec c); @Override public Version version(); public JsonToken peekNextToken() throws IOException; @Override public void close() throws IOException; @Override public JsonToken nextToken() throws IOException; @Override public String nextFieldName() throws IOException; @Override public boolean isClosed(); @Override public JsonStreamContext getParsingContext(); @Override public JsonLocation getTokenLocation(); @Override public JsonLocation getCurrentLocation(); @Override public String getCurrentName(); @Override public void overrideCurrentName(String name); @Override public String getText(); @Override public char[] getTextCharacters(); @Override public int getTextLength(); @Override public int getTextOffset(); @Override public boolean hasTextCharacters(); @Override public boolean isNaN(); @Override public BigInteger getBigIntegerValue() throws IOException; @Override public BigDecimal getDecimalValue() throws IOException; @Override public double getDoubleValue() throws IOException; @Override public float getFloatValue() throws IOException; @Override public int getIntValue() throws IOException; @Override public long getLongValue() throws IOException; @Override public NumberType getNumberType() throws IOException; @Override public final Number getNumberValue() throws IOException; private final boolean _smallerThanInt(Number n); private final boolean _smallerThanLong(Number n); protected int _convertNumberToInt(Number n) throws IOException; protected long _convertNumberToLong(Number n) throws IOException; @Override public Object getEmbeddedObject(); @Override @SuppressWarnings("resource") public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException; @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException; @Override public boolean canReadObjectId(); @Override public boolean canReadTypeId(); @Override public Object getTypeId(); @Override public Object getObjectId(); protected final Object _currentObject(); protected final void _checkIsNumber() throws JsonParseException; @Override protected void _handleEOF() throws JsonParseException; public Segment(); public JsonToken type(int index); public int rawType(int index); public Object get(int index); public Segment next(); public boolean hasIds(); public Segment append(int index, JsonToken tokenType); public Segment append(int index, JsonToken tokenType, Object objectId, Object typeId); public Segment append(int index, JsonToken tokenType, Object value); public Segment append(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private void set(int index, JsonToken tokenType); private void set(int index, JsonToken tokenType, Object objectId, Object typeId); private void set(int index, JsonToken tokenType, Object value); private void set(int index, JsonToken tokenType, Object value, Object objectId, Object typeId); private final void assignNativeIds(int index, Object objectId, Object typeId); private Object findObjectId(int index); private Object findTypeId(int index); private final int _typeIdIndex(int i); private final int _objectIdIndex(int i); } // Abstract Java Test Class package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*; public class TestTokenBuffer extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); public void testBasicConfig() throws IOException; public void testSimpleWrites() throws IOException; public void testSimpleNumberWrites() throws IOException; public void testNumberOverflowInt() throws IOException; public void testNumberOverflowLong() throws IOException; public void testParentContext() throws IOException; public void testSimpleArray() throws IOException; public void testSimpleObject() throws IOException; public void testWithJSONSampleDoc() throws Exception; public void testAppend() throws IOException; public void testWithUUID() throws IOException; public void testOutputContext() throws IOException; private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); public void testParentSiblingContext() throws IOException; public void testBasicSerialize() throws IOException; public void testWithJsonParserSequenceSimple() throws IOException; @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException; public void testRawValues() throws Exception; public void testEmbeddedObjectCoerceCheck() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testWithJsonParserSequenceSimple` for the `TokenBuffer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Tests to verify interaction of TokenBuffer and JsonParserSequence /********************************************************** */ public void testWithJsonParserSequenceSimple() throws IOException { ```
public class TokenBuffer /* Won't use JsonGeneratorBase, to minimize overhead for validity * checking */ extends JsonGenerator
package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*;
public void testBasicConfig() throws IOException; public void testSimpleWrites() throws IOException; public void testSimpleNumberWrites() throws IOException; public void testNumberOverflowInt() throws IOException; public void testNumberOverflowLong() throws IOException; public void testParentContext() throws IOException; public void testSimpleArray() throws IOException; public void testSimpleObject() throws IOException; public void testWithJSONSampleDoc() throws Exception; public void testAppend() throws IOException; public void testWithUUID() throws IOException; public void testOutputContext() throws IOException; private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2); private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2); public void testParentSiblingContext() throws IOException; public void testBasicSerialize() throws IOException; public void testWithJsonParserSequenceSimple() throws IOException; @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException; public void testRawValues() throws Exception; public void testEmbeddedObjectCoerceCheck() throws Exception;
e0861eb6736707ff900d7db738c970886788c5c922f9e72efd2d6d09ee506e82
[ "com.fasterxml.jackson.databind.util.TestTokenBuffer::testWithJsonParserSequenceSimple" ]
protected final static int DEFAULT_GENERATOR_FEATURES = JsonGenerator.Feature.collectDefaults(); protected ObjectCodec _objectCodec; protected JsonStreamContext _parentContext; protected int _generatorFeatures; protected boolean _closed; protected boolean _hasNativeTypeIds; protected boolean _hasNativeObjectIds; protected boolean _mayHaveNativeIds; protected boolean _forceBigDecimal; protected Segment _first; protected Segment _last; protected int _appendAt; protected Object _typeId; protected Object _objectId; protected boolean _hasNativeId = false; protected JsonWriteContext _writeContext;
public void testWithJsonParserSequenceSimple() throws IOException
private final ObjectMapper MAPPER = objectMapper();
JacksonDatabind
package com.fasterxml.jackson.databind.util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.util.JsonParserSequence; import com.fasterxml.jackson.databind.*; public class TestTokenBuffer extends BaseMapTest { private final ObjectMapper MAPPER = objectMapper(); static class Base1730 { } static class Sub1730 extends Base1730 { } /* /********************************************************** /* Basic TokenBuffer tests /********************************************************** */ public void testBasicConfig() throws IOException { TokenBuffer buf; buf = new TokenBuffer(MAPPER, false); assertEquals(MAPPER.version(), buf.version()); assertSame(MAPPER, buf.getCodec()); assertNotNull(buf.getOutputContext()); assertFalse(buf.isClosed()); buf.setCodec(null); assertNull(buf.getCodec()); assertFalse(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII); assertTrue(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII); assertFalse(buf.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); buf.close(); assertTrue(buf.isClosed()); } /** * Test writing of individual simple values */ public void testSimpleWrites() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec // First, with empty buffer JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); assertNull(p.nextToken()); p.close(); // Then with simple text buf.writeString("abc"); p = buf.asParser(); assertNull(p.getCurrentToken()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("abc", p.getText()); assertNull(p.nextToken()); p.close(); // Then, let's append at root level buf.writeNumber(13); p = buf.asParser(); assertNull(p.getCurrentToken()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(13, p.getIntValue()); assertNull(p.nextToken()); p.close(); buf.close(); } // For 2.9, explicit "isNaN" check public void testSimpleNumberWrites() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); double[] values1 = new double[] { 0.25, Double.NaN, -2.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY }; float[] values2 = new float[] { Float.NEGATIVE_INFINITY, 0.25f, Float.POSITIVE_INFINITY }; for (double v : values1) { buf.writeNumber(v); } for (float v : values2) { buf.writeNumber(v); } JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); for (double v : values1) { assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); double actual = p.getDoubleValue(); boolean expNan = Double.isNaN(v) || Double.isInfinite(v); assertEquals(expNan, p.isNaN()); assertEquals(0, Double.compare(v, actual)); } for (float v : values2) { assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); float actual = p.getFloatValue(); boolean expNan = Float.isNaN(v) || Float.isInfinite(v); assertEquals(expNan, p.isNaN()); assertEquals(0, Float.compare(v, actual)); } p.close(); buf.close(); } // [databind#1729] public void testNumberOverflowInt() throws IOException { try (TokenBuffer buf = new TokenBuffer(null, false)) { long big = 1L + Integer.MAX_VALUE; buf.writeNumber(big); try (JsonParser p = buf.asParser()) { assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(NumberType.LONG, p.getNumberType()); try { p.getIntValue(); fail("Expected failure for `int` overflow"); } catch (JsonParseException e) { verifyException(e, "Numeric value ("+big+") out of range of int"); } } } // and ditto for coercion. try (TokenBuffer buf = new TokenBuffer(null, false)) { long big = 1L + Integer.MAX_VALUE; buf.writeNumber(String.valueOf(big)); try (JsonParser p = buf.asParser()) { // NOTE: oddity of buffering, no inspection of "real" type if given String... assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); try { p.getIntValue(); fail("Expected failure for `int` overflow"); } catch (JsonParseException e) { verifyException(e, "Numeric value ("+big+") out of range of int"); } } } } public void testNumberOverflowLong() throws IOException { try (TokenBuffer buf = new TokenBuffer(null, false)) { BigInteger big = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); buf.writeNumber(big); try (JsonParser p = buf.asParser()) { assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(NumberType.BIG_INTEGER, p.getNumberType()); try { p.getLongValue(); fail("Expected failure for `long` overflow"); } catch (JsonParseException e) { verifyException(e, "Numeric value ("+big+") out of range of long"); } } } } public void testParentContext() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec buf.writeStartObject(); buf.writeFieldName("b"); buf.writeStartObject(); buf.writeFieldName("c"); //This assertion succeeds as expected assertEquals("b", buf.getOutputContext().getParent().getCurrentName()); buf.writeString("cval"); buf.writeEndObject(); buf.writeEndObject(); buf.close(); } public void testSimpleArray() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec // First, empty array assertTrue(buf.getOutputContext().inRoot()); buf.writeStartArray(); assertTrue(buf.getOutputContext().inArray()); buf.writeEndArray(); assertTrue(buf.getOutputContext().inRoot()); JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); assertTrue(p.getParsingContext().inRoot()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertTrue(p.getParsingContext().inArray()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertTrue(p.getParsingContext().inRoot()); assertNull(p.nextToken()); p.close(); buf.close(); // Then one with simple contents buf = new TokenBuffer(null, false); buf.writeStartArray(); buf.writeBoolean(true); buf.writeNull(); buf.writeEndArray(); p = buf.asParser(); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertTrue(p.getBooleanValue()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertNull(p.nextToken()); p.close(); buf.close(); // And finally, with array-in-array buf = new TokenBuffer(null, false); buf.writeStartArray(); buf.writeStartArray(); buf.writeBinary(new byte[3]); buf.writeEndArray(); buf.writeEndArray(); p = buf.asParser(); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.START_ARRAY, p.nextToken()); // TokenBuffer exposes it as embedded object... assertToken(JsonToken.VALUE_EMBEDDED_OBJECT, p.nextToken()); Object ob = p.getEmbeddedObject(); assertNotNull(ob); assertTrue(ob instanceof byte[]); assertEquals(3, ((byte[]) ob).length); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertNull(p.nextToken()); p.close(); buf.close(); } public void testSimpleObject() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // First, empty JSON Object assertTrue(buf.getOutputContext().inRoot()); buf.writeStartObject(); assertTrue(buf.getOutputContext().inObject()); buf.writeEndObject(); assertTrue(buf.getOutputContext().inRoot()); JsonParser p = buf.asParser(); assertNull(p.getCurrentToken()); assertTrue(p.getParsingContext().inRoot()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertTrue(p.getParsingContext().inObject()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertTrue(p.getParsingContext().inRoot()); assertNull(p.nextToken()); p.close(); buf.close(); // Then one with simple contents buf = new TokenBuffer(null, false); buf.writeStartObject(); buf.writeNumberField("num", 1.25); buf.writeEndObject(); p = buf.asParser(); assertNull(p.getCurrentToken()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertNull(p.getCurrentName()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); // and override should also work: p.overrideCurrentName("bah"); assertEquals("bah", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); assertEquals(1.25, p.getDoubleValue()); // should still have access to (overridden) name assertEquals("bah", p.getCurrentName()); assertToken(JsonToken.END_OBJECT, p.nextToken()); // but not any more assertNull(p.getCurrentName()); assertNull(p.nextToken()); p.close(); buf.close(); } /** * Verify handling of that "standard" test document (from JSON * specification) */ public void testWithJSONSampleDoc() throws Exception { // First, copy events from known good source (StringReader) JsonParser p = createParserUsingReader(SAMPLE_DOC_JSON_SPEC); TokenBuffer tb = new TokenBuffer(null, false); while (p.nextToken() != null) { tb.copyCurrentEvent(p); } // And then request verification; first structure only: verifyJsonSpecSampleDoc(tb.asParser(), false); // then content check too: verifyJsonSpecSampleDoc(tb.asParser(), true); tb.close(); p.close(); // 19-Oct-2016, tatu: Just for fun, trigger `toString()` for code coverage String desc = tb.toString(); assertNotNull(desc); } public void testAppend() throws IOException { TokenBuffer buf1 = new TokenBuffer(null, false); buf1.writeStartObject(); buf1.writeFieldName("a"); buf1.writeBoolean(true); TokenBuffer buf2 = new TokenBuffer(null, false); buf2.writeFieldName("b"); buf2.writeNumber(13); buf2.writeEndObject(); buf1.append(buf2); // and verify that we got it all... JsonParser p = buf1.asParser(); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("a", p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("b", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(13, p.getIntValue()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); buf1.close(); buf2.close(); } // Since 2.3 had big changes to UUID handling, let's verify we can // deal with public void testWithUUID() throws IOException { for (String value : new String[] { "00000007-0000-0000-0000-000000000000", "76e6d183-5f68-4afa-b94a-922c1fdb83f8", "540a88d1-e2d8-4fb1-9396-9212280d0a7f", "2c9e441d-1cd0-472d-9bab-69838f877574", "591b2869-146e-41d7-8048-e8131f1fdec5", "82994ac2-7b23-49f2-8cc5-e24cf6ed77be", }) { TokenBuffer buf = new TokenBuffer(MAPPER, false); // no ObjectCodec UUID uuid = UUID.fromString(value); MAPPER.writeValue(buf, uuid); buf.close(); // and bring it back UUID out = MAPPER.readValue(buf.asParser(), UUID.class); assertEquals(uuid.toString(), out.toString()); // second part: As per [databind#362], should NOT use binary with TokenBuffer JsonParser p = buf.asParser(); assertEquals(JsonToken.VALUE_STRING, p.nextToken()); String str = p.getText(); assertEquals(value, str); p.close(); } } /* /********************************************************** /* Tests for read/output contexts /********************************************************** */ // for [databind#984]: ensure output context handling identical public void testOutputContext() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec StringWriter w = new StringWriter(); JsonGenerator gen = MAPPER.getFactory().createGenerator(w); // test content: [{"a":1,"b":{"c":2}},{"a":2,"b":{"c":3}}] buf.writeStartArray(); gen.writeStartArray(); _verifyOutputContext(buf, gen); buf.writeStartObject(); gen.writeStartObject(); _verifyOutputContext(buf, gen); buf.writeFieldName("a"); gen.writeFieldName("a"); _verifyOutputContext(buf, gen); buf.writeNumber(1); gen.writeNumber(1); _verifyOutputContext(buf, gen); buf.writeFieldName("b"); gen.writeFieldName("b"); _verifyOutputContext(buf, gen); buf.writeStartObject(); gen.writeStartObject(); _verifyOutputContext(buf, gen); buf.writeFieldName("c"); gen.writeFieldName("c"); _verifyOutputContext(buf, gen); buf.writeNumber(2); gen.writeNumber(2); _verifyOutputContext(buf, gen); buf.writeEndObject(); gen.writeEndObject(); _verifyOutputContext(buf, gen); buf.writeEndObject(); gen.writeEndObject(); _verifyOutputContext(buf, gen); buf.writeEndArray(); gen.writeEndArray(); _verifyOutputContext(buf, gen); buf.close(); gen.close(); } private void _verifyOutputContext(JsonGenerator gen1, JsonGenerator gen2) { _verifyOutputContext(gen1.getOutputContext(), gen2.getOutputContext()); } private void _verifyOutputContext(JsonStreamContext ctxt1, JsonStreamContext ctxt2) { if (ctxt1 == null) { if (ctxt2 == null) { return; } fail("Context 1 null, context 2 not null: "+ctxt2); } else if (ctxt2 == null) { fail("Context 2 null, context 1 not null: "+ctxt1); } if (!ctxt1.toString().equals(ctxt2.toString())) { fail("Different output context: token-buffer's = "+ctxt1+", json-generator's: "+ctxt2); } if (ctxt1.inObject()) { assertTrue(ctxt2.inObject()); String str1 = ctxt1.getCurrentName(); String str2 = ctxt2.getCurrentName(); if ((str1 != str2) && !str1.equals(str2)) { fail("Expected name '"+str2+"' (JsonParser), TokenBuffer had '"+str1+"'"); } } else if (ctxt1.inArray()) { assertTrue(ctxt2.inArray()); assertEquals(ctxt1.getCurrentIndex(), ctxt2.getCurrentIndex()); } _verifyOutputContext(ctxt1.getParent(), ctxt2.getParent()); } // [databind#1253] public void testParentSiblingContext() throws IOException { TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec // {"a":{},"b":{"c":"cval"}} buf.writeStartObject(); buf.writeFieldName("a"); buf.writeStartObject(); buf.writeEndObject(); buf.writeFieldName("b"); buf.writeStartObject(); buf.writeFieldName("c"); //This assertion fails (because of 'a') assertEquals("b", buf.getOutputContext().getParent().getCurrentName()); buf.writeString("cval"); buf.writeEndObject(); buf.writeEndObject(); buf.close(); } public void testBasicSerialize() throws IOException { TokenBuffer buf; // let's see how empty works... buf = new TokenBuffer(MAPPER, false); assertEquals("", MAPPER.writeValueAsString(buf)); buf.close(); buf = new TokenBuffer(MAPPER, false); buf.writeStartArray(); buf.writeBoolean(true); buf.writeBoolean(false); long l = 1L + Integer.MAX_VALUE; buf.writeNumber(l); buf.writeNumber((short) 4); buf.writeNumber(0.5); buf.writeEndArray(); assertEquals(aposToQuotes("[true,false,"+l+",4,0.5]"), MAPPER.writeValueAsString(buf)); buf.close(); buf = new TokenBuffer(MAPPER, false); buf.writeStartObject(); buf.writeFieldName(new SerializedString("foo")); buf.writeNull(); buf.writeFieldName("bar"); buf.writeNumber(BigInteger.valueOf(123)); buf.writeFieldName("dec"); buf.writeNumber(BigDecimal.valueOf(5).movePointLeft(2)); assertEquals(aposToQuotes("{'foo':null,'bar':123,'dec':0.05}"), MAPPER.writeValueAsString(buf)); buf.close(); } /* /********************************************************** /* Tests to verify interaction of TokenBuffer and JsonParserSequence /********************************************************** */ public void testWithJsonParserSequenceSimple() throws IOException { // Let's join a TokenBuffer with JsonParser first TokenBuffer buf = new TokenBuffer(null, false); buf.writeStartArray(); buf.writeString("test"); JsonParser p = createParserUsingReader("[ true, null ]"); JsonParserSequence seq = JsonParserSequence.createFlattened(false, buf.asParser(), p); assertEquals(2, seq.containedParsersCount()); assertFalse(p.isClosed()); assertFalse(seq.hasCurrentToken()); assertNull(seq.getCurrentToken()); assertNull(seq.getCurrentName()); assertToken(JsonToken.START_ARRAY, seq.nextToken()); assertToken(JsonToken.VALUE_STRING, seq.nextToken()); assertEquals("test", seq.getText()); // end of first parser input, should switch over: assertToken(JsonToken.START_ARRAY, seq.nextToken()); assertToken(JsonToken.VALUE_TRUE, seq.nextToken()); assertToken(JsonToken.VALUE_NULL, seq.nextToken()); assertToken(JsonToken.END_ARRAY, seq.nextToken()); /* 17-Jan-2009, tatus: At this point, we may or may not get an * exception, depending on how underlying parsers work. * Ideally this should be fixed, probably by asking underlying * parsers to disable checking for balanced start/end markers. */ // for this particular case, we won't get an exception tho... assertNull(seq.nextToken()); // not an error to call again... assertNull(seq.nextToken()); // also: original parsers should be closed assertTrue(p.isClosed()); p.close(); buf.close(); seq.close(); } /** * Test to verify that TokenBuffer and JsonParserSequence work together * as expected. */ @SuppressWarnings("resource") public void testWithMultipleJsonParserSequences() throws IOException { TokenBuffer buf1 = new TokenBuffer(null, false); buf1.writeStartArray(); TokenBuffer buf2 = new TokenBuffer(null, false); buf2.writeString("a"); TokenBuffer buf3 = new TokenBuffer(null, false); buf3.writeNumber(13); TokenBuffer buf4 = new TokenBuffer(null, false); buf4.writeEndArray(); JsonParserSequence seq1 = JsonParserSequence.createFlattened(false, buf1.asParser(), buf2.asParser()); assertEquals(2, seq1.containedParsersCount()); JsonParserSequence seq2 = JsonParserSequence.createFlattened(false, buf3.asParser(), buf4.asParser()); assertEquals(2, seq2.containedParsersCount()); JsonParserSequence combo = JsonParserSequence.createFlattened(false, seq1, seq2); // should flatten it to have 4 underlying parsers assertEquals(4, combo.containedParsersCount()); assertToken(JsonToken.START_ARRAY, combo.nextToken()); assertToken(JsonToken.VALUE_STRING, combo.nextToken()); assertEquals("a", combo.getText()); assertToken(JsonToken.VALUE_NUMBER_INT, combo.nextToken()); assertEquals(13, combo.getIntValue()); assertToken(JsonToken.END_ARRAY, combo.nextToken()); assertNull(combo.nextToken()); buf1.close(); buf2.close(); buf3.close(); buf4.close(); } // [databind#743] public void testRawValues() throws Exception { final String RAW = "{\"a\":1}"; TokenBuffer buf = new TokenBuffer(null, false); buf.writeRawValue(RAW); // first: raw value won't be transformed in any way: JsonParser p = buf.asParser(); assertToken(JsonToken.VALUE_EMBEDDED_OBJECT, p.nextToken()); assertEquals(RawValue.class, p.getEmbeddedObject().getClass()); assertNull(p.nextToken()); p.close(); buf.close(); // then verify it would be serialized just fine assertEquals(RAW, MAPPER.writeValueAsString(buf)); } // [databind#1730] public void testEmbeddedObjectCoerceCheck() throws Exception { TokenBuffer buf = new TokenBuffer(null, false); Object inputPojo = new Sub1730(); buf.writeEmbeddedObject(inputPojo); // first: raw value won't be transformed in any way: JsonParser p = buf.asParser(); Base1730 out = MAPPER.readValue(p, Base1730.class); assertSame(inputPojo, out); p.close(); buf.close(); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "_append", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonToken;)V", "line_numbers": [ "1135", "1138", "1139", "1141", "1142", "1144" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "_appendValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonToken;Ljava/lang/Object;)V", "line_numbers": [ "1187", "1188", "1191", "1192", "1194", "1195", "1197" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "asParser", "be_test_function_signature": "()Lcom/fasterxml/jackson/core/JsonParser;", "line_numbers": [ "242" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "asParser", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/ObjectCodec;)Lcom/fasterxml/jackson/core/JsonParser;", "line_numbers": [ "276" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "close", "be_test_function_signature": "()V", "line_numbers": [ "654", "655" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "writeStartArray", "be_test_function_signature": "()V", "line_numbers": [ "669", "670", "671", "672" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/util/TokenBuffer.java", "be_test_class_name": "com.fasterxml.jackson.databind.util.TokenBuffer", "be_test_function_name": "writeString", "be_test_function_signature": "(Ljava/lang/String;)V", "line_numbers": [ "738", "739", "741", "743" ], "method_line_rate": 0.75 } ]
public class MultiBackgroundInitializerTest
@Test public void testAddInitializerAfterStart() throws ConcurrentException { initializer.start(); try { initializer.addInitializer(CHILD_INIT, new ChildBackgroundInitializer()); fail("Could add initializer after start()!"); } catch (final IllegalStateException istex) { initializer.get(); } }
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.Collections; // import java.util.HashMap; // import java.util.Map; // import java.util.NoSuchElementException; // import java.util.Set; // import java.util.concurrent.ExecutorService; // // // // public class MultiBackgroundInitializer // extends // BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { // private final Map<String, BackgroundInitializer<?>> childInitializers = // new HashMap<String, BackgroundInitializer<?>>(); // // public MultiBackgroundInitializer(); // public MultiBackgroundInitializer(final ExecutorService exec); // public void addInitializer(final String name, final BackgroundInitializer<?> init); // @Override // protected int getTaskCount(); // @Override // protected MultiBackgroundInitializerResults initialize() throws Exception; // private MultiBackgroundInitializerResults( // final Map<String, BackgroundInitializer<?>> inits, // final Map<String, Object> results, // final Map<String, ConcurrentException> excepts); // public BackgroundInitializer<?> getInitializer(final String name); // public Object getResultObject(final String name); // public boolean isException(final String name); // public ConcurrentException getException(final String name); // public Set<String> initializerNames(); // public boolean isSuccessful(); // private BackgroundInitializer<?> checkName(final String name); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.concurrent; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNull; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.util.Iterator; // import java.util.NoSuchElementException; // import java.util.concurrent.ExecutorService; // import java.util.concurrent.Executors; // import org.junit.Before; // import org.junit.Test; // // // // public class MultiBackgroundInitializerTest { // private static final String CHILD_INIT = "childInitializer"; // private MultiBackgroundInitializer initializer; // // @Before // public void setUp() throws Exception; // private void checkChild(final BackgroundInitializer<?> child, // final ExecutorService expExec) throws ConcurrentException; // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullName(); // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullInit(); // @Test // public void testInitializeNoChildren() throws ConcurrentException; // private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() // throws ConcurrentException; // @Test // public void testInitializeTempExec() throws ConcurrentException; // @Test // public void testInitializeExternalExec() throws ConcurrentException; // @Test // public void testInitializeChildWithExecutor() throws ConcurrentException; // @Test // public void testAddInitializerAfterStart() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetInitializerUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetResultObjectUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetExceptionUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultIsExceptionUnknown() throws ConcurrentException; // @Test(expected = UnsupportedOperationException.class) // public void testResultInitializerNamesModify() throws ConcurrentException; // @Test // public void testInitializeRuntimeEx(); // @Test // public void testInitializeEx() throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulTrue() // throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulFalse() // throws ConcurrentException; // @Test // public void testInitializeNested() throws ConcurrentException; // @Override // protected Integer initialize() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testAddInitializerAfterStart` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tries to add another child initializer after the start() method has been * called. This should not be allowed. */
src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
package org.apache.commons.lang3.concurrent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutorService;
public MultiBackgroundInitializer(); public MultiBackgroundInitializer(final ExecutorService exec); public void addInitializer(final String name, final BackgroundInitializer<?> init); @Override protected int getTaskCount(); @Override protected MultiBackgroundInitializerResults initialize() throws Exception; private MultiBackgroundInitializerResults( final Map<String, BackgroundInitializer<?>> inits, final Map<String, Object> results, final Map<String, ConcurrentException> excepts); public BackgroundInitializer<?> getInitializer(final String name); public Object getResultObject(final String name); public boolean isException(final String name); public ConcurrentException getException(final String name); public Set<String> initializerNames(); public boolean isSuccessful(); private BackgroundInitializer<?> checkName(final String name);
196
testAddInitializerAfterStart
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutorService; public class MultiBackgroundInitializer extends BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>(); public MultiBackgroundInitializer(); public MultiBackgroundInitializer(final ExecutorService exec); public void addInitializer(final String name, final BackgroundInitializer<?> init); @Override protected int getTaskCount(); @Override protected MultiBackgroundInitializerResults initialize() throws Exception; private MultiBackgroundInitializerResults( final Map<String, BackgroundInitializer<?>> inits, final Map<String, Object> results, final Map<String, ConcurrentException> excepts); public BackgroundInitializer<?> getInitializer(final String name); public Object getResultObject(final String name); public boolean isException(final String name); public ConcurrentException getException(final String name); public Set<String> initializerNames(); public boolean isSuccessful(); private BackgroundInitializer<?> checkName(final String name); } // Abstract Java Test Class package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; public class MultiBackgroundInitializerTest { private static final String CHILD_INIT = "childInitializer"; private MultiBackgroundInitializer initializer; @Before public void setUp() throws Exception; private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException; @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName(); @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit(); @Test public void testInitializeNoChildren() throws ConcurrentException; private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException; @Test public void testInitializeTempExec() throws ConcurrentException; @Test public void testInitializeExternalExec() throws ConcurrentException; @Test public void testInitializeChildWithExecutor() throws ConcurrentException; @Test public void testAddInitializerAfterStart() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException; @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException; @Test public void testInitializeRuntimeEx(); @Test public void testInitializeEx() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException; @Test public void testInitializeNested() throws ConcurrentException; @Override protected Integer initialize() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testAddInitializerAfterStart` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tries to add another child initializer after the start() method has been * called. This should not be allowed. */
186
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.Collections; // import java.util.HashMap; // import java.util.Map; // import java.util.NoSuchElementException; // import java.util.Set; // import java.util.concurrent.ExecutorService; // // // // public class MultiBackgroundInitializer // extends // BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { // private final Map<String, BackgroundInitializer<?>> childInitializers = // new HashMap<String, BackgroundInitializer<?>>(); // // public MultiBackgroundInitializer(); // public MultiBackgroundInitializer(final ExecutorService exec); // public void addInitializer(final String name, final BackgroundInitializer<?> init); // @Override // protected int getTaskCount(); // @Override // protected MultiBackgroundInitializerResults initialize() throws Exception; // private MultiBackgroundInitializerResults( // final Map<String, BackgroundInitializer<?>> inits, // final Map<String, Object> results, // final Map<String, ConcurrentException> excepts); // public BackgroundInitializer<?> getInitializer(final String name); // public Object getResultObject(final String name); // public boolean isException(final String name); // public ConcurrentException getException(final String name); // public Set<String> initializerNames(); // public boolean isSuccessful(); // private BackgroundInitializer<?> checkName(final String name); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.concurrent; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNull; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.util.Iterator; // import java.util.NoSuchElementException; // import java.util.concurrent.ExecutorService; // import java.util.concurrent.Executors; // import org.junit.Before; // import org.junit.Test; // // // // public class MultiBackgroundInitializerTest { // private static final String CHILD_INIT = "childInitializer"; // private MultiBackgroundInitializer initializer; // // @Before // public void setUp() throws Exception; // private void checkChild(final BackgroundInitializer<?> child, // final ExecutorService expExec) throws ConcurrentException; // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullName(); // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullInit(); // @Test // public void testInitializeNoChildren() throws ConcurrentException; // private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() // throws ConcurrentException; // @Test // public void testInitializeTempExec() throws ConcurrentException; // @Test // public void testInitializeExternalExec() throws ConcurrentException; // @Test // public void testInitializeChildWithExecutor() throws ConcurrentException; // @Test // public void testAddInitializerAfterStart() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetInitializerUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetResultObjectUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetExceptionUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultIsExceptionUnknown() throws ConcurrentException; // @Test(expected = UnsupportedOperationException.class) // public void testResultInitializerNamesModify() throws ConcurrentException; // @Test // public void testInitializeRuntimeEx(); // @Test // public void testInitializeEx() throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulTrue() // throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulFalse() // throws ConcurrentException; // @Test // public void testInitializeNested() throws ConcurrentException; // @Override // protected Integer initialize() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testAddInitializerAfterStart` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tries to add another child initializer after the start() method has been * called. This should not be allowed. */ @Test public void testAddInitializerAfterStart() throws ConcurrentException {
/** * Tries to add another child initializer after the start() method has been * called. This should not be allowed. */
1
org.apache.commons.lang3.concurrent.MultiBackgroundInitializer
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutorService; public class MultiBackgroundInitializer extends BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>(); public MultiBackgroundInitializer(); public MultiBackgroundInitializer(final ExecutorService exec); public void addInitializer(final String name, final BackgroundInitializer<?> init); @Override protected int getTaskCount(); @Override protected MultiBackgroundInitializerResults initialize() throws Exception; private MultiBackgroundInitializerResults( final Map<String, BackgroundInitializer<?>> inits, final Map<String, Object> results, final Map<String, ConcurrentException> excepts); public BackgroundInitializer<?> getInitializer(final String name); public Object getResultObject(final String name); public boolean isException(final String name); public ConcurrentException getException(final String name); public Set<String> initializerNames(); public boolean isSuccessful(); private BackgroundInitializer<?> checkName(final String name); } // Abstract Java Test Class package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; public class MultiBackgroundInitializerTest { private static final String CHILD_INIT = "childInitializer"; private MultiBackgroundInitializer initializer; @Before public void setUp() throws Exception; private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException; @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName(); @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit(); @Test public void testInitializeNoChildren() throws ConcurrentException; private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException; @Test public void testInitializeTempExec() throws ConcurrentException; @Test public void testInitializeExternalExec() throws ConcurrentException; @Test public void testInitializeChildWithExecutor() throws ConcurrentException; @Test public void testAddInitializerAfterStart() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException; @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException; @Test public void testInitializeRuntimeEx(); @Test public void testInitializeEx() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException; @Test public void testInitializeNested() throws ConcurrentException; @Override protected Integer initialize() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testAddInitializerAfterStart` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tries to add another child initializer after the start() method has been * called. This should not be allowed. */ @Test public void testAddInitializerAfterStart() throws ConcurrentException { ```
public class MultiBackgroundInitializer extends BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults>
package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test;
@Before public void setUp() throws Exception; private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException; @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName(); @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit(); @Test public void testInitializeNoChildren() throws ConcurrentException; private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException; @Test public void testInitializeTempExec() throws ConcurrentException; @Test public void testInitializeExternalExec() throws ConcurrentException; @Test public void testInitializeChildWithExecutor() throws ConcurrentException; @Test public void testAddInitializerAfterStart() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException; @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException; @Test public void testInitializeRuntimeEx(); @Test public void testInitializeEx() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException; @Test public void testInitializeNested() throws ConcurrentException; @Override protected Integer initialize() throws Exception;
e5db49e456564c5dd9af1c9f84c066fa34b409f08aff61120ad3bd127a5da798
[ "org.apache.commons.lang3.concurrent.MultiBackgroundInitializerTest::testAddInitializerAfterStart" ]
private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>();
@Test public void testAddInitializerAfterStart() throws ConcurrentException
private static final String CHILD_INIT = "childInitializer"; private MultiBackgroundInitializer initializer;
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; /** * Test class for {@link MultiBackgroundInitializer}. * * @version $Id$ */ public class MultiBackgroundInitializerTest { /** Constant for the names of the child initializers. */ private static final String CHILD_INIT = "childInitializer"; /** The initializer to be tested. */ private MultiBackgroundInitializer initializer; @Before public void setUp() throws Exception { initializer = new MultiBackgroundInitializer(); } /** * Tests whether a child initializer has been executed. Optionally the * expected executor service can be checked, too. * * @param child the child initializer * @param expExec the expected executor service (null if the executor should * not be checked) * @throws ConcurrentException if an error occurs */ private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException { final ChildBackgroundInitializer cinit = (ChildBackgroundInitializer) child; final Integer result = cinit.get(); assertEquals("Wrong result", 1, result.intValue()); assertEquals("Wrong number of executions", 1, cinit.initializeCalls); if (expExec != null) { assertEquals("Wrong executor service", expExec, cinit.currentExecutor); } } /** * Tests addInitializer() if a null name is passed in. This should cause an * exception. */ @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName() { initializer.addInitializer(null, new ChildBackgroundInitializer()); } /** * Tests addInitializer() if a null initializer is passed in. This should * cause an exception. */ @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit() { initializer.addInitializer(CHILD_INIT, null); } /** * Tests the background processing if there are no child initializers. */ @Test public void testInitializeNoChildren() throws ConcurrentException { assertTrue("Wrong result of start()", initializer.start()); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertTrue("Got child initializers", res.initializerNames().isEmpty()); assertTrue("Executor not shutdown", initializer.getActiveExecutor() .isShutdown()); } /** * Helper method for testing the initialize() method. This method can * operate with both an external and a temporary executor service. * * @return the result object produced by the initializer */ private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException { final int count = 5; for (int i = 0; i < count; i++) { initializer.addInitializer(CHILD_INIT + i, new ChildBackgroundInitializer()); } initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertEquals("Wrong number of child initializers", count, res .initializerNames().size()); for (int i = 0; i < count; i++) { final String key = CHILD_INIT + i; assertTrue("Name not found: " + key, res.initializerNames() .contains(key)); assertEquals("Wrong result object", Integer.valueOf(1), res .getResultObject(key)); assertFalse("Exception flag", res.isException(key)); assertNull("Got an exception", res.getException(key)); checkChild(res.getInitializer(key), initializer.getActiveExecutor()); } return res; } /** * Tests background processing if a temporary executor is used. */ @Test public void testInitializeTempExec() throws ConcurrentException { checkInitialize(); assertTrue("Executor not shutdown", initializer.getActiveExecutor() .isShutdown()); } /** * Tests background processing if an external executor service is provided. */ @Test public void testInitializeExternalExec() throws ConcurrentException { final ExecutorService exec = Executors.newCachedThreadPool(); try { initializer = new MultiBackgroundInitializer(exec); checkInitialize(); assertEquals("Wrong executor", exec, initializer .getActiveExecutor()); assertFalse("Executor was shutdown", exec.isShutdown()); } finally { exec.shutdown(); } } /** * Tests the behavior of initialize() if a child initializer has a specific * executor service. Then this service should not be overridden. */ @Test public void testInitializeChildWithExecutor() throws ConcurrentException { final String initExec = "childInitializerWithExecutor"; final ExecutorService exec = Executors.newSingleThreadExecutor(); try { final ChildBackgroundInitializer c1 = new ChildBackgroundInitializer(); final ChildBackgroundInitializer c2 = new ChildBackgroundInitializer(); c2.setExternalExecutor(exec); initializer.addInitializer(CHILD_INIT, c1); initializer.addInitializer(initExec, c2); initializer.start(); initializer.get(); checkChild(c1, initializer.getActiveExecutor()); checkChild(c2, exec); } finally { exec.shutdown(); } } /** * Tries to add another child initializer after the start() method has been * called. This should not be allowed. */ @Test public void testAddInitializerAfterStart() throws ConcurrentException { initializer.start(); try { initializer.addInitializer(CHILD_INIT, new ChildBackgroundInitializer()); fail("Could add initializer after start()!"); } catch (final IllegalStateException istex) { initializer.get(); } } /** * Tries to query an unknown child initializer from the results object. This * should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.getInitializer("unknown"); } /** * Tries to query the results of an unknown child initializer from the * results object. This should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.getResultObject("unknown"); } /** * Tries to query the exception of an unknown child initializer from the * results object. This should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.getException("unknown"); } /** * Tries to query the exception flag of an unknown child initializer from * the results object. This should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.isException("unknown"); } /** * Tests that the set with the names of the initializers cannot be modified. */ @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException { checkInitialize(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); final Iterator<String> it = res.initializerNames().iterator(); it.next(); it.remove(); } /** * Tests the behavior of the initializer if one of the child initializers * throws a runtime exception. */ @Test public void testInitializeRuntimeEx() { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); child.ex = new RuntimeException(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); try { initializer.get(); fail("Runtime exception not thrown!"); } catch (final Exception ex) { assertEquals("Wrong exception", child.ex, ex); } } /** * Tests the behavior of the initializer if one of the child initializers * throws a checked exception. */ @Test public void testInitializeEx() throws ConcurrentException { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); child.ex = new Exception(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertTrue("No exception flag", res.isException(CHILD_INIT)); assertNull("Got a results object", res.getResultObject(CHILD_INIT)); final ConcurrentException cex = res.getException(CHILD_INIT); assertEquals("Wrong cause", child.ex, cex.getCause()); } /** * Tests the isSuccessful() method of the result object if no child * initializer has thrown an exception. */ @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertTrue("Wrong success flag", res.isSuccessful()); } /** * Tests the isSuccessful() method of the result object if at least one * child initializer has thrown an exception. */ @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); child.ex = new Exception(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertFalse("Wrong success flag", res.isSuccessful()); } /** * Tests whether MultiBackgroundInitializers can be combined in a nested * way. */ @Test public void testInitializeNested() throws ConcurrentException { final String nameMulti = "multiChildInitializer"; initializer .addInitializer(CHILD_INIT, new ChildBackgroundInitializer()); final MultiBackgroundInitializer mi2 = new MultiBackgroundInitializer(); final int count = 3; for (int i = 0; i < count; i++) { mi2 .addInitializer(CHILD_INIT + i, new ChildBackgroundInitializer()); } initializer.addInitializer(nameMulti, mi2); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); final ExecutorService exec = initializer.getActiveExecutor(); checkChild(res.getInitializer(CHILD_INIT), exec); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res2 = (MultiBackgroundInitializer.MultiBackgroundInitializerResults) res .getResultObject(nameMulti); assertEquals("Wrong number of initializers", count, res2 .initializerNames().size()); for (int i = 0; i < count; i++) { checkChild(res2.getInitializer(CHILD_INIT + i), exec); } assertTrue("Executor not shutdown", exec.isShutdown()); } /** * A concrete implementation of {@code BackgroundInitializer} used for * defining background tasks for {@code MultiBackgroundInitializer}. */ private static class ChildBackgroundInitializer extends BackgroundInitializer<Integer> { /** Stores the current executor service. */ volatile ExecutorService currentExecutor; /** A counter for the invocations of initialize(). */ volatile int initializeCalls; /** An exception to be thrown by initialize(). */ Exception ex; /** * Records this invocation. Optionally throws an exception. */ @Override protected Integer initialize() throws Exception { currentExecutor = getActiveExecutor(); initializeCalls++; if (ex != null) { throw ex; } return Integer.valueOf(initializeCalls); } } }
[ { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "addInitializer", "be_test_function_signature": "(Ljava/lang/String;Lorg/apache/commons/lang3/concurrent/BackgroundInitializer;)V", "line_numbers": [ "135", "136", "139", "140", "144", "145", "146", "149", "150", "151" ], "method_line_rate": 0.5 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "getTaskCount", "be_test_function_signature": "()I", "line_numbers": [ "165", "167", "168", "169", "171" ], "method_line_rate": 0.6 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "initialize", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "97" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "initialize", "be_test_function_signature": "()Lorg/apache/commons/lang3/concurrent/MultiBackgroundInitializer$MultiBackgroundInitializerResults;", "line_numbers": [ "187", "189", "191", "194", "195", "196", "198", "200", "201", "204", "205", "206", "208", "209", "210", "211", "212", "214" ], "method_line_rate": 0.5 } ]
public class ObjectWriterTest extends BaseMapTest
public void testArgumentChecking() throws Exception { final ObjectWriter w = MAPPER.writer(); try { w.acceptJsonFormatVisitor((JavaType) null, null); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "type must be provided"); } }
// public ObjectWriter with(FormatFeature feature); // public ObjectWriter withFeatures(FormatFeature... features); // public ObjectWriter without(FormatFeature feature); // public ObjectWriter withoutFeatures(FormatFeature... features); // public ObjectWriter forType(JavaType rootType); // public ObjectWriter forType(Class<?> rootType); // public ObjectWriter forType(TypeReference<?> rootType); // @Deprecated // since 2.5 // public ObjectWriter withType(JavaType rootType); // @Deprecated // since 2.5 // public ObjectWriter withType(Class<?> rootType); // @Deprecated // since 2.5 // public ObjectWriter withType(TypeReference<?> rootType); // public ObjectWriter with(DateFormat df); // public ObjectWriter withDefaultPrettyPrinter(); // public ObjectWriter with(FilterProvider filterProvider); // public ObjectWriter with(PrettyPrinter pp); // public ObjectWriter withRootName(String rootName); // public ObjectWriter withRootName(PropertyName rootName); // public ObjectWriter withoutRootName(); // public ObjectWriter with(FormatSchema schema); // @Deprecated // public ObjectWriter withSchema(FormatSchema schema); // public ObjectWriter withView(Class<?> view); // public ObjectWriter with(Locale l); // public ObjectWriter with(TimeZone tz); // public ObjectWriter with(Base64Variant b64variant); // public ObjectWriter with(CharacterEscapes escapes); // public ObjectWriter with(JsonFactory f); // public ObjectWriter with(ContextAttributes attrs); // public ObjectWriter withAttributes(Map<?,?> attrs); // public ObjectWriter withAttribute(Object key, Object value); // public ObjectWriter withoutAttribute(Object key); // public ObjectWriter withRootValueSeparator(String sep); // public ObjectWriter withRootValueSeparator(SerializableString sep); // public SequenceWriter writeValues(File out) throws IOException; // public SequenceWriter writeValues(JsonGenerator gen) throws IOException; // public SequenceWriter writeValues(Writer out) throws IOException; // public SequenceWriter writeValues(OutputStream out) throws IOException; // public SequenceWriter writeValues(DataOutput out) throws IOException; // public SequenceWriter writeValuesAsArray(File out) throws IOException; // public SequenceWriter writeValuesAsArray(JsonGenerator gen) throws IOException; // public SequenceWriter writeValuesAsArray(Writer out) throws IOException; // public SequenceWriter writeValuesAsArray(OutputStream out) throws IOException; // public SequenceWriter writeValuesAsArray(DataOutput out) throws IOException; // public boolean isEnabled(SerializationFeature f); // public boolean isEnabled(MapperFeature f); // @Deprecated // public boolean isEnabled(JsonParser.Feature f); // public boolean isEnabled(JsonGenerator.Feature f); // public SerializationConfig getConfig(); // public JsonFactory getFactory(); // public TypeFactory getTypeFactory(); // public boolean hasPrefetchedSerializer(); // public ContextAttributes getAttributes(); // public void writeValue(JsonGenerator gen, Object value) throws IOException; // public void writeValue(File resultFile, Object value) // throws IOException, JsonGenerationException, JsonMappingException; // public void writeValue(OutputStream out, Object value) // throws IOException, JsonGenerationException, JsonMappingException; // public void writeValue(Writer w, Object value) // throws IOException, JsonGenerationException, JsonMappingException; // public void writeValue(DataOutput out, Object value) // throws IOException; // @SuppressWarnings("resource") // public String writeValueAsString(Object value) // throws JsonProcessingException; // @SuppressWarnings("resource") // public byte[] writeValueAsBytes(Object value) // throws JsonProcessingException; // public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) throws JsonMappingException; // public void acceptJsonFormatVisitor(Class<?> rawType, JsonFormatVisitorWrapper visitor) throws JsonMappingException; // public boolean canSerialize(Class<?> type); // public boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause); // protected DefaultSerializerProvider _serializerProvider(); // protected void _verifySchemaType(FormatSchema schema); // protected final void _configAndWriteValue(JsonGenerator gen, Object value) throws IOException; // private final void _writeCloseable(JsonGenerator gen, Object value) // throws IOException; // protected final void _configureGenerator(JsonGenerator gen); // public GeneratorSettings(PrettyPrinter pp, FormatSchema sch, // CharacterEscapes esc, SerializableString rootSep); // public GeneratorSettings with(PrettyPrinter pp); // public GeneratorSettings with(FormatSchema sch); // public GeneratorSettings with(CharacterEscapes esc); // public GeneratorSettings withRootValueSeparator(String sep); // public GeneratorSettings withRootValueSeparator(SerializableString sep); // private final String _rootValueSeparatorAsString(); // public void initialize(JsonGenerator gen); // private Prefetch(JavaType rootT, // JsonSerializer<Object> ser, TypeSerializer typeSer); // public Prefetch forRootType(ObjectWriter parent, JavaType newType); // public final JsonSerializer<Object> getValueSerializer(); // public final TypeSerializer getTypeSerializer(); // public boolean hasSerializer(); // public void serialize(JsonGenerator gen, Object value, DefaultSerializerProvider prov) // throws IOException; // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.ByteArrayOutputStream; // import java.io.Closeable; // import java.io.IOException; // import java.io.StringWriter; // import java.util.*; // import com.fasterxml.jackson.annotation.JsonTypeInfo; // import com.fasterxml.jackson.annotation.JsonTypeName; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.io.SerializedString; // import com.fasterxml.jackson.databind.node.ObjectNode; // // // // public class ObjectWriterTest // extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testPrettyPrinter() throws Exception; // public void testPrefetch() throws Exception; // public void testObjectWriterFeatures() throws Exception; // public void testObjectWriterWithNode() throws Exception; // public void testPolymorphicWithTyping() throws Exception; // public void testCanSerialize() throws Exception; // public void testNoPrefetch() throws Exception; // public void testWithCloseCloseable() throws Exception; // public void testViewSettings() throws Exception; // public void testMiscSettings() throws Exception; // public void testRootValueSettings() throws Exception; // public void testFeatureSettings() throws Exception; // public void testGeneratorFeatures() throws Exception; // public void testArgumentChecking() throws Exception; // public void testSchema() throws Exception; // @Override // public void close() throws IOException; // public ImplA(int v); // public ImplB(int v); // } // You are a professional Java test case writer, please create a test case named `testArgumentChecking` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, failures /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/ObjectWriterTest.java
package com.fasterxml.jackson.databind; import java.io.*; import java.text.*; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.CharacterEscapes; import com.fasterxml.jackson.core.io.SegmentedStringWriter; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.util.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.*; import com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.util.ClassUtil;
protected ObjectWriter(ObjectMapper mapper, SerializationConfig config, JavaType rootType, PrettyPrinter pp); protected ObjectWriter(ObjectMapper mapper, SerializationConfig config); protected ObjectWriter(ObjectMapper mapper, SerializationConfig config, FormatSchema s); protected ObjectWriter(ObjectWriter base, SerializationConfig config, GeneratorSettings genSettings, Prefetch prefetch); protected ObjectWriter(ObjectWriter base, SerializationConfig config); protected ObjectWriter(ObjectWriter base, JsonFactory f); @Override public Version version(); protected ObjectWriter _new(ObjectWriter base, JsonFactory f); protected ObjectWriter _new(ObjectWriter base, SerializationConfig config); protected ObjectWriter _new(GeneratorSettings genSettings, Prefetch prefetch); @SuppressWarnings("resource") protected SequenceWriter _newSequenceWriter(boolean wrapInArray, JsonGenerator gen, boolean managedInput) throws IOException; public ObjectWriter with(SerializationFeature feature); public ObjectWriter with(SerializationFeature first, SerializationFeature... other); public ObjectWriter withFeatures(SerializationFeature... features); public ObjectWriter without(SerializationFeature feature); public ObjectWriter without(SerializationFeature first, SerializationFeature... other); public ObjectWriter withoutFeatures(SerializationFeature... features); public ObjectWriter with(JsonGenerator.Feature feature); public ObjectWriter withFeatures(JsonGenerator.Feature... features); public ObjectWriter without(JsonGenerator.Feature feature); public ObjectWriter withoutFeatures(JsonGenerator.Feature... features); public ObjectWriter with(FormatFeature feature); public ObjectWriter withFeatures(FormatFeature... features); public ObjectWriter without(FormatFeature feature); public ObjectWriter withoutFeatures(FormatFeature... features); public ObjectWriter forType(JavaType rootType); public ObjectWriter forType(Class<?> rootType); public ObjectWriter forType(TypeReference<?> rootType); @Deprecated // since 2.5 public ObjectWriter withType(JavaType rootType); @Deprecated // since 2.5 public ObjectWriter withType(Class<?> rootType); @Deprecated // since 2.5 public ObjectWriter withType(TypeReference<?> rootType); public ObjectWriter with(DateFormat df); public ObjectWriter withDefaultPrettyPrinter(); public ObjectWriter with(FilterProvider filterProvider); public ObjectWriter with(PrettyPrinter pp); public ObjectWriter withRootName(String rootName); public ObjectWriter withRootName(PropertyName rootName); public ObjectWriter withoutRootName(); public ObjectWriter with(FormatSchema schema); @Deprecated public ObjectWriter withSchema(FormatSchema schema); public ObjectWriter withView(Class<?> view); public ObjectWriter with(Locale l); public ObjectWriter with(TimeZone tz); public ObjectWriter with(Base64Variant b64variant); public ObjectWriter with(CharacterEscapes escapes); public ObjectWriter with(JsonFactory f); public ObjectWriter with(ContextAttributes attrs); public ObjectWriter withAttributes(Map<?,?> attrs); public ObjectWriter withAttribute(Object key, Object value); public ObjectWriter withoutAttribute(Object key); public ObjectWriter withRootValueSeparator(String sep); public ObjectWriter withRootValueSeparator(SerializableString sep); public SequenceWriter writeValues(File out) throws IOException; public SequenceWriter writeValues(JsonGenerator gen) throws IOException; public SequenceWriter writeValues(Writer out) throws IOException; public SequenceWriter writeValues(OutputStream out) throws IOException; public SequenceWriter writeValues(DataOutput out) throws IOException; public SequenceWriter writeValuesAsArray(File out) throws IOException; public SequenceWriter writeValuesAsArray(JsonGenerator gen) throws IOException; public SequenceWriter writeValuesAsArray(Writer out) throws IOException; public SequenceWriter writeValuesAsArray(OutputStream out) throws IOException; public SequenceWriter writeValuesAsArray(DataOutput out) throws IOException; public boolean isEnabled(SerializationFeature f); public boolean isEnabled(MapperFeature f); @Deprecated public boolean isEnabled(JsonParser.Feature f); public boolean isEnabled(JsonGenerator.Feature f); public SerializationConfig getConfig(); public JsonFactory getFactory(); public TypeFactory getTypeFactory(); public boolean hasPrefetchedSerializer(); public ContextAttributes getAttributes(); public void writeValue(JsonGenerator gen, Object value) throws IOException; public void writeValue(File resultFile, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(OutputStream out, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(Writer w, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(DataOutput out, Object value) throws IOException; @SuppressWarnings("resource") public String writeValueAsString(Object value) throws JsonProcessingException; @SuppressWarnings("resource") public byte[] writeValueAsBytes(Object value) throws JsonProcessingException; public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) throws JsonMappingException; public void acceptJsonFormatVisitor(Class<?> rawType, JsonFormatVisitorWrapper visitor) throws JsonMappingException; public boolean canSerialize(Class<?> type); public boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause); protected DefaultSerializerProvider _serializerProvider(); protected void _verifySchemaType(FormatSchema schema); protected final void _configAndWriteValue(JsonGenerator gen, Object value) throws IOException; private final void _writeCloseable(JsonGenerator gen, Object value) throws IOException; protected final void _configureGenerator(JsonGenerator gen); public GeneratorSettings(PrettyPrinter pp, FormatSchema sch, CharacterEscapes esc, SerializableString rootSep); public GeneratorSettings with(PrettyPrinter pp); public GeneratorSettings with(FormatSchema sch); public GeneratorSettings with(CharacterEscapes esc); public GeneratorSettings withRootValueSeparator(String sep); public GeneratorSettings withRootValueSeparator(SerializableString sep); private final String _rootValueSeparatorAsString(); public void initialize(JsonGenerator gen); private Prefetch(JavaType rootT, JsonSerializer<Object> ser, TypeSerializer typeSer); public Prefetch forRootType(ObjectWriter parent, JavaType newType); public final JsonSerializer<Object> getValueSerializer(); public final TypeSerializer getTypeSerializer(); public boolean hasSerializer(); public void serialize(JsonGenerator gen, Object value, DefaultSerializerProvider prov) throws IOException;
286
testArgumentChecking
```java public ObjectWriter with(FormatFeature feature); public ObjectWriter withFeatures(FormatFeature... features); public ObjectWriter without(FormatFeature feature); public ObjectWriter withoutFeatures(FormatFeature... features); public ObjectWriter forType(JavaType rootType); public ObjectWriter forType(Class<?> rootType); public ObjectWriter forType(TypeReference<?> rootType); @Deprecated // since 2.5 public ObjectWriter withType(JavaType rootType); @Deprecated // since 2.5 public ObjectWriter withType(Class<?> rootType); @Deprecated // since 2.5 public ObjectWriter withType(TypeReference<?> rootType); public ObjectWriter with(DateFormat df); public ObjectWriter withDefaultPrettyPrinter(); public ObjectWriter with(FilterProvider filterProvider); public ObjectWriter with(PrettyPrinter pp); public ObjectWriter withRootName(String rootName); public ObjectWriter withRootName(PropertyName rootName); public ObjectWriter withoutRootName(); public ObjectWriter with(FormatSchema schema); @Deprecated public ObjectWriter withSchema(FormatSchema schema); public ObjectWriter withView(Class<?> view); public ObjectWriter with(Locale l); public ObjectWriter with(TimeZone tz); public ObjectWriter with(Base64Variant b64variant); public ObjectWriter with(CharacterEscapes escapes); public ObjectWriter with(JsonFactory f); public ObjectWriter with(ContextAttributes attrs); public ObjectWriter withAttributes(Map<?,?> attrs); public ObjectWriter withAttribute(Object key, Object value); public ObjectWriter withoutAttribute(Object key); public ObjectWriter withRootValueSeparator(String sep); public ObjectWriter withRootValueSeparator(SerializableString sep); public SequenceWriter writeValues(File out) throws IOException; public SequenceWriter writeValues(JsonGenerator gen) throws IOException; public SequenceWriter writeValues(Writer out) throws IOException; public SequenceWriter writeValues(OutputStream out) throws IOException; public SequenceWriter writeValues(DataOutput out) throws IOException; public SequenceWriter writeValuesAsArray(File out) throws IOException; public SequenceWriter writeValuesAsArray(JsonGenerator gen) throws IOException; public SequenceWriter writeValuesAsArray(Writer out) throws IOException; public SequenceWriter writeValuesAsArray(OutputStream out) throws IOException; public SequenceWriter writeValuesAsArray(DataOutput out) throws IOException; public boolean isEnabled(SerializationFeature f); public boolean isEnabled(MapperFeature f); @Deprecated public boolean isEnabled(JsonParser.Feature f); public boolean isEnabled(JsonGenerator.Feature f); public SerializationConfig getConfig(); public JsonFactory getFactory(); public TypeFactory getTypeFactory(); public boolean hasPrefetchedSerializer(); public ContextAttributes getAttributes(); public void writeValue(JsonGenerator gen, Object value) throws IOException; public void writeValue(File resultFile, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(OutputStream out, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(Writer w, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(DataOutput out, Object value) throws IOException; @SuppressWarnings("resource") public String writeValueAsString(Object value) throws JsonProcessingException; @SuppressWarnings("resource") public byte[] writeValueAsBytes(Object value) throws JsonProcessingException; public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) throws JsonMappingException; public void acceptJsonFormatVisitor(Class<?> rawType, JsonFormatVisitorWrapper visitor) throws JsonMappingException; public boolean canSerialize(Class<?> type); public boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause); protected DefaultSerializerProvider _serializerProvider(); protected void _verifySchemaType(FormatSchema schema); protected final void _configAndWriteValue(JsonGenerator gen, Object value) throws IOException; private final void _writeCloseable(JsonGenerator gen, Object value) throws IOException; protected final void _configureGenerator(JsonGenerator gen); public GeneratorSettings(PrettyPrinter pp, FormatSchema sch, CharacterEscapes esc, SerializableString rootSep); public GeneratorSettings with(PrettyPrinter pp); public GeneratorSettings with(FormatSchema sch); public GeneratorSettings with(CharacterEscapes esc); public GeneratorSettings withRootValueSeparator(String sep); public GeneratorSettings withRootValueSeparator(SerializableString sep); private final String _rootValueSeparatorAsString(); public void initialize(JsonGenerator gen); private Prefetch(JavaType rootT, JsonSerializer<Object> ser, TypeSerializer typeSer); public Prefetch forRootType(ObjectWriter parent, JavaType newType); public final JsonSerializer<Object> getValueSerializer(); public final TypeSerializer getTypeSerializer(); public boolean hasSerializer(); public void serialize(JsonGenerator gen, Object value, DefaultSerializerProvider prov) throws IOException; } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.StringWriter; import java.util.*; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectWriterTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testPrettyPrinter() throws Exception; public void testPrefetch() throws Exception; public void testObjectWriterFeatures() throws Exception; public void testObjectWriterWithNode() throws Exception; public void testPolymorphicWithTyping() throws Exception; public void testCanSerialize() throws Exception; public void testNoPrefetch() throws Exception; public void testWithCloseCloseable() throws Exception; public void testViewSettings() throws Exception; public void testMiscSettings() throws Exception; public void testRootValueSettings() throws Exception; public void testFeatureSettings() throws Exception; public void testGeneratorFeatures() throws Exception; public void testArgumentChecking() throws Exception; public void testSchema() throws Exception; @Override public void close() throws IOException; public ImplA(int v); public ImplB(int v); } ``` You are a professional Java test case writer, please create a test case named `testArgumentChecking` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, failures /********************************************************** */
277
// public ObjectWriter with(FormatFeature feature); // public ObjectWriter withFeatures(FormatFeature... features); // public ObjectWriter without(FormatFeature feature); // public ObjectWriter withoutFeatures(FormatFeature... features); // public ObjectWriter forType(JavaType rootType); // public ObjectWriter forType(Class<?> rootType); // public ObjectWriter forType(TypeReference<?> rootType); // @Deprecated // since 2.5 // public ObjectWriter withType(JavaType rootType); // @Deprecated // since 2.5 // public ObjectWriter withType(Class<?> rootType); // @Deprecated // since 2.5 // public ObjectWriter withType(TypeReference<?> rootType); // public ObjectWriter with(DateFormat df); // public ObjectWriter withDefaultPrettyPrinter(); // public ObjectWriter with(FilterProvider filterProvider); // public ObjectWriter with(PrettyPrinter pp); // public ObjectWriter withRootName(String rootName); // public ObjectWriter withRootName(PropertyName rootName); // public ObjectWriter withoutRootName(); // public ObjectWriter with(FormatSchema schema); // @Deprecated // public ObjectWriter withSchema(FormatSchema schema); // public ObjectWriter withView(Class<?> view); // public ObjectWriter with(Locale l); // public ObjectWriter with(TimeZone tz); // public ObjectWriter with(Base64Variant b64variant); // public ObjectWriter with(CharacterEscapes escapes); // public ObjectWriter with(JsonFactory f); // public ObjectWriter with(ContextAttributes attrs); // public ObjectWriter withAttributes(Map<?,?> attrs); // public ObjectWriter withAttribute(Object key, Object value); // public ObjectWriter withoutAttribute(Object key); // public ObjectWriter withRootValueSeparator(String sep); // public ObjectWriter withRootValueSeparator(SerializableString sep); // public SequenceWriter writeValues(File out) throws IOException; // public SequenceWriter writeValues(JsonGenerator gen) throws IOException; // public SequenceWriter writeValues(Writer out) throws IOException; // public SequenceWriter writeValues(OutputStream out) throws IOException; // public SequenceWriter writeValues(DataOutput out) throws IOException; // public SequenceWriter writeValuesAsArray(File out) throws IOException; // public SequenceWriter writeValuesAsArray(JsonGenerator gen) throws IOException; // public SequenceWriter writeValuesAsArray(Writer out) throws IOException; // public SequenceWriter writeValuesAsArray(OutputStream out) throws IOException; // public SequenceWriter writeValuesAsArray(DataOutput out) throws IOException; // public boolean isEnabled(SerializationFeature f); // public boolean isEnabled(MapperFeature f); // @Deprecated // public boolean isEnabled(JsonParser.Feature f); // public boolean isEnabled(JsonGenerator.Feature f); // public SerializationConfig getConfig(); // public JsonFactory getFactory(); // public TypeFactory getTypeFactory(); // public boolean hasPrefetchedSerializer(); // public ContextAttributes getAttributes(); // public void writeValue(JsonGenerator gen, Object value) throws IOException; // public void writeValue(File resultFile, Object value) // throws IOException, JsonGenerationException, JsonMappingException; // public void writeValue(OutputStream out, Object value) // throws IOException, JsonGenerationException, JsonMappingException; // public void writeValue(Writer w, Object value) // throws IOException, JsonGenerationException, JsonMappingException; // public void writeValue(DataOutput out, Object value) // throws IOException; // @SuppressWarnings("resource") // public String writeValueAsString(Object value) // throws JsonProcessingException; // @SuppressWarnings("resource") // public byte[] writeValueAsBytes(Object value) // throws JsonProcessingException; // public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) throws JsonMappingException; // public void acceptJsonFormatVisitor(Class<?> rawType, JsonFormatVisitorWrapper visitor) throws JsonMappingException; // public boolean canSerialize(Class<?> type); // public boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause); // protected DefaultSerializerProvider _serializerProvider(); // protected void _verifySchemaType(FormatSchema schema); // protected final void _configAndWriteValue(JsonGenerator gen, Object value) throws IOException; // private final void _writeCloseable(JsonGenerator gen, Object value) // throws IOException; // protected final void _configureGenerator(JsonGenerator gen); // public GeneratorSettings(PrettyPrinter pp, FormatSchema sch, // CharacterEscapes esc, SerializableString rootSep); // public GeneratorSettings with(PrettyPrinter pp); // public GeneratorSettings with(FormatSchema sch); // public GeneratorSettings with(CharacterEscapes esc); // public GeneratorSettings withRootValueSeparator(String sep); // public GeneratorSettings withRootValueSeparator(SerializableString sep); // private final String _rootValueSeparatorAsString(); // public void initialize(JsonGenerator gen); // private Prefetch(JavaType rootT, // JsonSerializer<Object> ser, TypeSerializer typeSer); // public Prefetch forRootType(ObjectWriter parent, JavaType newType); // public final JsonSerializer<Object> getValueSerializer(); // public final TypeSerializer getTypeSerializer(); // public boolean hasSerializer(); // public void serialize(JsonGenerator gen, Object value, DefaultSerializerProvider prov) // throws IOException; // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.ByteArrayOutputStream; // import java.io.Closeable; // import java.io.IOException; // import java.io.StringWriter; // import java.util.*; // import com.fasterxml.jackson.annotation.JsonTypeInfo; // import com.fasterxml.jackson.annotation.JsonTypeName; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.io.SerializedString; // import com.fasterxml.jackson.databind.node.ObjectNode; // // // // public class ObjectWriterTest // extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testPrettyPrinter() throws Exception; // public void testPrefetch() throws Exception; // public void testObjectWriterFeatures() throws Exception; // public void testObjectWriterWithNode() throws Exception; // public void testPolymorphicWithTyping() throws Exception; // public void testCanSerialize() throws Exception; // public void testNoPrefetch() throws Exception; // public void testWithCloseCloseable() throws Exception; // public void testViewSettings() throws Exception; // public void testMiscSettings() throws Exception; // public void testRootValueSettings() throws Exception; // public void testFeatureSettings() throws Exception; // public void testGeneratorFeatures() throws Exception; // public void testArgumentChecking() throws Exception; // public void testSchema() throws Exception; // @Override // public void close() throws IOException; // public ImplA(int v); // public ImplB(int v); // } // You are a professional Java test case writer, please create a test case named `testArgumentChecking` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, failures /********************************************************** */ public void testArgumentChecking() throws Exception {
/* /********************************************************** /* Test methods, failures /********************************************************** */
112
com.fasterxml.jackson.databind.ObjectWriter
src/test/java
```java public ObjectWriter with(FormatFeature feature); public ObjectWriter withFeatures(FormatFeature... features); public ObjectWriter without(FormatFeature feature); public ObjectWriter withoutFeatures(FormatFeature... features); public ObjectWriter forType(JavaType rootType); public ObjectWriter forType(Class<?> rootType); public ObjectWriter forType(TypeReference<?> rootType); @Deprecated // since 2.5 public ObjectWriter withType(JavaType rootType); @Deprecated // since 2.5 public ObjectWriter withType(Class<?> rootType); @Deprecated // since 2.5 public ObjectWriter withType(TypeReference<?> rootType); public ObjectWriter with(DateFormat df); public ObjectWriter withDefaultPrettyPrinter(); public ObjectWriter with(FilterProvider filterProvider); public ObjectWriter with(PrettyPrinter pp); public ObjectWriter withRootName(String rootName); public ObjectWriter withRootName(PropertyName rootName); public ObjectWriter withoutRootName(); public ObjectWriter with(FormatSchema schema); @Deprecated public ObjectWriter withSchema(FormatSchema schema); public ObjectWriter withView(Class<?> view); public ObjectWriter with(Locale l); public ObjectWriter with(TimeZone tz); public ObjectWriter with(Base64Variant b64variant); public ObjectWriter with(CharacterEscapes escapes); public ObjectWriter with(JsonFactory f); public ObjectWriter with(ContextAttributes attrs); public ObjectWriter withAttributes(Map<?,?> attrs); public ObjectWriter withAttribute(Object key, Object value); public ObjectWriter withoutAttribute(Object key); public ObjectWriter withRootValueSeparator(String sep); public ObjectWriter withRootValueSeparator(SerializableString sep); public SequenceWriter writeValues(File out) throws IOException; public SequenceWriter writeValues(JsonGenerator gen) throws IOException; public SequenceWriter writeValues(Writer out) throws IOException; public SequenceWriter writeValues(OutputStream out) throws IOException; public SequenceWriter writeValues(DataOutput out) throws IOException; public SequenceWriter writeValuesAsArray(File out) throws IOException; public SequenceWriter writeValuesAsArray(JsonGenerator gen) throws IOException; public SequenceWriter writeValuesAsArray(Writer out) throws IOException; public SequenceWriter writeValuesAsArray(OutputStream out) throws IOException; public SequenceWriter writeValuesAsArray(DataOutput out) throws IOException; public boolean isEnabled(SerializationFeature f); public boolean isEnabled(MapperFeature f); @Deprecated public boolean isEnabled(JsonParser.Feature f); public boolean isEnabled(JsonGenerator.Feature f); public SerializationConfig getConfig(); public JsonFactory getFactory(); public TypeFactory getTypeFactory(); public boolean hasPrefetchedSerializer(); public ContextAttributes getAttributes(); public void writeValue(JsonGenerator gen, Object value) throws IOException; public void writeValue(File resultFile, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(OutputStream out, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(Writer w, Object value) throws IOException, JsonGenerationException, JsonMappingException; public void writeValue(DataOutput out, Object value) throws IOException; @SuppressWarnings("resource") public String writeValueAsString(Object value) throws JsonProcessingException; @SuppressWarnings("resource") public byte[] writeValueAsBytes(Object value) throws JsonProcessingException; public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) throws JsonMappingException; public void acceptJsonFormatVisitor(Class<?> rawType, JsonFormatVisitorWrapper visitor) throws JsonMappingException; public boolean canSerialize(Class<?> type); public boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause); protected DefaultSerializerProvider _serializerProvider(); protected void _verifySchemaType(FormatSchema schema); protected final void _configAndWriteValue(JsonGenerator gen, Object value) throws IOException; private final void _writeCloseable(JsonGenerator gen, Object value) throws IOException; protected final void _configureGenerator(JsonGenerator gen); public GeneratorSettings(PrettyPrinter pp, FormatSchema sch, CharacterEscapes esc, SerializableString rootSep); public GeneratorSettings with(PrettyPrinter pp); public GeneratorSettings with(FormatSchema sch); public GeneratorSettings with(CharacterEscapes esc); public GeneratorSettings withRootValueSeparator(String sep); public GeneratorSettings withRootValueSeparator(SerializableString sep); private final String _rootValueSeparatorAsString(); public void initialize(JsonGenerator gen); private Prefetch(JavaType rootT, JsonSerializer<Object> ser, TypeSerializer typeSer); public Prefetch forRootType(ObjectWriter parent, JavaType newType); public final JsonSerializer<Object> getValueSerializer(); public final TypeSerializer getTypeSerializer(); public boolean hasSerializer(); public void serialize(JsonGenerator gen, Object value, DefaultSerializerProvider prov) throws IOException; } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.StringWriter; import java.util.*; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectWriterTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testPrettyPrinter() throws Exception; public void testPrefetch() throws Exception; public void testObjectWriterFeatures() throws Exception; public void testObjectWriterWithNode() throws Exception; public void testPolymorphicWithTyping() throws Exception; public void testCanSerialize() throws Exception; public void testNoPrefetch() throws Exception; public void testWithCloseCloseable() throws Exception; public void testViewSettings() throws Exception; public void testMiscSettings() throws Exception; public void testRootValueSettings() throws Exception; public void testFeatureSettings() throws Exception; public void testGeneratorFeatures() throws Exception; public void testArgumentChecking() throws Exception; public void testSchema() throws Exception; @Override public void close() throws IOException; public ImplA(int v); public ImplB(int v); } ``` You are a professional Java test case writer, please create a test case named `testArgumentChecking` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, failures /********************************************************** */ public void testArgumentChecking() throws Exception { ```
public class ObjectWriter implements Versioned, java.io.Serializable // since 2.1
package com.fasterxml.jackson.databind; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.StringWriter; import java.util.*; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.databind.node.ObjectNode;
public void testPrettyPrinter() throws Exception; public void testPrefetch() throws Exception; public void testObjectWriterFeatures() throws Exception; public void testObjectWriterWithNode() throws Exception; public void testPolymorphicWithTyping() throws Exception; public void testCanSerialize() throws Exception; public void testNoPrefetch() throws Exception; public void testWithCloseCloseable() throws Exception; public void testViewSettings() throws Exception; public void testMiscSettings() throws Exception; public void testRootValueSettings() throws Exception; public void testFeatureSettings() throws Exception; public void testGeneratorFeatures() throws Exception; public void testArgumentChecking() throws Exception; public void testSchema() throws Exception; @Override public void close() throws IOException; public ImplA(int v); public ImplB(int v);
e6815a6d8fc08a6870105062db9a1e0bc54cbf9191e969810d6178dfd4506653
[ "com.fasterxml.jackson.databind.ObjectWriterTest::testArgumentChecking" ]
private static final long serialVersionUID = 1; protected final static PrettyPrinter NULL_PRETTY_PRINTER = new MinimalPrettyPrinter(); protected final SerializationConfig _config; protected final DefaultSerializerProvider _serializerProvider; protected final SerializerFactory _serializerFactory; protected final JsonFactory _generatorFactory; protected final GeneratorSettings _generatorSettings; protected final Prefetch _prefetch;
public void testArgumentChecking() throws Exception
final ObjectMapper MAPPER = new ObjectMapper();
JacksonDatabind
package com.fasterxml.jackson.databind; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.StringWriter; import java.util.*; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Unit tests for checking features added to {@link ObjectWriter}, such * as adding of explicit pretty printer. */ public class ObjectWriterTest extends BaseMapTest { static class CloseableValue implements Closeable { public int x; public boolean closed; @Override public void close() throws IOException { closed = true; } } final ObjectMapper MAPPER = new ObjectMapper(); @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") static class PolyBase { } @JsonTypeName("A") static class ImplA extends PolyBase { public int value; public ImplA(int v) { value = v; } } @JsonTypeName("B") static class ImplB extends PolyBase { public int b; public ImplB(int v) { b = v; } } /* /********************************************************** /* Test methods, normal operation /********************************************************** */ public void testPrettyPrinter() throws Exception { ObjectWriter writer = MAPPER.writer(); HashMap<String, Integer> data = new HashMap<String,Integer>(); data.put("a", 1); // default: no indentation assertEquals("{\"a\":1}", writer.writeValueAsString(data)); // and then with standard writer = writer.withDefaultPrettyPrinter(); // pretty printer uses system-specific line feeds, so we do that as well. String lf = System.getProperty("line.separator"); assertEquals("{" + lf + " \"a\" : 1" + lf + "}", writer.writeValueAsString(data)); // and finally, again without indentation writer = writer.with((PrettyPrinter) null); assertEquals("{\"a\":1}", writer.writeValueAsString(data)); } public void testPrefetch() throws Exception { ObjectWriter writer = MAPPER.writer(); assertFalse(writer.hasPrefetchedSerializer()); writer = writer.forType(String.class); assertTrue(writer.hasPrefetchedSerializer()); } public void testObjectWriterFeatures() throws Exception { ObjectWriter writer = MAPPER.writer() .without(JsonGenerator.Feature.QUOTE_FIELD_NAMES); Map<String,Integer> map = new HashMap<String,Integer>(); map.put("a", 1); assertEquals("{a:1}", writer.writeValueAsString(map)); // but can also reconfigure assertEquals("{\"a\":1}", writer.with(JsonGenerator.Feature.QUOTE_FIELD_NAMES) .writeValueAsString(map)); } public void testObjectWriterWithNode() throws Exception { ObjectNode stuff = MAPPER.createObjectNode(); stuff.put("a", 5); ObjectWriter writer = MAPPER.writerFor(JsonNode.class); String json = writer.writeValueAsString(stuff); assertEquals("{\"a\":5}", json); } public void testPolymorphicWithTyping() throws Exception { ObjectWriter writer = MAPPER.writerFor(PolyBase.class); String json; json = writer.writeValueAsString(new ImplA(3)); assertEquals(aposToQuotes("{'type':'A','value':3}"), json); json = writer.writeValueAsString(new ImplB(-5)); assertEquals(aposToQuotes("{'type':'B','b':-5}"), json); } public void testCanSerialize() throws Exception { assertTrue(MAPPER.writer().canSerialize(String.class)); assertTrue(MAPPER.writer().canSerialize(String.class, null)); } public void testNoPrefetch() throws Exception { ObjectWriter w = MAPPER.writer() .without(SerializationFeature.EAGER_SERIALIZER_FETCH); ByteArrayOutputStream out = new ByteArrayOutputStream(); w.writeValue(out, Integer.valueOf(3)); out.close(); assertEquals("3", out.toString("UTF-8")); } public void testWithCloseCloseable() throws Exception { ObjectWriter w = MAPPER.writer() .with(SerializationFeature.CLOSE_CLOSEABLE); assertTrue(w.isEnabled(SerializationFeature.CLOSE_CLOSEABLE)); CloseableValue input = new CloseableValue(); assertFalse(input.closed); byte[] json = w.writeValueAsBytes(input); assertNotNull(json); assertTrue(input.closed); input.close(); // and via explicitly passed generator JsonGenerator g = MAPPER.getFactory().createGenerator(new StringWriter()); input = new CloseableValue(); assertFalse(input.closed); w.writeValue(g, input); assertTrue(input.closed); g.close(); input.close(); } public void testViewSettings() throws Exception { ObjectWriter w = MAPPER.writer(); ObjectWriter newW = w.withView(String.class); assertNotSame(w, newW); assertSame(newW, newW.withView(String.class)); newW = w.with(Locale.CANADA); assertNotSame(w, newW); assertSame(newW, newW.with(Locale.CANADA)); } public void testMiscSettings() throws Exception { ObjectWriter w = MAPPER.writer(); assertSame(MAPPER.getFactory(), w.getFactory()); assertFalse(w.hasPrefetchedSerializer()); assertNotNull(w.getTypeFactory()); JsonFactory f = new JsonFactory(); w = w.with(f); assertSame(f, w.getFactory()); ObjectWriter newW = w.with(Base64Variants.MODIFIED_FOR_URL); assertNotSame(w, newW); assertSame(newW, newW.with(Base64Variants.MODIFIED_FOR_URL)); w = w.withAttributes(Collections.emptyMap()); w = w.withAttribute("a", "b"); assertEquals("b", w.getAttributes().getAttribute("a")); w = w.withoutAttribute("a"); assertNull(w.getAttributes().getAttribute("a")); FormatSchema schema = new BogusSchema(); try { newW = w.with(schema); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "Cannot use FormatSchema"); } } public void testRootValueSettings() throws Exception { ObjectWriter w = MAPPER.writer(); // First, root name: ObjectWriter newW = w.withRootName("foo"); assertNotSame(w, newW); assertSame(newW, newW.withRootName(PropertyName.construct("foo"))); w = newW; newW = w.withRootName((String) null); assertNotSame(w, newW); assertSame(newW, newW.withRootName((PropertyName) null)); // Then root value separator w = w.withRootValueSeparator(new SerializedString(",")); assertSame(w, w.withRootValueSeparator(new SerializedString(","))); assertSame(w, w.withRootValueSeparator(",")); newW = w.withRootValueSeparator("/"); assertNotSame(w, newW); assertSame(newW, newW.withRootValueSeparator("/")); newW = w.withRootValueSeparator((String) null); assertNotSame(w, newW); newW = w.withRootValueSeparator((SerializableString) null); assertNotSame(w, newW); } public void testFeatureSettings() throws Exception { ObjectWriter w = MAPPER.writer(); assertFalse(w.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)); assertFalse(w.isEnabled(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION)); ObjectWriter newW = w.with(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, SerializationFeature.INDENT_OUTPUT); assertNotSame(w, newW); assertTrue(newW.isEnabled(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); assertTrue(newW.isEnabled(SerializationFeature.INDENT_OUTPUT)); assertSame(newW, newW.with(SerializationFeature.INDENT_OUTPUT)); assertSame(newW, newW.withFeatures(SerializationFeature.INDENT_OUTPUT)); newW = w.withFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, SerializationFeature.INDENT_OUTPUT); assertNotSame(w, newW); newW = w.without(SerializationFeature.FAIL_ON_EMPTY_BEANS, SerializationFeature.EAGER_SERIALIZER_FETCH); assertNotSame(w, newW); assertFalse(newW.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertFalse(newW.isEnabled(SerializationFeature.EAGER_SERIALIZER_FETCH)); assertSame(newW, newW.without(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertSame(newW, newW.withoutFeatures(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertNotSame(w, w.withoutFeatures(SerializationFeature.FAIL_ON_EMPTY_BEANS, SerializationFeature.EAGER_SERIALIZER_FETCH)); } public void testGeneratorFeatures() throws Exception { ObjectWriter w = MAPPER.writer(); assertFalse(w.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); assertNotSame(w, w.with(JsonGenerator.Feature.ESCAPE_NON_ASCII)); assertNotSame(w, w.withFeatures(JsonGenerator.Feature.ESCAPE_NON_ASCII)); assertTrue(w.isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)); assertNotSame(w, w.without(JsonGenerator.Feature.AUTO_CLOSE_TARGET)); assertNotSame(w, w.withoutFeatures(JsonGenerator.Feature.AUTO_CLOSE_TARGET)); } /* /********************************************************** /* Test methods, failures /********************************************************** */ public void testArgumentChecking() throws Exception { final ObjectWriter w = MAPPER.writer(); try { w.acceptJsonFormatVisitor((JavaType) null, null); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "type must be provided"); } } public void testSchema() throws Exception { try { MAPPER.writerFor(String.class) .with(new BogusSchema()) .writeValueAsBytes("foo"); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "Cannot use FormatSchema"); } } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectWriter.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectWriter", "be_test_function_name": "acceptJsonFormatVisitor", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/JavaType;Lcom/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitorWrapper;)V", "line_numbers": [ "1048", "1049", "1051", "1052" ], "method_line_rate": 0.5 } ]
public class TimeSeriesTests extends TestCase implements SeriesChangeListener
public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); assertEquals(16.89, s1.getMinY(), EPSILON); assertEquals(19.32, s1.getMaxY(), EPSILON); }
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.lang.reflect.InvocationTargetException; // import java.lang.reflect.Method; // import java.util.Collection; // import java.util.Collections; // import java.util.Date; // import java.util.Iterator; // import java.util.List; // import java.util.TimeZone; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.data.general.Series; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.general.SeriesException; // // // // public class TimeSeries extends Series implements Cloneable, Serializable { // private static final long serialVersionUID = -5032960206869675528L; // protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; // protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; // private String domain; // private String range; // protected Class timePeriodClass; // protected List data; // private int maximumItemCount; // private long maximumItemAge; // private double minY; // private double maxY; // // public TimeSeries(Comparable name); // public TimeSeries(Comparable name, String domain, String range); // public String getDomainDescription(); // public void setDomainDescription(String description); // public String getRangeDescription(); // public void setRangeDescription(String description); // public int getItemCount(); // public List getItems(); // public int getMaximumItemCount(); // public void setMaximumItemCount(int maximum); // public long getMaximumItemAge(); // public void setMaximumItemAge(long periods); // public double getMinY(); // public double getMaxY(); // public Class getTimePeriodClass(); // public TimeSeriesDataItem getDataItem(int index); // public TimeSeriesDataItem getDataItem(RegularTimePeriod period); // TimeSeriesDataItem getRawDataItem(int index); // TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); // public RegularTimePeriod getTimePeriod(int index); // public RegularTimePeriod getNextTimePeriod(); // public Collection getTimePeriods(); // public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); // public int getIndex(RegularTimePeriod period); // public Number getValue(int index); // public Number getValue(RegularTimePeriod period); // public void add(TimeSeriesDataItem item); // public void add(TimeSeriesDataItem item, boolean notify); // public void add(RegularTimePeriod period, double value); // public void add(RegularTimePeriod period, double value, boolean notify); // public void add(RegularTimePeriod period, Number value); // public void add(RegularTimePeriod period, Number value, boolean notify); // public void update(RegularTimePeriod period, Number value); // public void update(int index, Number value); // public TimeSeries addAndOrUpdate(TimeSeries series); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // double value); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // Number value); // public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); // public void removeAgedItems(boolean notify); // public void removeAgedItems(long latest, boolean notify); // public void clear(); // public void delete(RegularTimePeriod period); // public void delete(int start, int end); // public void delete(int start, int end, boolean notify); // public Object clone() throws CloneNotSupportedException; // public TimeSeries createCopy(int start, int end) // throws CloneNotSupportedException; // public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) // throws CloneNotSupportedException; // public boolean equals(Object obj); // public int hashCode(); // private void updateBoundsForAddedItem(TimeSeriesDataItem item); // private void updateBoundsForRemovedItem(TimeSeriesDataItem item); // private void findBoundsByIteration(); // private double minIgnoreNaN(double a, double b); // private double maxIgnoreNaN(double a, double b); // } // // // Abstract Java Test Class // package org.jfree.data.time.junit; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.event.SeriesChangeListener; // import org.jfree.data.general.SeriesException; // import org.jfree.data.time.Day; // import org.jfree.data.time.FixedMillisecond; // import org.jfree.data.time.Month; // import org.jfree.data.time.MonthConstants; // import org.jfree.data.time.RegularTimePeriod; // import org.jfree.data.time.TimeSeries; // import org.jfree.data.time.TimeSeriesDataItem; // import org.jfree.data.time.Year; // // // // public class TimeSeriesTests extends TestCase implements SeriesChangeListener { // private TimeSeries seriesA; // private TimeSeries seriesB; // private TimeSeries seriesC; // private boolean gotSeriesChangeEvent = false; // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public TimeSeriesTests(String name); // protected void setUp(); // public void seriesChanged(SeriesChangeEvent event); // public void testClone(); // public void testClone2(); // public void testAddValue(); // public void testGetValue(); // public void testDelete(); // public void testDelete2(); // public void testDelete3(); // public void testDelete_RegularTimePeriod(); // public void testSerialization(); // public void testEquals(); // public void testEquals2(); // public void testCreateCopy1(); // public void testCreateCopy2(); // public void testCreateCopy3() throws CloneNotSupportedException; // public void testSetMaximumItemCount(); // public void testAddOrUpdate(); // public void testAddOrUpdate2(); // public void testAddOrUpdate3(); // public void testAddOrUpdate4(); // public void testBug1075255(); // public void testBug1832432(); // public void testGetIndex(); // public void testGetDataItem1(); // public void testGetDataItem2(); // public void testRemoveAgedItems(); // public void testRemoveAgedItems2(); // public void testRemoveAgedItems3(); // public void testRemoveAgedItems4(); // public void testRemoveAgedItems5(); // public void testHashCode(); // public void testBug1864222(); // public void testGetMinY(); // public void testGetMaxY(); // public void testClear(); // public void testAdd(); // public void testUpdate_RegularTimePeriod(); // public void testAdd_TimeSeriesDataItem(); // } // You are a professional Java test case writer, please create a test case named `testSetMaximumItemCount` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */
tests/org/jfree/data/time/junit/TimeSeriesTests.java
package org.jfree.data.time; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimeZone; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.general.Series; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.general.SeriesException;
public TimeSeries(Comparable name); public TimeSeries(Comparable name, String domain, String range); public String getDomainDescription(); public void setDomainDescription(String description); public String getRangeDescription(); public void setRangeDescription(String description); public int getItemCount(); public List getItems(); public int getMaximumItemCount(); public void setMaximumItemCount(int maximum); public long getMaximumItemAge(); public void setMaximumItemAge(long periods); public double getMinY(); public double getMaxY(); public Class getTimePeriodClass(); public TimeSeriesDataItem getDataItem(int index); public TimeSeriesDataItem getDataItem(RegularTimePeriod period); TimeSeriesDataItem getRawDataItem(int index); TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); public RegularTimePeriod getTimePeriod(int index); public RegularTimePeriod getNextTimePeriod(); public Collection getTimePeriods(); public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); public int getIndex(RegularTimePeriod period); public Number getValue(int index); public Number getValue(RegularTimePeriod period); public void add(TimeSeriesDataItem item); public void add(TimeSeriesDataItem item, boolean notify); public void add(RegularTimePeriod period, double value); public void add(RegularTimePeriod period, double value, boolean notify); public void add(RegularTimePeriod period, Number value); public void add(RegularTimePeriod period, Number value, boolean notify); public void update(RegularTimePeriod period, Number value); public void update(int index, Number value); public TimeSeries addAndOrUpdate(TimeSeries series); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, double value); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value); public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); public void removeAgedItems(boolean notify); public void removeAgedItems(long latest, boolean notify); public void clear(); public void delete(RegularTimePeriod period); public void delete(int start, int end); public void delete(int start, int end, boolean notify); public Object clone() throws CloneNotSupportedException; public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException; public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); private void updateBoundsForAddedItem(TimeSeriesDataItem item); private void updateBoundsForRemovedItem(TimeSeriesDataItem item); private void findBoundsByIteration(); private double minIgnoreNaN(double a, double b); private double maxIgnoreNaN(double a, double b);
632
testSetMaximumItemCount
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimeZone; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.general.Series; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.general.SeriesException; public class TimeSeries extends Series implements Cloneable, Serializable { private static final long serialVersionUID = -5032960206869675528L; protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; private String domain; private String range; protected Class timePeriodClass; protected List data; private int maximumItemCount; private long maximumItemAge; private double minY; private double maxY; public TimeSeries(Comparable name); public TimeSeries(Comparable name, String domain, String range); public String getDomainDescription(); public void setDomainDescription(String description); public String getRangeDescription(); public void setRangeDescription(String description); public int getItemCount(); public List getItems(); public int getMaximumItemCount(); public void setMaximumItemCount(int maximum); public long getMaximumItemAge(); public void setMaximumItemAge(long periods); public double getMinY(); public double getMaxY(); public Class getTimePeriodClass(); public TimeSeriesDataItem getDataItem(int index); public TimeSeriesDataItem getDataItem(RegularTimePeriod period); TimeSeriesDataItem getRawDataItem(int index); TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); public RegularTimePeriod getTimePeriod(int index); public RegularTimePeriod getNextTimePeriod(); public Collection getTimePeriods(); public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); public int getIndex(RegularTimePeriod period); public Number getValue(int index); public Number getValue(RegularTimePeriod period); public void add(TimeSeriesDataItem item); public void add(TimeSeriesDataItem item, boolean notify); public void add(RegularTimePeriod period, double value); public void add(RegularTimePeriod period, double value, boolean notify); public void add(RegularTimePeriod period, Number value); public void add(RegularTimePeriod period, Number value, boolean notify); public void update(RegularTimePeriod period, Number value); public void update(int index, Number value); public TimeSeries addAndOrUpdate(TimeSeries series); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, double value); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value); public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); public void removeAgedItems(boolean notify); public void removeAgedItems(long latest, boolean notify); public void clear(); public void delete(RegularTimePeriod period); public void delete(int start, int end); public void delete(int start, int end, boolean notify); public Object clone() throws CloneNotSupportedException; public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException; public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); private void updateBoundsForAddedItem(TimeSeriesDataItem item); private void updateBoundsForRemovedItem(TimeSeriesDataItem item); private void findBoundsByIteration(); private double minIgnoreNaN(double a, double b); private double maxIgnoreNaN(double a, double b); } // Abstract Java Test Class package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; public class TimeSeriesTests extends TestCase implements SeriesChangeListener { private TimeSeries seriesA; private TimeSeries seriesB; private TimeSeries seriesC; private boolean gotSeriesChangeEvent = false; private static final double EPSILON = 0.0000000001; public static Test suite(); public TimeSeriesTests(String name); protected void setUp(); public void seriesChanged(SeriesChangeEvent event); public void testClone(); public void testClone2(); public void testAddValue(); public void testGetValue(); public void testDelete(); public void testDelete2(); public void testDelete3(); public void testDelete_RegularTimePeriod(); public void testSerialization(); public void testEquals(); public void testEquals2(); public void testCreateCopy1(); public void testCreateCopy2(); public void testCreateCopy3() throws CloneNotSupportedException; public void testSetMaximumItemCount(); public void testAddOrUpdate(); public void testAddOrUpdate2(); public void testAddOrUpdate3(); public void testAddOrUpdate4(); public void testBug1075255(); public void testBug1832432(); public void testGetIndex(); public void testGetDataItem1(); public void testGetDataItem2(); public void testRemoveAgedItems(); public void testRemoveAgedItems2(); public void testRemoveAgedItems3(); public void testRemoveAgedItems4(); public void testRemoveAgedItems5(); public void testHashCode(); public void testBug1864222(); public void testGetMinY(); public void testGetMaxY(); public void testClear(); public void testAdd(); public void testUpdate_RegularTimePeriod(); public void testAdd_TimeSeriesDataItem(); } ``` You are a professional Java test case writer, please create a test case named `testSetMaximumItemCount` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */
617
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.lang.reflect.InvocationTargetException; // import java.lang.reflect.Method; // import java.util.Collection; // import java.util.Collections; // import java.util.Date; // import java.util.Iterator; // import java.util.List; // import java.util.TimeZone; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.data.general.Series; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.general.SeriesException; // // // // public class TimeSeries extends Series implements Cloneable, Serializable { // private static final long serialVersionUID = -5032960206869675528L; // protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; // protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; // private String domain; // private String range; // protected Class timePeriodClass; // protected List data; // private int maximumItemCount; // private long maximumItemAge; // private double minY; // private double maxY; // // public TimeSeries(Comparable name); // public TimeSeries(Comparable name, String domain, String range); // public String getDomainDescription(); // public void setDomainDescription(String description); // public String getRangeDescription(); // public void setRangeDescription(String description); // public int getItemCount(); // public List getItems(); // public int getMaximumItemCount(); // public void setMaximumItemCount(int maximum); // public long getMaximumItemAge(); // public void setMaximumItemAge(long periods); // public double getMinY(); // public double getMaxY(); // public Class getTimePeriodClass(); // public TimeSeriesDataItem getDataItem(int index); // public TimeSeriesDataItem getDataItem(RegularTimePeriod period); // TimeSeriesDataItem getRawDataItem(int index); // TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); // public RegularTimePeriod getTimePeriod(int index); // public RegularTimePeriod getNextTimePeriod(); // public Collection getTimePeriods(); // public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); // public int getIndex(RegularTimePeriod period); // public Number getValue(int index); // public Number getValue(RegularTimePeriod period); // public void add(TimeSeriesDataItem item); // public void add(TimeSeriesDataItem item, boolean notify); // public void add(RegularTimePeriod period, double value); // public void add(RegularTimePeriod period, double value, boolean notify); // public void add(RegularTimePeriod period, Number value); // public void add(RegularTimePeriod period, Number value, boolean notify); // public void update(RegularTimePeriod period, Number value); // public void update(int index, Number value); // public TimeSeries addAndOrUpdate(TimeSeries series); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // double value); // public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, // Number value); // public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); // public void removeAgedItems(boolean notify); // public void removeAgedItems(long latest, boolean notify); // public void clear(); // public void delete(RegularTimePeriod period); // public void delete(int start, int end); // public void delete(int start, int end, boolean notify); // public Object clone() throws CloneNotSupportedException; // public TimeSeries createCopy(int start, int end) // throws CloneNotSupportedException; // public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) // throws CloneNotSupportedException; // public boolean equals(Object obj); // public int hashCode(); // private void updateBoundsForAddedItem(TimeSeriesDataItem item); // private void updateBoundsForRemovedItem(TimeSeriesDataItem item); // private void findBoundsByIteration(); // private double minIgnoreNaN(double a, double b); // private double maxIgnoreNaN(double a, double b); // } // // // Abstract Java Test Class // package org.jfree.data.time.junit; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.event.SeriesChangeEvent; // import org.jfree.data.event.SeriesChangeListener; // import org.jfree.data.general.SeriesException; // import org.jfree.data.time.Day; // import org.jfree.data.time.FixedMillisecond; // import org.jfree.data.time.Month; // import org.jfree.data.time.MonthConstants; // import org.jfree.data.time.RegularTimePeriod; // import org.jfree.data.time.TimeSeries; // import org.jfree.data.time.TimeSeriesDataItem; // import org.jfree.data.time.Year; // // // // public class TimeSeriesTests extends TestCase implements SeriesChangeListener { // private TimeSeries seriesA; // private TimeSeries seriesB; // private TimeSeries seriesC; // private boolean gotSeriesChangeEvent = false; // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public TimeSeriesTests(String name); // protected void setUp(); // public void seriesChanged(SeriesChangeEvent event); // public void testClone(); // public void testClone2(); // public void testAddValue(); // public void testGetValue(); // public void testDelete(); // public void testDelete2(); // public void testDelete3(); // public void testDelete_RegularTimePeriod(); // public void testSerialization(); // public void testEquals(); // public void testEquals2(); // public void testCreateCopy1(); // public void testCreateCopy2(); // public void testCreateCopy3() throws CloneNotSupportedException; // public void testSetMaximumItemCount(); // public void testAddOrUpdate(); // public void testAddOrUpdate2(); // public void testAddOrUpdate3(); // public void testAddOrUpdate4(); // public void testBug1075255(); // public void testBug1832432(); // public void testGetIndex(); // public void testGetDataItem1(); // public void testGetDataItem2(); // public void testRemoveAgedItems(); // public void testRemoveAgedItems2(); // public void testRemoveAgedItems3(); // public void testRemoveAgedItems4(); // public void testRemoveAgedItems5(); // public void testHashCode(); // public void testBug1864222(); // public void testGetMinY(); // public void testGetMaxY(); // public void testClear(); // public void testAdd(); // public void testUpdate_RegularTimePeriod(); // public void testAdd_TimeSeriesDataItem(); // } // You are a professional Java test case writer, please create a test case named `testSetMaximumItemCount` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() {
/** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */
1
org.jfree.data.time.TimeSeries
tests
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimeZone; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.general.Series; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.general.SeriesException; public class TimeSeries extends Series implements Cloneable, Serializable { private static final long serialVersionUID = -5032960206869675528L; protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; private String domain; private String range; protected Class timePeriodClass; protected List data; private int maximumItemCount; private long maximumItemAge; private double minY; private double maxY; public TimeSeries(Comparable name); public TimeSeries(Comparable name, String domain, String range); public String getDomainDescription(); public void setDomainDescription(String description); public String getRangeDescription(); public void setRangeDescription(String description); public int getItemCount(); public List getItems(); public int getMaximumItemCount(); public void setMaximumItemCount(int maximum); public long getMaximumItemAge(); public void setMaximumItemAge(long periods); public double getMinY(); public double getMaxY(); public Class getTimePeriodClass(); public TimeSeriesDataItem getDataItem(int index); public TimeSeriesDataItem getDataItem(RegularTimePeriod period); TimeSeriesDataItem getRawDataItem(int index); TimeSeriesDataItem getRawDataItem(RegularTimePeriod period); public RegularTimePeriod getTimePeriod(int index); public RegularTimePeriod getNextTimePeriod(); public Collection getTimePeriods(); public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series); public int getIndex(RegularTimePeriod period); public Number getValue(int index); public Number getValue(RegularTimePeriod period); public void add(TimeSeriesDataItem item); public void add(TimeSeriesDataItem item, boolean notify); public void add(RegularTimePeriod period, double value); public void add(RegularTimePeriod period, double value, boolean notify); public void add(RegularTimePeriod period, Number value); public void add(RegularTimePeriod period, Number value, boolean notify); public void update(RegularTimePeriod period, Number value); public void update(int index, Number value); public TimeSeries addAndOrUpdate(TimeSeries series); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, double value); public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value); public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item); public void removeAgedItems(boolean notify); public void removeAgedItems(long latest, boolean notify); public void clear(); public void delete(RegularTimePeriod period); public void delete(int start, int end); public void delete(int start, int end, boolean notify); public Object clone() throws CloneNotSupportedException; public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException; public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); private void updateBoundsForAddedItem(TimeSeriesDataItem item); private void updateBoundsForRemovedItem(TimeSeriesDataItem item); private void findBoundsByIteration(); private double minIgnoreNaN(double a, double b); private double maxIgnoreNaN(double a, double b); } // Abstract Java Test Class package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; public class TimeSeriesTests extends TestCase implements SeriesChangeListener { private TimeSeries seriesA; private TimeSeries seriesB; private TimeSeries seriesC; private boolean gotSeriesChangeEvent = false; private static final double EPSILON = 0.0000000001; public static Test suite(); public TimeSeriesTests(String name); protected void setUp(); public void seriesChanged(SeriesChangeEvent event); public void testClone(); public void testClone2(); public void testAddValue(); public void testGetValue(); public void testDelete(); public void testDelete2(); public void testDelete3(); public void testDelete_RegularTimePeriod(); public void testSerialization(); public void testEquals(); public void testEquals2(); public void testCreateCopy1(); public void testCreateCopy2(); public void testCreateCopy3() throws CloneNotSupportedException; public void testSetMaximumItemCount(); public void testAddOrUpdate(); public void testAddOrUpdate2(); public void testAddOrUpdate3(); public void testAddOrUpdate4(); public void testBug1075255(); public void testBug1832432(); public void testGetIndex(); public void testGetDataItem1(); public void testGetDataItem2(); public void testRemoveAgedItems(); public void testRemoveAgedItems2(); public void testRemoveAgedItems3(); public void testRemoveAgedItems4(); public void testRemoveAgedItems5(); public void testHashCode(); public void testBug1864222(); public void testGetMinY(); public void testGetMaxY(); public void testClear(); public void testAdd(); public void testUpdate_RegularTimePeriod(); public void testAdd_TimeSeriesDataItem(); } ``` You are a professional Java test case writer, please create a test case named `testSetMaximumItemCount` for the `TimeSeries` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { ```
public class TimeSeries extends Series implements Cloneable, Serializable
package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year;
public static Test suite(); public TimeSeriesTests(String name); protected void setUp(); public void seriesChanged(SeriesChangeEvent event); public void testClone(); public void testClone2(); public void testAddValue(); public void testGetValue(); public void testDelete(); public void testDelete2(); public void testDelete3(); public void testDelete_RegularTimePeriod(); public void testSerialization(); public void testEquals(); public void testEquals2(); public void testCreateCopy1(); public void testCreateCopy2(); public void testCreateCopy3() throws CloneNotSupportedException; public void testSetMaximumItemCount(); public void testAddOrUpdate(); public void testAddOrUpdate2(); public void testAddOrUpdate3(); public void testAddOrUpdate4(); public void testBug1075255(); public void testBug1832432(); public void testGetIndex(); public void testGetDataItem1(); public void testGetDataItem2(); public void testRemoveAgedItems(); public void testRemoveAgedItems2(); public void testRemoveAgedItems3(); public void testRemoveAgedItems4(); public void testRemoveAgedItems5(); public void testHashCode(); public void testBug1864222(); public void testGetMinY(); public void testGetMaxY(); public void testClear(); public void testAdd(); public void testUpdate_RegularTimePeriod(); public void testAdd_TimeSeriesDataItem();
e7d7f4e4ceecd55b636791a6ba0e456aaddc3f59e5657095bb7beb094d090c94
[ "org.jfree.data.time.junit.TimeSeriesTests::testSetMaximumItemCount" ]
private static final long serialVersionUID = -5032960206869675528L; protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time"; protected static final String DEFAULT_RANGE_DESCRIPTION = "Value"; private String domain; private String range; protected Class timePeriodClass; protected List data; private int maximumItemCount; private long maximumItemAge; private double minY; private double maxY;
public void testSetMaximumItemCount()
private TimeSeries seriesA; private TimeSeries seriesB; private TimeSeries seriesC; private boolean gotSeriesChangeEvent = false; private static final double EPSILON = 0.0000000001;
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2009, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TimeSeriesTests.java * -------------------- * (C) Copyright 2001-2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2001 : Version 1 (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 15-Oct-2003 : Added test for setMaximumItemCount method (DG); * 23-Aug-2004 : Added test that highlights a bug where the addOrUpdate() * method can lead to more than maximumItemCount items in the * dataset (DG); * 24-May-2006 : Added new tests (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 31-Oct-2007 : New hashCode() test (DG); * 21-Nov-2007 : Added testBug1832432() and testClone2() (DG); * 10-Jan-2008 : Added testBug1864222() (DG); * 13-Jan-2009 : Added testEquals3() and testRemoveAgedItems3() (DG); * 26-May-2009 : Added various tests for min/maxY values (DG); * 09-Jun-2009 : Added testAdd_TimeSeriesDataItem (DG); * 31-Aug-2009 : Added new test for createCopy() method (DG); * */ package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.event.SeriesChangeEvent; import org.jfree.data.event.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; /** * A collection of test cases for the {@link TimeSeries} class. */ public class TimeSeriesTests extends TestCase implements SeriesChangeListener { /** A time series. */ private TimeSeries seriesA; /** A time series. */ private TimeSeries seriesB; /** A time series. */ private TimeSeries seriesC; /** A flag that indicates whether or not a change event was fired. */ private boolean gotSeriesChangeEvent = false; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.seriesA = new TimeSeries("Series A"); try { this.seriesA.add(new Year(2000), new Integer(102000)); this.seriesA.add(new Year(2001), new Integer(102001)); this.seriesA.add(new Year(2002), new Integer(102002)); this.seriesA.add(new Year(2003), new Integer(102003)); this.seriesA.add(new Year(2004), new Integer(102004)); this.seriesA.add(new Year(2005), new Integer(102005)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesB = new TimeSeries("Series B"); try { this.seriesB.add(new Year(2006), new Integer(202006)); this.seriesB.add(new Year(2007), new Integer(202007)); this.seriesB.add(new Year(2008), new Integer(202008)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesC = new TimeSeries("Series C"); try { this.seriesC.add(new Year(1999), new Integer(301999)); this.seriesC.add(new Year(2000), new Integer(302000)); this.seriesC.add(new Year(2002), new Integer(302002)); } catch (SeriesException e) { System.err.println("Problem creating series."); } } /** * Sets the flag to indicate that a {@link SeriesChangeEvent} has been * received. * * @param event the event. */ public void seriesChanged(SeriesChangeEvent event) { this.gotSeriesChangeEvent = true; } /** * Check that cloning works. */ public void testClone() { TimeSeries series = new TimeSeries("Test Series"); RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002); try { series.add(jan1st2002, new Integer(42)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } TimeSeries clone = null; try { clone = (TimeSeries) series.clone(); clone.setKey("Clone Series"); try { clone.update(jan1st2002, new Integer(10)); } catch (SeriesException e) { e.printStackTrace(); } } catch (CloneNotSupportedException e) { assertTrue(false); } int seriesValue = series.getValue(jan1st2002).intValue(); int cloneValue = Integer.MAX_VALUE; if (clone != null) { cloneValue = clone.getValue(jan1st2002).intValue(); } assertEquals(42, seriesValue); assertEquals(10, cloneValue); assertEquals("Test Series", series.getKey()); if (clone != null) { assertEquals("Clone Series", clone.getKey()); } else { assertTrue(false); } } /** * Another test of the clone() method. */ public void testClone2() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2007), 100.0); s1.add(new Year(2008), null); s1.add(new Year(2009), 200.0); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.addOrUpdate(new Year(2009), 300.0); assertFalse(s1.equals(s2)); s1.addOrUpdate(new Year(2009), 300.0); assertTrue(s1.equals(s2)); } /** * Add a value to series A for 1999. It should be added at index 0. */ public void testAddValue() { try { this.seriesA.add(new Year(1999), new Integer(1)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } int value = this.seriesA.getValue(0).intValue(); assertEquals(1, value); } /** * Tests the retrieval of values. */ public void testGetValue() { Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } /** * Tests the deletion of values. */ public void testDelete() { this.seriesA.delete(0, 0); assertEquals(5, this.seriesA.getItemCount()); Number value = this.seriesA.getValue(new Year(2000)); assertNull(value); } /** * Basic tests for the delete() method. */ public void testDelete2() { TimeSeries s1 = new TimeSeries("Series"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } /** * Some checks for the delete(int, int) method. */ public void testDelete3() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2011), 1.1); s1.add(new Year(2012), 2.2); s1.add(new Year(2013), 3.3); s1.add(new Year(2014), 4.4); s1.add(new Year(2015), 5.5); s1.add(new Year(2016), 6.6); s1.delete(2, 5); assertEquals(2, s1.getItemCount()); assertEquals(new Year(2011), s1.getTimePeriod(0)); assertEquals(new Year(2012), s1.getTimePeriod(1)); assertEquals(1.1, s1.getMinY(), EPSILON); assertEquals(2.2, s1.getMaxY(), EPSILON); } /** * Check that the item bounds are determined correctly when there is a * maximum item count and a new value is added. */ public void testDelete_RegularTimePeriod() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.add(new Year(2013), 4.4); s1.delete(new Year(2010)); s1.delete(new Year(2013)); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); } /** * Tests the equals method. */ public void testEquals() { TimeSeries s1 = new TimeSeries("Time Series 1"); TimeSeries s2 = new TimeSeries("Time Series 2"); boolean b1 = s1.equals(s2); assertFalse("b1", b1); s2.setKey("Time Series 1"); boolean b2 = s1.equals(s2); assertTrue("b2", b2); RegularTimePeriod p1 = new Day(); RegularTimePeriod p2 = p1.next(); s1.add(p1, 100.0); s1.add(p2, 200.0); boolean b3 = s1.equals(s2); assertFalse("b3", b3); s2.add(p1, 100.0); s2.add(p2, 200.0); boolean b4 = s1.equals(s2); assertTrue("b4", b4); s1.setMaximumItemCount(100); boolean b5 = s1.equals(s2); assertFalse("b5", b5); s2.setMaximumItemCount(100); boolean b6 = s1.equals(s2); assertTrue("b6", b6); s1.setMaximumItemAge(100); boolean b7 = s1.equals(s2); assertFalse("b7", b7); s2.setMaximumItemAge(100); boolean b8 = s1.equals(s2); assertTrue("b8", b8); } /** * Tests a specific bug report where null arguments in the constructor * cause the equals() method to fail. Fixed for 0.9.21. */ public void testEquals2() { TimeSeries s1 = new TimeSeries("Series", null, null); TimeSeries s2 = new TimeSeries("Series", null, null); assertTrue(s1.equals(s2)); } /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series"); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Some tests to ensure that the createCopy(int, int) method is * functioning correctly. */ public void testCreateCopy2() { TimeSeries series = new TimeSeries("Series"); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy just the first item... TimeSeries result1 = series.createCopy(0, 0); assertEquals(new Month(1, 2003), result1.getTimePeriod(0)); // copy the first two items... result1 = series.createCopy(0, 1); assertEquals(new Month(2, 2003), result1.getTimePeriod(1)); // copy the middle three items... result1 = series.createCopy(1, 3); assertEquals(new Month(2, 2003), result1.getTimePeriod(0)); assertEquals(new Month(11, 2003), result1.getTimePeriod(2)); // copy the last two items... result1 = series.createCopy(3, 4); assertEquals(new Month(11, 2003), result1.getTimePeriod(0)); assertEquals(new Month(12, 2003), result1.getTimePeriod(1)); // copy the last item... result1 = series.createCopy(4, 4); assertEquals(new Month(12, 2003), result1.getTimePeriod(0)); } catch (CloneNotSupportedException e) { assertTrue(false); } // check negative first argument boolean pass = false; try { /* TimeSeries result = */ series.createCopy(-1, 1); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); // check second argument less than first argument pass = false; try { /* TimeSeries result = */ series.createCopy(1, 0); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); TimeSeries series2 = new TimeSeries("Series 2"); try { TimeSeries series3 = series2.createCopy(99, 999); assertEquals(0, series3.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Checks that the min and max y values are updated correctly when copying * a subset. * * @throws java.lang.CloneNotSupportedException */ public void testCreateCopy3() throws CloneNotSupportedException { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2009), 100.0); s1.add(new Year(2010), 101.0); s1.add(new Year(2011), 102.0); assertEquals(100.0, s1.getMinY(), EPSILON); assertEquals(102.0, s1.getMaxY(), EPSILON); TimeSeries s2 = s1.createCopy(0, 1); assertEquals(100.0, s2.getMinY(), EPSILON); assertEquals(101.0, s2.getMaxY(), EPSILON); TimeSeries s3 = s1.createCopy(1, 2); assertEquals(101.0, s3.getMinY(), EPSILON); assertEquals(102.0, s3.getMaxY(), EPSILON); } /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); assertEquals(16.89, s1.getMinY(), EPSILON); assertEquals(19.32, s1.getMaxY(), EPSILON); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2000), 100.0); assertEquals(1, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 101.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 102.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2002), 103.0); assertEquals(2, s1.getItemCount()); } /** * Test the add branch of the addOrUpdate() method. */ public void testAddOrUpdate2() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2010), 1.1); s1.addOrUpdate(new Year(2011), 2.2); s1.addOrUpdate(new Year(2012), 3.3); assertEquals(2, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Test that the addOrUpdate() method won't allow multiple time period * classes. */ public void testAddOrUpdate3() { TimeSeries s1 = new TimeSeries("S1"); s1.addOrUpdate(new Year(2010), 1.1); assertEquals(Year.class, s1.getTimePeriodClass()); boolean pass = false; try { s1.addOrUpdate(new Month(1, 2009), 0.0); } catch (SeriesException e) { pass = true; } assertTrue(pass); } /** * Some more checks for the addOrUpdate() method. */ public void testAddOrUpdate4() { TimeSeries ts = new TimeSeries("S"); TimeSeriesDataItem overwritten = ts.addOrUpdate(new Year(2009), 20.09); assertNull(overwritten); overwritten = ts.addOrUpdate(new Year(2009), 1.0); assertEquals(new Double(20.09), overwritten.getValue()); assertEquals(new Double(1.0), ts.getValue(new Year(2009))); // changing the overwritten record shouldn't affect the series overwritten.setValue(null); assertEquals(new Double(1.0), ts.getValue(new Year(2009))); TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2010), 20.10); overwritten = ts.addOrUpdate(item); assertNull(overwritten); assertEquals(new Double(20.10), ts.getValue(new Year(2010))); // changing the item that was added should not change the series item.setValue(null); assertEquals(new Double(20.10), ts.getValue(new Year(2010))); } /** * A test for the bug report 1075255. */ public void testBug1075255() { TimeSeries ts = new TimeSeries("dummy"); ts.add(new FixedMillisecond(0L), 0.0); TimeSeries ts2 = new TimeSeries("dummy2"); ts2.add(new FixedMillisecond(0L), 1.0); try { ts.addAndOrUpdate(ts2); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } assertEquals(1, ts.getItemCount()); } /** * A test for bug 1832432. */ public void testBug1832432() { TimeSeries s1 = new TimeSeries("Series"); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); // test independence s1.add(new Day(1, 1, 2007), 100.0); assertFalse(s1.equals(s2)); } /** * Some checks for the getIndex() method. */ public void testGetIndex() { TimeSeries series = new TimeSeries("Series"); assertEquals(-1, series.getIndex(new Month(1, 2003))); series.add(new Month(1, 2003), 45.0); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(-2, series.getIndex(new Month(2, 2003))); series.add(new Month(3, 2003), 55.0); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-2, series.getIndex(new Month(2, 2003))); assertEquals(1, series.getIndex(new Month(3, 2003))); assertEquals(-3, series.getIndex(new Month(4, 2003))); } /** * Some checks for the getDataItem(int) method. */ public void testGetDataItem1() { TimeSeries series = new TimeSeries("S"); // can't get anything yet...just an exception boolean pass = false; try { /*TimeSeriesDataItem item =*/ series.getDataItem(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); series.add(new Year(2006), 100.0); TimeSeriesDataItem item = series.getDataItem(0); assertEquals(new Year(2006), item.getPeriod()); pass = false; try { /*item = */series.getDataItem(-1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); pass = false; try { /*item = */series.getDataItem(1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getDataItem(RegularTimePeriod) method. */ public void testGetDataItem2() { TimeSeries series = new TimeSeries("S"); assertNull(series.getDataItem(new Year(2006))); // try a null argument boolean pass = false; try { /* TimeSeriesDataItem item = */ series.getDataItem(null); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the removeAgedItems() method. */ public void testRemoveAgedItems() { TimeSeries series = new TimeSeries("Test Series"); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with one item series.add(new Year(1999), 1.0); series.setMaximumItemAge(0); this.gotSeriesChangeEvent = false; series.removeAgedItems(true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with two items series.setMaximumItemAge(10); series.add(new Year(2001), 2.0); this.gotSeriesChangeEvent = false; series.setMaximumItemAge(2); assertEquals(2, series.getItemCount()); assertEquals(0, series.getIndex(new Year(1999))); assertFalse(this.gotSeriesChangeEvent); series.setMaximumItemAge(1); assertEquals(1, series.getItemCount()); assertEquals(0, series.getIndex(new Year(2001))); assertTrue(this.gotSeriesChangeEvent); } /** * Some checks for the removeAgedItems(long, boolean) method. */ public void testRemoveAgedItems2() { long y2006 = 1157087372534L; // milliseconds somewhere in 2006 TimeSeries series = new TimeSeries("Test Series"); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test a series with 1 item series.add(new Year(2004), 1.0); series.setMaximumItemAge(1); this.gotSeriesChangeEvent = false; series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); // test a series with two items series.setMaximumItemAge(2); series.add(new Year(2003), 1.0); series.add(new Year(2005), 2.0); assertEquals(2, series.getItemCount()); this.gotSeriesChangeEvent = false; assertEquals(2, series.getItemCount()); series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(2, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(1, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); } /** * Calling removeAgedItems() on an empty series should not throw any * exception. */ public void testRemoveAgedItems3() { TimeSeries s = new TimeSeries("Test"); boolean pass = true; try { s.removeAgedItems(0L, true); } catch (Exception e) { pass = false; } assertTrue(pass); } /** * Check that the item bounds are determined correctly when there is a * maximum item count. */ public void testRemoveAgedItems4() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemAge(2); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.add(new Year(2013), 2.5); assertEquals(3, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Check that the item bounds are determined correctly after a call to * removeAgedItems(). */ public void testRemoveAgedItems5() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemAge(4); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.add(new Year(2013), 2.5); s1.removeAgedItems(new Year(2015).getMiddleMillisecond(), true); assertEquals(3, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { TimeSeries s1 = new TimeSeries("Test"); TimeSeries s2 = new TimeSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(1, 1, 2007), 500.0); s2.add(new Day(1, 1, 2007), 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(2, 1, 2007), null); s2.add(new Day(2, 1, 2007), null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(5, 1, 2007), 111.0); s2.add(new Day(5, 1, 2007), 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(9, 1, 2007), 1.0); s2.add(new Day(9, 1, 2007), 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } /** * Test for bug report 1864222. */ public void testBug1864222() { TimeSeries s = new TimeSeries("S"); s.add(new Day(19, 8, 2005), 1); s.add(new Day(31, 1, 2006), 1); boolean pass = true; try { s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006)); } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); } private static final double EPSILON = 0.0000000001; /** * Some checks for the getMinY() method. */ public void testGetMinY() { TimeSeries s1 = new TimeSeries("S1"); assertTrue(Double.isNaN(s1.getMinY())); s1.add(new Year(2008), 1.1); assertEquals(1.1, s1.getMinY(), EPSILON); s1.add(new Year(2009), 2.2); assertEquals(1.1, s1.getMinY(), EPSILON); s1.add(new Year(2000), 99.9); assertEquals(1.1, s1.getMinY(), EPSILON); s1.add(new Year(2002), -1.1); assertEquals(-1.1, s1.getMinY(), EPSILON); s1.add(new Year(2003), null); assertEquals(-1.1, s1.getMinY(), EPSILON); s1.addOrUpdate(new Year(2002), null); assertEquals(1.1, s1.getMinY(), EPSILON); } /** * Some checks for the getMaxY() method. */ public void testGetMaxY() { TimeSeries s1 = new TimeSeries("S1"); assertTrue(Double.isNaN(s1.getMaxY())); s1.add(new Year(2008), 1.1); assertEquals(1.1, s1.getMaxY(), EPSILON); s1.add(new Year(2009), 2.2); assertEquals(2.2, s1.getMaxY(), EPSILON); s1.add(new Year(2000), 99.9); assertEquals(99.9, s1.getMaxY(), EPSILON); s1.add(new Year(2002), -1.1); assertEquals(99.9, s1.getMaxY(), EPSILON); s1.add(new Year(2003), null); assertEquals(99.9, s1.getMaxY(), EPSILON); s1.addOrUpdate(new Year(2000), null); assertEquals(2.2, s1.getMaxY(), EPSILON); } /** * A test for the clear method. */ public void testClear() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2009), 1.1); s1.add(new Year(2010), 2.2); assertEquals(2, s1.getItemCount()); s1.clear(); assertEquals(0, s1.getItemCount()); assertTrue(Double.isNaN(s1.getMinY())); assertTrue(Double.isNaN(s1.getMaxY())); } /** * Check that the item bounds are determined correctly when there is a * maximum item count and a new value is added. */ public void testAdd() { TimeSeries s1 = new TimeSeries("S1"); s1.setMaximumItemCount(2); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); assertEquals(2, s1.getItemCount()); assertEquals(2.2, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); } /** * Some checks for the update(RegularTimePeriod...method). */ public void testUpdate_RegularTimePeriod() { TimeSeries s1 = new TimeSeries("S1"); s1.add(new Year(2010), 1.1); s1.add(new Year(2011), 2.2); s1.add(new Year(2012), 3.3); s1.update(new Year(2012), new Double(4.4)); assertEquals(4.4, s1.getMaxY(), EPSILON); s1.update(new Year(2010), new Double(0.5)); assertEquals(0.5, s1.getMinY(), EPSILON); s1.update(new Year(2012), null); assertEquals(2.2, s1.getMaxY(), EPSILON); s1.update(new Year(2010), null); assertEquals(2.2, s1.getMinY(), EPSILON); } /** * Create a TimeSeriesDataItem, add it to a TimeSeries. Now, modifying * the original TimeSeriesDataItem should NOT affect the TimeSeries. */ public void testAdd_TimeSeriesDataItem() { TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2009), 1.0); TimeSeries series = new TimeSeries("S1"); series.add(item); assertTrue(item.equals(series.getDataItem(0))); item.setValue(new Double(99.9)); assertFalse(item.equals(series.getDataItem(0))); } }
[ { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;D)V", "line_numbers": [ "653", "654" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;DZ)V", "line_numbers": [ "666", "667", "668" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;Ljava/lang/Number;)V", "line_numbers": [ "680", "681" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/RegularTimePeriod;Ljava/lang/Number;Z)V", "line_numbers": [ "693", "694", "695" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/data/time/TimeSeriesDataItem;Z)V", "line_numbers": [ "576", "577", "579", "580", "581", "582", "584", "585", "586", "587", "588", "589", "590", "591", "592", "596", "597", "598", "599", "600", "603", "604", "605", "606", "609", "610", "611", "612", "615", "616", "617", "618", "619", "620", "621", "622", "626", "627", "629", "630", "631", "634", "637", "638", "642" ], "method_line_rate": 0.4888888888888889 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "delete", "be_test_function_signature": "(II)V", "line_numbers": [ "987", "988" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "delete", "be_test_function_signature": "(IIZ)V", "line_numbers": [ "1000", "1001", "1003", "1004", "1006", "1007", "1008", "1010", "1011", "1013" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "findBoundsByIteration", "be_test_function_signature": "()V", "line_numbers": [ "1248", "1249", "1250", "1251", "1252", "1253", "1254", "1255" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getDataItem", "be_test_function_signature": "(I)Lorg/jfree/data/time/TimeSeriesDataItem;", "line_numbers": [ "389", "390" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getItemCount", "be_test_function_signature": "()I", "line_numbers": [ "254" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getMaxY", "be_test_function_signature": "()D", "line_numbers": [ "360" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getMinY", "be_test_function_signature": "()D", "line_numbers": [ "345" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getRawDataItem", "be_test_function_signature": "(I)Lorg/jfree/data/time/TimeSeriesDataItem;", "line_numbers": [ "429" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "getTimePeriod", "be_test_function_signature": "(I)Lorg/jfree/data/time/RegularTimePeriod;", "line_numbers": [ "463" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "maxIgnoreNaN", "be_test_function_signature": "(DD)D", "line_numbers": [ "1290", "1291", "1294", "1295", "1298" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "minIgnoreNaN", "be_test_function_signature": "(DD)D", "line_numbers": [ "1267", "1268", "1271", "1272", "1275" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "removeAgedItems", "be_test_function_signature": "(Z)V", "line_numbers": [ "877", "878", "879", "881", "882", "883", "885", "886", "887", "888", "892" ], "method_line_rate": 0.5454545454545454 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "setMaximumItemCount", "be_test_function_signature": "(I)V", "line_numbers": [ "292", "293", "295", "296", "297", "298", "300" ], "method_line_rate": 0.8571428571428571 }, { "be_test_class_file": "org/jfree/data/time/TimeSeries.java", "be_test_class_name": "org.jfree.data.time.TimeSeries", "be_test_function_name": "updateBoundsForAddedItem", "be_test_function_signature": "(Lorg/jfree/data/time/TimeSeriesDataItem;)V", "line_numbers": [ "1213", "1214", "1215", "1216", "1217", "1219" ], "method_line_rate": 1 } ]
public final class EmpiricalDistributionTest extends RealDistributionAbstractTest
@Test public void testLoad() throws Exception { // Load from a URL empiricalDistribution.load(url); checkDistribution(); // Load again from a file (also verifies idempotency of load) File file = new File(url.toURI()); empiricalDistribution.load(file); checkDistribution(); }
// private EmpiricalDistribution(int binCount, // RandomDataGenerator randomData); // public void load(double[] in) throws NullArgumentException; // public void load(URL url) throws IOException, NullArgumentException, ZeroException; // public void load(File file) throws IOException, NullArgumentException; // private void fillBinStats(final DataAdapter da) // throws IOException; // private int findBin(double value); // public double getNextValue() throws MathIllegalStateException; // public StatisticalSummary getSampleStats(); // public int getBinCount(); // public List<SummaryStatistics> getBinStats(); // public double[] getUpperBounds(); // public double[] getGeneratorUpperBounds(); // public boolean isLoaded(); // public void reSeed(long seed); // @Override // public double probability(double x); // public double density(double x); // public double cumulativeProbability(double x); // @Override // public double inverseCumulativeProbability(final double p) throws OutOfRangeException; // public double getNumericalMean(); // public double getNumericalVariance(); // public double getSupportLowerBound(); // public double getSupportUpperBound(); // public boolean isSupportLowerBoundInclusive(); // public boolean isSupportUpperBoundInclusive(); // public boolean isSupportConnected(); // @Override // public double sample(); // @Override // public void reseedRandomGenerator(long seed); // private double pB(int i); // private double pBminus(int i); // @SuppressWarnings("deprecation") // private double kB(int i); // private RealDistribution k(double x); // private double cumBinP(int binIndex); // protected RealDistribution getKernel(SummaryStatistics bStats); // public abstract void computeBinStats() throws IOException; // public abstract void computeStats() throws IOException; // public StreamDataAdapter(BufferedReader in); // @Override // public void computeBinStats() throws IOException; // @Override // public void computeStats() throws IOException; // public ArrayDataAdapter(double[] in) throws NullArgumentException; // @Override // public void computeStats() throws IOException; // @Override // public void computeBinStats() throws IOException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.random; // // import java.io.BufferedReader; // import java.io.File; // import java.io.IOException; // import java.io.InputStreamReader; // import java.net.URL; // import java.util.ArrayList; // import java.util.Arrays; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.integration.BaseAbstractUnivariateIntegrator; // import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator; // import org.apache.commons.math3.distribution.AbstractRealDistribution; // import org.apache.commons.math3.distribution.NormalDistribution; // import org.apache.commons.math3.distribution.RealDistribution; // import org.apache.commons.math3.distribution.RealDistributionAbstractTest; // import org.apache.commons.math3.distribution.UniformRealDistribution; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.exception.OutOfRangeException; // import org.apache.commons.math3.stat.descriptive.SummaryStatistics; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // // // // public final class EmpiricalDistributionTest extends RealDistributionAbstractTest { // protected EmpiricalDistribution empiricalDistribution = null; // protected EmpiricalDistribution empiricalDistribution2 = null; // protected File file = null; // protected URL url = null; // protected double[] dataArray = null; // protected final int n = 10000; // private final double binMass = 10d / (n + 1); // private final double firstBinMass = 11d / (n + 1); // // @Override // @Before // public void setUp(); // @Test // public void testLoad() throws Exception; // private void checkDistribution(); // @Test // public void testDoubleLoad() throws Exception; // @Test // public void testNext() throws Exception; // @Test // public void testNexFail(); // @Test // public void testGridTooFine() throws Exception; // @Test // public void testGridTooFat() throws Exception; // @Test // public void testBinIndexOverflow() throws Exception; // @Test // public void testSerialization(); // @Test(expected=NullArgumentException.class) // public void testLoadNullDoubleArray(); // @Test(expected=NullArgumentException.class) // public void testLoadNullURL() throws Exception; // @Test(expected=NullArgumentException.class) // public void testLoadNullFile() throws Exception; // @Test // public void testGetBinUpperBounds(); // @Test // public void testGeneratorConfig(); // @Test // public void testReSeed() throws Exception; // private void verifySame(EmpiricalDistribution d1, EmpiricalDistribution d2); // private void tstGen(double tolerance)throws Exception; // private void tstDoubleGen(double tolerance)throws Exception; // @Override // public RealDistribution makeDistribution(); // @Override // public double[] makeCumulativeTestPoints(); // @Override // public double[] makeCumulativeTestValues(); // @Override // public double[] makeDensityTestValues(); // @Override // @Test // public void testDensityIntegrals(); // private int findBin(double x); // private RealDistribution findKernel(double lower, double upper); // @Test // public void testKernelOverrideConstant(); // @Test // public void testKernelOverrideUniform(); // public ConstantKernelEmpiricalDistribution(int i); // @Override // protected RealDistribution getKernel(SummaryStatistics bStats); // public UniformKernelEmpiricalDistribution(int i); // @Override // protected RealDistribution getKernel(SummaryStatistics bStats); // public ConstantDistribution(double c); // public double density(double x); // public double cumulativeProbability(double x); // @Override // public double inverseCumulativeProbability(double p); // public double getNumericalMean(); // public double getNumericalVariance(); // public double getSupportLowerBound(); // public double getSupportUpperBound(); // public boolean isSupportLowerBoundInclusive(); // public boolean isSupportUpperBoundInclusive(); // public boolean isSupportConnected(); // @Override // public double sample(); // public double value(double x); // } // You are a professional Java test case writer, please create a test case named `testLoad` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test EmpiricalDistrbution.load() using sample data file.<br> * Check that the sampleCount, mu and sigma match data in * the sample data file. Also verify that load is idempotent. */
src/test/java/org/apache/commons/math3/random/EmpiricalDistributionTest.java
package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.distribution.AbstractRealDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.MathInternalError; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.stat.descriptive.StatisticalSummary; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils;
public EmpiricalDistribution(); public EmpiricalDistribution(int binCount); public EmpiricalDistribution(int binCount, RandomGenerator generator); public EmpiricalDistribution(RandomGenerator generator); @Deprecated public EmpiricalDistribution(int binCount, RandomDataImpl randomData); @Deprecated public EmpiricalDistribution(RandomDataImpl randomData); private EmpiricalDistribution(int binCount, RandomDataGenerator randomData); public void load(double[] in) throws NullArgumentException; public void load(URL url) throws IOException, NullArgumentException, ZeroException; public void load(File file) throws IOException, NullArgumentException; private void fillBinStats(final DataAdapter da) throws IOException; private int findBin(double value); public double getNextValue() throws MathIllegalStateException; public StatisticalSummary getSampleStats(); public int getBinCount(); public List<SummaryStatistics> getBinStats(); public double[] getUpperBounds(); public double[] getGeneratorUpperBounds(); public boolean isLoaded(); public void reSeed(long seed); @Override public double probability(double x); public double density(double x); public double cumulativeProbability(double x); @Override public double inverseCumulativeProbability(final double p) throws OutOfRangeException; public double getNumericalMean(); public double getNumericalVariance(); public double getSupportLowerBound(); public double getSupportUpperBound(); public boolean isSupportLowerBoundInclusive(); public boolean isSupportUpperBoundInclusive(); public boolean isSupportConnected(); @Override public double sample(); @Override public void reseedRandomGenerator(long seed); private double pB(int i); private double pBminus(int i); @SuppressWarnings("deprecation") private double kB(int i); private RealDistribution k(double x); private double cumBinP(int binIndex); protected RealDistribution getKernel(SummaryStatistics bStats); public abstract void computeBinStats() throws IOException; public abstract void computeStats() throws IOException; public StreamDataAdapter(BufferedReader in); @Override public void computeBinStats() throws IOException; @Override public void computeStats() throws IOException; public ArrayDataAdapter(double[] in) throws NullArgumentException; @Override public void computeStats() throws IOException; @Override public void computeBinStats() throws IOException;
104
testLoad
```java private EmpiricalDistribution(int binCount, RandomDataGenerator randomData); public void load(double[] in) throws NullArgumentException; public void load(URL url) throws IOException, NullArgumentException, ZeroException; public void load(File file) throws IOException, NullArgumentException; private void fillBinStats(final DataAdapter da) throws IOException; private int findBin(double value); public double getNextValue() throws MathIllegalStateException; public StatisticalSummary getSampleStats(); public int getBinCount(); public List<SummaryStatistics> getBinStats(); public double[] getUpperBounds(); public double[] getGeneratorUpperBounds(); public boolean isLoaded(); public void reSeed(long seed); @Override public double probability(double x); public double density(double x); public double cumulativeProbability(double x); @Override public double inverseCumulativeProbability(final double p) throws OutOfRangeException; public double getNumericalMean(); public double getNumericalVariance(); public double getSupportLowerBound(); public double getSupportUpperBound(); public boolean isSupportLowerBoundInclusive(); public boolean isSupportUpperBoundInclusive(); public boolean isSupportConnected(); @Override public double sample(); @Override public void reseedRandomGenerator(long seed); private double pB(int i); private double pBminus(int i); @SuppressWarnings("deprecation") private double kB(int i); private RealDistribution k(double x); private double cumBinP(int binIndex); protected RealDistribution getKernel(SummaryStatistics bStats); public abstract void computeBinStats() throws IOException; public abstract void computeStats() throws IOException; public StreamDataAdapter(BufferedReader in); @Override public void computeBinStats() throws IOException; @Override public void computeStats() throws IOException; public ArrayDataAdapter(double[] in) throws NullArgumentException; @Override public void computeStats() throws IOException; @Override public void computeBinStats() throws IOException; } // Abstract Java Test Class package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.integration.BaseAbstractUnivariateIntegrator; import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator; import org.apache.commons.math3.distribution.AbstractRealDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.RealDistributionAbstractTest; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public final class EmpiricalDistributionTest extends RealDistributionAbstractTest { protected EmpiricalDistribution empiricalDistribution = null; protected EmpiricalDistribution empiricalDistribution2 = null; protected File file = null; protected URL url = null; protected double[] dataArray = null; protected final int n = 10000; private final double binMass = 10d / (n + 1); private final double firstBinMass = 11d / (n + 1); @Override @Before public void setUp(); @Test public void testLoad() throws Exception; private void checkDistribution(); @Test public void testDoubleLoad() throws Exception; @Test public void testNext() throws Exception; @Test public void testNexFail(); @Test public void testGridTooFine() throws Exception; @Test public void testGridTooFat() throws Exception; @Test public void testBinIndexOverflow() throws Exception; @Test public void testSerialization(); @Test(expected=NullArgumentException.class) public void testLoadNullDoubleArray(); @Test(expected=NullArgumentException.class) public void testLoadNullURL() throws Exception; @Test(expected=NullArgumentException.class) public void testLoadNullFile() throws Exception; @Test public void testGetBinUpperBounds(); @Test public void testGeneratorConfig(); @Test public void testReSeed() throws Exception; private void verifySame(EmpiricalDistribution d1, EmpiricalDistribution d2); private void tstGen(double tolerance)throws Exception; private void tstDoubleGen(double tolerance)throws Exception; @Override public RealDistribution makeDistribution(); @Override public double[] makeCumulativeTestPoints(); @Override public double[] makeCumulativeTestValues(); @Override public double[] makeDensityTestValues(); @Override @Test public void testDensityIntegrals(); private int findBin(double x); private RealDistribution findKernel(double lower, double upper); @Test public void testKernelOverrideConstant(); @Test public void testKernelOverrideUniform(); public ConstantKernelEmpiricalDistribution(int i); @Override protected RealDistribution getKernel(SummaryStatistics bStats); public UniformKernelEmpiricalDistribution(int i); @Override protected RealDistribution getKernel(SummaryStatistics bStats); public ConstantDistribution(double c); public double density(double x); public double cumulativeProbability(double x); @Override public double inverseCumulativeProbability(double p); public double getNumericalMean(); public double getNumericalVariance(); public double getSupportLowerBound(); public double getSupportUpperBound(); public boolean isSupportLowerBoundInclusive(); public boolean isSupportUpperBoundInclusive(); public boolean isSupportConnected(); @Override public double sample(); public double value(double x); } ``` You are a professional Java test case writer, please create a test case named `testLoad` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test EmpiricalDistrbution.load() using sample data file.<br> * Check that the sampleCount, mu and sigma match data in * the sample data file. Also verify that load is idempotent. */
94
// private EmpiricalDistribution(int binCount, // RandomDataGenerator randomData); // public void load(double[] in) throws NullArgumentException; // public void load(URL url) throws IOException, NullArgumentException, ZeroException; // public void load(File file) throws IOException, NullArgumentException; // private void fillBinStats(final DataAdapter da) // throws IOException; // private int findBin(double value); // public double getNextValue() throws MathIllegalStateException; // public StatisticalSummary getSampleStats(); // public int getBinCount(); // public List<SummaryStatistics> getBinStats(); // public double[] getUpperBounds(); // public double[] getGeneratorUpperBounds(); // public boolean isLoaded(); // public void reSeed(long seed); // @Override // public double probability(double x); // public double density(double x); // public double cumulativeProbability(double x); // @Override // public double inverseCumulativeProbability(final double p) throws OutOfRangeException; // public double getNumericalMean(); // public double getNumericalVariance(); // public double getSupportLowerBound(); // public double getSupportUpperBound(); // public boolean isSupportLowerBoundInclusive(); // public boolean isSupportUpperBoundInclusive(); // public boolean isSupportConnected(); // @Override // public double sample(); // @Override // public void reseedRandomGenerator(long seed); // private double pB(int i); // private double pBminus(int i); // @SuppressWarnings("deprecation") // private double kB(int i); // private RealDistribution k(double x); // private double cumBinP(int binIndex); // protected RealDistribution getKernel(SummaryStatistics bStats); // public abstract void computeBinStats() throws IOException; // public abstract void computeStats() throws IOException; // public StreamDataAdapter(BufferedReader in); // @Override // public void computeBinStats() throws IOException; // @Override // public void computeStats() throws IOException; // public ArrayDataAdapter(double[] in) throws NullArgumentException; // @Override // public void computeStats() throws IOException; // @Override // public void computeBinStats() throws IOException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.random; // // import java.io.BufferedReader; // import java.io.File; // import java.io.IOException; // import java.io.InputStreamReader; // import java.net.URL; // import java.util.ArrayList; // import java.util.Arrays; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.integration.BaseAbstractUnivariateIntegrator; // import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator; // import org.apache.commons.math3.distribution.AbstractRealDistribution; // import org.apache.commons.math3.distribution.NormalDistribution; // import org.apache.commons.math3.distribution.RealDistribution; // import org.apache.commons.math3.distribution.RealDistributionAbstractTest; // import org.apache.commons.math3.distribution.UniformRealDistribution; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.exception.OutOfRangeException; // import org.apache.commons.math3.stat.descriptive.SummaryStatistics; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // // // // public final class EmpiricalDistributionTest extends RealDistributionAbstractTest { // protected EmpiricalDistribution empiricalDistribution = null; // protected EmpiricalDistribution empiricalDistribution2 = null; // protected File file = null; // protected URL url = null; // protected double[] dataArray = null; // protected final int n = 10000; // private final double binMass = 10d / (n + 1); // private final double firstBinMass = 11d / (n + 1); // // @Override // @Before // public void setUp(); // @Test // public void testLoad() throws Exception; // private void checkDistribution(); // @Test // public void testDoubleLoad() throws Exception; // @Test // public void testNext() throws Exception; // @Test // public void testNexFail(); // @Test // public void testGridTooFine() throws Exception; // @Test // public void testGridTooFat() throws Exception; // @Test // public void testBinIndexOverflow() throws Exception; // @Test // public void testSerialization(); // @Test(expected=NullArgumentException.class) // public void testLoadNullDoubleArray(); // @Test(expected=NullArgumentException.class) // public void testLoadNullURL() throws Exception; // @Test(expected=NullArgumentException.class) // public void testLoadNullFile() throws Exception; // @Test // public void testGetBinUpperBounds(); // @Test // public void testGeneratorConfig(); // @Test // public void testReSeed() throws Exception; // private void verifySame(EmpiricalDistribution d1, EmpiricalDistribution d2); // private void tstGen(double tolerance)throws Exception; // private void tstDoubleGen(double tolerance)throws Exception; // @Override // public RealDistribution makeDistribution(); // @Override // public double[] makeCumulativeTestPoints(); // @Override // public double[] makeCumulativeTestValues(); // @Override // public double[] makeDensityTestValues(); // @Override // @Test // public void testDensityIntegrals(); // private int findBin(double x); // private RealDistribution findKernel(double lower, double upper); // @Test // public void testKernelOverrideConstant(); // @Test // public void testKernelOverrideUniform(); // public ConstantKernelEmpiricalDistribution(int i); // @Override // protected RealDistribution getKernel(SummaryStatistics bStats); // public UniformKernelEmpiricalDistribution(int i); // @Override // protected RealDistribution getKernel(SummaryStatistics bStats); // public ConstantDistribution(double c); // public double density(double x); // public double cumulativeProbability(double x); // @Override // public double inverseCumulativeProbability(double p); // public double getNumericalMean(); // public double getNumericalVariance(); // public double getSupportLowerBound(); // public double getSupportUpperBound(); // public boolean isSupportLowerBoundInclusive(); // public boolean isSupportUpperBoundInclusive(); // public boolean isSupportConnected(); // @Override // public double sample(); // public double value(double x); // } // You are a professional Java test case writer, please create a test case named `testLoad` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test EmpiricalDistrbution.load() using sample data file.<br> * Check that the sampleCount, mu and sigma match data in * the sample data file. Also verify that load is idempotent. */ @Test public void testLoad() throws Exception {
/** * Test EmpiricalDistrbution.load() using sample data file.<br> * Check that the sampleCount, mu and sigma match data in * the sample data file. Also verify that load is idempotent. */
1
org.apache.commons.math3.random.EmpiricalDistribution
src/test/java
```java private EmpiricalDistribution(int binCount, RandomDataGenerator randomData); public void load(double[] in) throws NullArgumentException; public void load(URL url) throws IOException, NullArgumentException, ZeroException; public void load(File file) throws IOException, NullArgumentException; private void fillBinStats(final DataAdapter da) throws IOException; private int findBin(double value); public double getNextValue() throws MathIllegalStateException; public StatisticalSummary getSampleStats(); public int getBinCount(); public List<SummaryStatistics> getBinStats(); public double[] getUpperBounds(); public double[] getGeneratorUpperBounds(); public boolean isLoaded(); public void reSeed(long seed); @Override public double probability(double x); public double density(double x); public double cumulativeProbability(double x); @Override public double inverseCumulativeProbability(final double p) throws OutOfRangeException; public double getNumericalMean(); public double getNumericalVariance(); public double getSupportLowerBound(); public double getSupportUpperBound(); public boolean isSupportLowerBoundInclusive(); public boolean isSupportUpperBoundInclusive(); public boolean isSupportConnected(); @Override public double sample(); @Override public void reseedRandomGenerator(long seed); private double pB(int i); private double pBminus(int i); @SuppressWarnings("deprecation") private double kB(int i); private RealDistribution k(double x); private double cumBinP(int binIndex); protected RealDistribution getKernel(SummaryStatistics bStats); public abstract void computeBinStats() throws IOException; public abstract void computeStats() throws IOException; public StreamDataAdapter(BufferedReader in); @Override public void computeBinStats() throws IOException; @Override public void computeStats() throws IOException; public ArrayDataAdapter(double[] in) throws NullArgumentException; @Override public void computeStats() throws IOException; @Override public void computeBinStats() throws IOException; } // Abstract Java Test Class package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.integration.BaseAbstractUnivariateIntegrator; import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator; import org.apache.commons.math3.distribution.AbstractRealDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.RealDistributionAbstractTest; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public final class EmpiricalDistributionTest extends RealDistributionAbstractTest { protected EmpiricalDistribution empiricalDistribution = null; protected EmpiricalDistribution empiricalDistribution2 = null; protected File file = null; protected URL url = null; protected double[] dataArray = null; protected final int n = 10000; private final double binMass = 10d / (n + 1); private final double firstBinMass = 11d / (n + 1); @Override @Before public void setUp(); @Test public void testLoad() throws Exception; private void checkDistribution(); @Test public void testDoubleLoad() throws Exception; @Test public void testNext() throws Exception; @Test public void testNexFail(); @Test public void testGridTooFine() throws Exception; @Test public void testGridTooFat() throws Exception; @Test public void testBinIndexOverflow() throws Exception; @Test public void testSerialization(); @Test(expected=NullArgumentException.class) public void testLoadNullDoubleArray(); @Test(expected=NullArgumentException.class) public void testLoadNullURL() throws Exception; @Test(expected=NullArgumentException.class) public void testLoadNullFile() throws Exception; @Test public void testGetBinUpperBounds(); @Test public void testGeneratorConfig(); @Test public void testReSeed() throws Exception; private void verifySame(EmpiricalDistribution d1, EmpiricalDistribution d2); private void tstGen(double tolerance)throws Exception; private void tstDoubleGen(double tolerance)throws Exception; @Override public RealDistribution makeDistribution(); @Override public double[] makeCumulativeTestPoints(); @Override public double[] makeCumulativeTestValues(); @Override public double[] makeDensityTestValues(); @Override @Test public void testDensityIntegrals(); private int findBin(double x); private RealDistribution findKernel(double lower, double upper); @Test public void testKernelOverrideConstant(); @Test public void testKernelOverrideUniform(); public ConstantKernelEmpiricalDistribution(int i); @Override protected RealDistribution getKernel(SummaryStatistics bStats); public UniformKernelEmpiricalDistribution(int i); @Override protected RealDistribution getKernel(SummaryStatistics bStats); public ConstantDistribution(double c); public double density(double x); public double cumulativeProbability(double x); @Override public double inverseCumulativeProbability(double p); public double getNumericalMean(); public double getNumericalVariance(); public double getSupportLowerBound(); public double getSupportUpperBound(); public boolean isSupportLowerBoundInclusive(); public boolean isSupportUpperBoundInclusive(); public boolean isSupportConnected(); @Override public double sample(); public double value(double x); } ``` You are a professional Java test case writer, please create a test case named `testLoad` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test EmpiricalDistrbution.load() using sample data file.<br> * Check that the sampleCount, mu and sigma match data in * the sample data file. Also verify that load is idempotent. */ @Test public void testLoad() throws Exception { ```
public class EmpiricalDistribution extends AbstractRealDistribution
package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.integration.BaseAbstractUnivariateIntegrator; import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator; import org.apache.commons.math3.distribution.AbstractRealDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.RealDistributionAbstractTest; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
@Override @Before public void setUp(); @Test public void testLoad() throws Exception; private void checkDistribution(); @Test public void testDoubleLoad() throws Exception; @Test public void testNext() throws Exception; @Test public void testNexFail(); @Test public void testGridTooFine() throws Exception; @Test public void testGridTooFat() throws Exception; @Test public void testBinIndexOverflow() throws Exception; @Test public void testSerialization(); @Test(expected=NullArgumentException.class) public void testLoadNullDoubleArray(); @Test(expected=NullArgumentException.class) public void testLoadNullURL() throws Exception; @Test(expected=NullArgumentException.class) public void testLoadNullFile() throws Exception; @Test public void testGetBinUpperBounds(); @Test public void testGeneratorConfig(); @Test public void testReSeed() throws Exception; private void verifySame(EmpiricalDistribution d1, EmpiricalDistribution d2); private void tstGen(double tolerance)throws Exception; private void tstDoubleGen(double tolerance)throws Exception; @Override public RealDistribution makeDistribution(); @Override public double[] makeCumulativeTestPoints(); @Override public double[] makeCumulativeTestValues(); @Override public double[] makeDensityTestValues(); @Override @Test public void testDensityIntegrals(); private int findBin(double x); private RealDistribution findKernel(double lower, double upper); @Test public void testKernelOverrideConstant(); @Test public void testKernelOverrideUniform(); public ConstantKernelEmpiricalDistribution(int i); @Override protected RealDistribution getKernel(SummaryStatistics bStats); public UniformKernelEmpiricalDistribution(int i); @Override protected RealDistribution getKernel(SummaryStatistics bStats); public ConstantDistribution(double c); public double density(double x); public double cumulativeProbability(double x); @Override public double inverseCumulativeProbability(double p); public double getNumericalMean(); public double getNumericalVariance(); public double getSupportLowerBound(); public double getSupportUpperBound(); public boolean isSupportLowerBoundInclusive(); public boolean isSupportUpperBoundInclusive(); public boolean isSupportConnected(); @Override public double sample(); public double value(double x);
eb1b181d2515f73a4627e66538cdc4473e1ea22c25380cbcb1631861ad740a1d
[ "org.apache.commons.math3.random.EmpiricalDistributionTest::testLoad" ]
public static final int DEFAULT_BIN_COUNT = 1000; private static final String FILE_CHARSET = "US-ASCII"; private static final long serialVersionUID = 5729073523949762654L; protected final RandomDataGenerator randomData; private final List<SummaryStatistics> binStats; private SummaryStatistics sampleStats = null; private double max = Double.NEGATIVE_INFINITY; private double min = Double.POSITIVE_INFINITY; private double delta = 0d; private final int binCount; private boolean loaded = false; private double[] upperBounds = null;
@Test public void testLoad() throws Exception
protected EmpiricalDistribution empiricalDistribution = null; protected EmpiricalDistribution empiricalDistribution2 = null; protected File file = null; protected URL url = null; protected double[] dataArray = null; protected final int n = 10000; private final double binMass = 10d / (n + 1); private final double firstBinMass = 11d / (n + 1);
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.integration.BaseAbstractUnivariateIntegrator; import org.apache.commons.math3.analysis.integration.IterativeLegendreGaussIntegrator; import org.apache.commons.math3.distribution.AbstractRealDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.RealDistributionAbstractTest; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Test cases for the EmpiricalDistribution class * * @version $Id$ */ public final class EmpiricalDistributionTest extends RealDistributionAbstractTest { protected EmpiricalDistribution empiricalDistribution = null; protected EmpiricalDistribution empiricalDistribution2 = null; protected File file = null; protected URL url = null; protected double[] dataArray = null; protected final int n = 10000; @Override @Before public void setUp() { super.setUp(); empiricalDistribution = new EmpiricalDistribution(100); // empiricalDistribution = new EmpiricalDistribution(100, new RandomDataImpl()); // XXX Deprecated API url = getClass().getResource("testData.txt"); final ArrayList<Double> list = new ArrayList<Double>(); try { empiricalDistribution2 = new EmpiricalDistribution(100); // empiricalDistribution2 = new EmpiricalDistribution(100, new RandomDataImpl()); // XXX Deprecated API BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream())); String str = null; while ((str = in.readLine()) != null) { list.add(Double.valueOf(str)); } in.close(); in = null; } catch (IOException ex) { Assert.fail("IOException " + ex); } dataArray = new double[list.size()]; int i = 0; for (Double data : list) { dataArray[i] = data.doubleValue(); i++; } } /** * Test EmpiricalDistrbution.load() using sample data file.<br> * Check that the sampleCount, mu and sigma match data in * the sample data file. Also verify that load is idempotent. */ @Test public void testLoad() throws Exception { // Load from a URL empiricalDistribution.load(url); checkDistribution(); // Load again from a file (also verifies idempotency of load) File file = new File(url.toURI()); empiricalDistribution.load(file); checkDistribution(); } private void checkDistribution() { // testData File has 10000 values, with mean ~ 5.0, std dev ~ 1 // Make sure that loaded distribution matches this Assert.assertEquals(empiricalDistribution.getSampleStats().getN(),1000,10E-7); //TODO: replace with statistical tests Assert.assertEquals(empiricalDistribution.getSampleStats().getMean(), 5.069831575018909,10E-7); Assert.assertEquals(empiricalDistribution.getSampleStats().getStandardDeviation(), 1.0173699343977738,10E-7); } /** * Test EmpiricalDistrbution.load(double[]) using data taken from * sample data file.<br> * Check that the sampleCount, mu and sigma match data in * the sample data file. */ @Test public void testDoubleLoad() throws Exception { empiricalDistribution2.load(dataArray); // testData File has 10000 values, with mean ~ 5.0, std dev ~ 1 // Make sure that loaded distribution matches this Assert.assertEquals(empiricalDistribution2.getSampleStats().getN(),1000,10E-7); //TODO: replace with statistical tests Assert.assertEquals(empiricalDistribution2.getSampleStats().getMean(), 5.069831575018909,10E-7); Assert.assertEquals(empiricalDistribution2.getSampleStats().getStandardDeviation(), 1.0173699343977738,10E-7); double[] bounds = empiricalDistribution2.getGeneratorUpperBounds(); Assert.assertEquals(bounds.length, 100); Assert.assertEquals(bounds[99], 1.0, 10e-12); } /** * Generate 1000 random values and make sure they look OK.<br> * Note that there is a non-zero (but very small) probability that * these tests will fail even if the code is working as designed. */ @Test public void testNext() throws Exception { tstGen(0.1); tstDoubleGen(0.1); } /** * Make sure exception thrown if digest getNext is attempted * before loading empiricalDistribution. */ @Test public void testNexFail() { try { empiricalDistribution.getNextValue(); empiricalDistribution2.getNextValue(); Assert.fail("Expecting IllegalStateException"); } catch (IllegalStateException ex) { // expected } } /** * Make sure we can handle a grid size that is too fine */ @Test public void testGridTooFine() throws Exception { empiricalDistribution = new EmpiricalDistribution(1001); tstGen(0.1); empiricalDistribution2 = new EmpiricalDistribution(1001); tstDoubleGen(0.1); } /** * How about too fat? */ @Test public void testGridTooFat() throws Exception { empiricalDistribution = new EmpiricalDistribution(1); tstGen(5); // ridiculous tolerance; but ridiculous grid size // really just checking to make sure we do not bomb empiricalDistribution2 = new EmpiricalDistribution(1); tstDoubleGen(5); } /** * Test bin index overflow problem (BZ 36450) */ @Test public void testBinIndexOverflow() throws Exception { double[] x = new double[] {9474.94326071674, 2080107.8865462579}; new EmpiricalDistribution().load(x); } @Test public void testSerialization() { // Empty EmpiricalDistribution dist = new EmpiricalDistribution(); EmpiricalDistribution dist2 = (EmpiricalDistribution) TestUtils.serializeAndRecover(dist); verifySame(dist, dist2); // Loaded empiricalDistribution2.load(dataArray); dist2 = (EmpiricalDistribution) TestUtils.serializeAndRecover(empiricalDistribution2); verifySame(empiricalDistribution2, dist2); } @Test(expected=NullArgumentException.class) public void testLoadNullDoubleArray() { new EmpiricalDistribution().load((double[]) null); } @Test(expected=NullArgumentException.class) public void testLoadNullURL() throws Exception { new EmpiricalDistribution().load((URL) null); } @Test(expected=NullArgumentException.class) public void testLoadNullFile() throws Exception { new EmpiricalDistribution().load((File) null); } /** * MATH-298 */ @Test public void testGetBinUpperBounds() { double[] testData = {0, 1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10}; EmpiricalDistribution dist = new EmpiricalDistribution(5); dist.load(testData); double[] expectedBinUpperBounds = {2, 4, 6, 8, 10}; double[] expectedGeneratorUpperBounds = {4d/13d, 7d/13d, 9d/13d, 11d/13d, 1}; double tol = 10E-12; TestUtils.assertEquals(expectedBinUpperBounds, dist.getUpperBounds(), tol); TestUtils.assertEquals(expectedGeneratorUpperBounds, dist.getGeneratorUpperBounds(), tol); } @Test public void testGeneratorConfig() { double[] testData = {0, 1, 2, 3, 4}; RandomGenerator generator = new RandomAdaptorTest.ConstantGenerator(0.5); EmpiricalDistribution dist = new EmpiricalDistribution(5, generator); dist.load(testData); for (int i = 0; i < 5; i++) { Assert.assertEquals(2.0, dist.getNextValue(), 0d); } // Verify no NPE with null generator argument dist = new EmpiricalDistribution(5, (RandomGenerator) null); dist.load(testData); dist.getNextValue(); } @Test public void testReSeed() throws Exception { empiricalDistribution.load(url); empiricalDistribution.reSeed(100); final double [] values = new double[10]; for (int i = 0; i < 10; i++) { values[i] = empiricalDistribution.getNextValue(); } empiricalDistribution.reSeed(100); for (int i = 0; i < 10; i++) { Assert.assertEquals(values[i],empiricalDistribution.getNextValue(), 0d); } } private void verifySame(EmpiricalDistribution d1, EmpiricalDistribution d2) { Assert.assertEquals(d1.isLoaded(), d2.isLoaded()); Assert.assertEquals(d1.getBinCount(), d2.getBinCount()); Assert.assertEquals(d1.getSampleStats(), d2.getSampleStats()); if (d1.isLoaded()) { for (int i = 0; i < d1.getUpperBounds().length; i++) { Assert.assertEquals(d1.getUpperBounds()[i], d2.getUpperBounds()[i], 0); } Assert.assertEquals(d1.getBinStats(), d2.getBinStats()); } } private void tstGen(double tolerance)throws Exception { empiricalDistribution.load(url); empiricalDistribution.reSeed(1000); SummaryStatistics stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { stats.addValue(empiricalDistribution.getNextValue()); } Assert.assertEquals("mean", 5.069831575018909, stats.getMean(),tolerance); Assert.assertEquals("std dev", 1.0173699343977738, stats.getStandardDeviation(),tolerance); } private void tstDoubleGen(double tolerance)throws Exception { empiricalDistribution2.load(dataArray); empiricalDistribution2.reSeed(1000); SummaryStatistics stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { stats.addValue(empiricalDistribution2.getNextValue()); } Assert.assertEquals("mean", 5.069831575018909, stats.getMean(), tolerance); Assert.assertEquals("std dev", 1.0173699343977738, stats.getStandardDeviation(), tolerance); } // Setup for distribution tests @Override public RealDistribution makeDistribution() { // Create a uniform distribution on [0, 10,000] final double[] sourceData = new double[n + 1]; for (int i = 0; i < n + 1; i++) { sourceData[i] = i; } EmpiricalDistribution dist = new EmpiricalDistribution(); dist.load(sourceData); return dist; } /** Uniform bin mass = 10/10001 == mass of all but the first bin */ private final double binMass = 10d / (n + 1); /** Mass of first bin = 11/10001 */ private final double firstBinMass = 11d / (n + 1); @Override public double[] makeCumulativeTestPoints() { final double[] testPoints = new double[] {9, 10, 15, 1000, 5004, 9999}; return testPoints; } @Override public double[] makeCumulativeTestValues() { /* * Bins should be [0, 10], (10, 20], ..., (9990, 10000] * Kernels should be N(4.5, 3.02765), N(14.5, 3.02765)... * Each bin should have mass 10/10000 = .001 */ final double[] testPoints = getCumulativeTestPoints(); final double[] cumValues = new double[testPoints.length]; final EmpiricalDistribution empiricalDistribution = (EmpiricalDistribution) makeDistribution(); final double[] binBounds = empiricalDistribution.getUpperBounds(); for (int i = 0; i < testPoints.length; i++) { final int bin = findBin(testPoints[i]); final double lower = bin == 0 ? empiricalDistribution.getSupportLowerBound() : binBounds[bin - 1]; final double upper = binBounds[bin]; // Compute bMinus = sum or mass of bins below the bin containing the point // First bin has mass 11 / 10000, the rest have mass 10 / 10000. final double bMinus = bin == 0 ? 0 : (bin - 1) * binMass + firstBinMass; final RealDistribution kernel = findKernel(lower, upper); final double withinBinKernelMass = kernel.cumulativeProbability(lower, upper); final double kernelCum = kernel.cumulativeProbability(lower, testPoints[i]); cumValues[i] = bMinus + (bin == 0 ? firstBinMass : binMass) * kernelCum/withinBinKernelMass; } return cumValues; } @Override public double[] makeDensityTestValues() { final double[] testPoints = getCumulativeTestPoints(); final double[] densityValues = new double[testPoints.length]; final EmpiricalDistribution empiricalDistribution = (EmpiricalDistribution) makeDistribution(); final double[] binBounds = empiricalDistribution.getUpperBounds(); for (int i = 0; i < testPoints.length; i++) { final int bin = findBin(testPoints[i]); final double lower = bin == 0 ? empiricalDistribution.getSupportLowerBound() : binBounds[bin - 1]; final double upper = binBounds[bin]; final RealDistribution kernel = findKernel(lower, upper); final double withinBinKernelMass = kernel.cumulativeProbability(lower, upper); final double density = kernel.density(testPoints[i]); densityValues[i] = density * (bin == 0 ? firstBinMass : binMass) / withinBinKernelMass; } return densityValues; } /** * Modify test integration bounds from the default. Because the distribution * has discontinuities at bin boundaries, integrals spanning multiple bins * will face convergence problems. Only test within-bin integrals and spans * across no more than 3 bin boundaries. */ @Override @Test public void testDensityIntegrals() { final RealDistribution distribution = makeDistribution(); final double tol = 1.0e-9; final BaseAbstractUnivariateIntegrator integrator = new IterativeLegendreGaussIntegrator(5, 1.0e-12, 1.0e-10); final UnivariateFunction d = new UnivariateFunction() { public double value(double x) { return distribution.density(x); } }; final double[] lower = {0, 5, 1000, 5001, 9995}; final double[] upper = {5, 12, 1030, 5010, 10000}; for (int i = 1; i < 5; i++) { Assert.assertEquals( distribution.cumulativeProbability( lower[i], upper[i]), integrator.integrate( 1000000, // Triangle integrals are very slow to converge d, lower[i], upper[i]), tol); } } /** * Find the bin that x belongs (relative to {@link #makeDistribution()}). */ private int findBin(double x) { // Number of bins below x should be trunc(x/10) final double nMinus = Math.floor(x / 10); final int bin = (int) Math.round(nMinus); // If x falls on a bin boundary, it is in the lower bin return Math.floor(x / 10) == x / 10 ? bin - 1 : bin; } /** * Find the within-bin kernel for the bin with lower bound lower * and upper bound upper. All bins other than the first contain 10 points * exclusive of the lower bound and are centered at (lower + upper + 1) / 2. * The first bin includes its lower bound, 0, so has different mean and * standard deviation. */ private RealDistribution findKernel(double lower, double upper) { if (lower < 1) { return new NormalDistribution(5d, 3.3166247903554); } else { return new NormalDistribution((upper + lower + 1) / 2d, 3.0276503540974917); } } @Test public void testKernelOverrideConstant() { final EmpiricalDistribution dist = new ConstantKernelEmpiricalDistribution(5); final double[] data = {1d,2d,3d, 4d,5d,6d, 7d,8d,9d, 10d,11d,12d, 13d,14d,15d}; dist.load(data); // Bin masses concentrated on 2, 5, 8, 11, 14 <- effectively discrete uniform distribution over these double[] values = {2d, 5d, 8d, 11d, 14d}; for (int i = 0; i < 20; i++) { Assert.assertTrue(Arrays.binarySearch(values, dist.sample()) >= 0); } final double tol = 10E-12; Assert.assertEquals(0.0, dist.cumulativeProbability(1), tol); Assert.assertEquals(0.2, dist.cumulativeProbability(2), tol); Assert.assertEquals(0.6, dist.cumulativeProbability(10), tol); Assert.assertEquals(0.8, dist.cumulativeProbability(12), tol); Assert.assertEquals(0.8, dist.cumulativeProbability(13), tol); Assert.assertEquals(1.0, dist.cumulativeProbability(15), tol); Assert.assertEquals(2.0, dist.inverseCumulativeProbability(0.1), tol); Assert.assertEquals(2.0, dist.inverseCumulativeProbability(0.2), tol); Assert.assertEquals(5.0, dist.inverseCumulativeProbability(0.3), tol); Assert.assertEquals(5.0, dist.inverseCumulativeProbability(0.4), tol); Assert.assertEquals(8.0, dist.inverseCumulativeProbability(0.5), tol); Assert.assertEquals(8.0, dist.inverseCumulativeProbability(0.6), tol); } @Test public void testKernelOverrideUniform() { final EmpiricalDistribution dist = new UniformKernelEmpiricalDistribution(5); final double[] data = {1d,2d,3d, 4d,5d,6d, 7d,8d,9d, 10d,11d,12d, 13d,14d,15d}; dist.load(data); // Kernels are uniform distributions on [1,3], [4,6], [7,9], [10,12], [13,15] final double bounds[] = {3d, 6d, 9d, 12d}; final double tol = 10E-12; for (int i = 0; i < 20; i++) { final double v = dist.sample(); // Make sure v is not in the excluded range between bins - that is (bounds[i], bounds[i] + 1) for (int j = 0; j < bounds.length; j++) { Assert.assertFalse(v > bounds[j] + tol && v < bounds[j] + 1 - tol); } } Assert.assertEquals(0.0, dist.cumulativeProbability(1), tol); Assert.assertEquals(0.1, dist.cumulativeProbability(2), tol); Assert.assertEquals(0.6, dist.cumulativeProbability(10), tol); Assert.assertEquals(0.8, dist.cumulativeProbability(12), tol); Assert.assertEquals(0.8, dist.cumulativeProbability(13), tol); Assert.assertEquals(1.0, dist.cumulativeProbability(15), tol); Assert.assertEquals(2.0, dist.inverseCumulativeProbability(0.1), tol); Assert.assertEquals(3.0, dist.inverseCumulativeProbability(0.2), tol); Assert.assertEquals(5.0, dist.inverseCumulativeProbability(0.3), tol); Assert.assertEquals(6.0, dist.inverseCumulativeProbability(0.4), tol); Assert.assertEquals(8.0, dist.inverseCumulativeProbability(0.5), tol); Assert.assertEquals(9.0, dist.inverseCumulativeProbability(0.6), tol); } /** * Empirical distribution using a constant smoothing kernel. */ private class ConstantKernelEmpiricalDistribution extends EmpiricalDistribution { private static final long serialVersionUID = 1L; public ConstantKernelEmpiricalDistribution(int i) { super(i); } // Use constant distribution equal to bin mean within bin @Override protected RealDistribution getKernel(SummaryStatistics bStats) { return new ConstantDistribution(bStats.getMean()); } } /** * Empirical distribution using a uniform smoothing kernel. */ private class UniformKernelEmpiricalDistribution extends EmpiricalDistribution { private static final long serialVersionUID = 2963149194515159653L; public UniformKernelEmpiricalDistribution(int i) { super(i); } @Override protected RealDistribution getKernel(SummaryStatistics bStats) { return new UniformRealDistribution(randomData.getRandomGenerator(), bStats.getMin(), bStats.getMax(), UniformRealDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); } } /** * Distribution that takes just one value. */ private class ConstantDistribution extends AbstractRealDistribution { private static final long serialVersionUID = 1L; /** Singleton value in the sample space */ private final double c; public ConstantDistribution(double c) { this.c = c; } public double density(double x) { return 0; } public double cumulativeProbability(double x) { return x < c ? 0 : 1; } @Override public double inverseCumulativeProbability(double p) { if (p < 0.0 || p > 1.0) { throw new OutOfRangeException(p, 0, 1); } return c; } public double getNumericalMean() { return c; } public double getNumericalVariance() { return 0; } public double getSupportLowerBound() { return c; } public double getSupportUpperBound() { return c; } public boolean isSupportLowerBoundInclusive() { return false; } public boolean isSupportUpperBoundInclusive() { return true; } public boolean isSupportConnected() { return true; } @Override public double sample() { return c; } } }
[ { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "access$300", "be_test_function_signature": "(Lorg/apache/commons/math3/random/EmpiricalDistribution;)Lorg/apache/commons/math3/stat/descriptive/SummaryStatistics;", "line_numbers": [ "102" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "fillBinStats", "be_test_function_signature": "(Lorg/apache/commons/math3/random/EmpiricalDistribution$DataAdapter;)V", "line_numbers": [ "429", "430", "431", "434", "435", "437", "438", "439", "443", "446", "447", "449", "450", "453", "454" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "findBin", "be_test_function_signature": "(D)I", "line_numbers": [ "463" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "getSampleStats", "be_test_function_signature": "()Lorg/apache/commons/math3/stat/descriptive/StatisticalSummary;", "line_numbers": [ "509" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "getSupportLowerBound", "be_test_function_signature": "()D", "line_numbers": [ "730" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "getUpperBounds", "be_test_function_signature": "()[D", "line_numbers": [ "546", "547", "548", "550", "551" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "load", "be_test_function_signature": "(Ljava/io/File;)V", "line_numbers": [ "289", "290", "291", "292", "294", "295", "297", "298", "299", "300", "302", "303", "304", "306", "307", "308" ], "method_line_rate": 0.8125 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "load", "be_test_function_signature": "(Ljava/net/URL;)V", "line_numbers": [ "255", "256", "257", "260", "261", "262", "263", "266", "267", "268", "270", "271", "272", "274", "275", "276" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/apache/commons/math3/random/EmpiricalDistribution.java", "be_test_class_name": "org.apache.commons.math3.random.EmpiricalDistribution", "be_test_function_name": "load", "be_test_function_signature": "([D)V", "line_numbers": [ "229", "231", "233", "234", "236", "237", "238", "240" ], "method_line_rate": 0.75 } ]
public class MultiBackgroundInitializerTest
@Test public void testInitializeChildWithExecutor() throws ConcurrentException { final String initExec = "childInitializerWithExecutor"; final ExecutorService exec = Executors.newSingleThreadExecutor(); try { final ChildBackgroundInitializer c1 = new ChildBackgroundInitializer(); final ChildBackgroundInitializer c2 = new ChildBackgroundInitializer(); c2.setExternalExecutor(exec); initializer.addInitializer(CHILD_INIT, c1); initializer.addInitializer(initExec, c2); initializer.start(); initializer.get(); checkChild(c1, initializer.getActiveExecutor()); checkChild(c2, exec); } finally { exec.shutdown(); } }
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.Collections; // import java.util.HashMap; // import java.util.Map; // import java.util.NoSuchElementException; // import java.util.Set; // import java.util.concurrent.ExecutorService; // // // // public class MultiBackgroundInitializer // extends // BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { // private final Map<String, BackgroundInitializer<?>> childInitializers = // new HashMap<String, BackgroundInitializer<?>>(); // // public MultiBackgroundInitializer(); // public MultiBackgroundInitializer(final ExecutorService exec); // public void addInitializer(final String name, final BackgroundInitializer<?> init); // @Override // protected int getTaskCount(); // @Override // protected MultiBackgroundInitializerResults initialize() throws Exception; // private MultiBackgroundInitializerResults( // final Map<String, BackgroundInitializer<?>> inits, // final Map<String, Object> results, // final Map<String, ConcurrentException> excepts); // public BackgroundInitializer<?> getInitializer(final String name); // public Object getResultObject(final String name); // public boolean isException(final String name); // public ConcurrentException getException(final String name); // public Set<String> initializerNames(); // public boolean isSuccessful(); // private BackgroundInitializer<?> checkName(final String name); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.concurrent; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNull; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.util.Iterator; // import java.util.NoSuchElementException; // import java.util.concurrent.ExecutorService; // import java.util.concurrent.Executors; // import org.junit.Before; // import org.junit.Test; // // // // public class MultiBackgroundInitializerTest { // private static final String CHILD_INIT = "childInitializer"; // private MultiBackgroundInitializer initializer; // // @Before // public void setUp() throws Exception; // private void checkChild(final BackgroundInitializer<?> child, // final ExecutorService expExec) throws ConcurrentException; // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullName(); // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullInit(); // @Test // public void testInitializeNoChildren() throws ConcurrentException; // private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() // throws ConcurrentException; // @Test // public void testInitializeTempExec() throws ConcurrentException; // @Test // public void testInitializeExternalExec() throws ConcurrentException; // @Test // public void testInitializeChildWithExecutor() throws ConcurrentException; // @Test // public void testAddInitializerAfterStart() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetInitializerUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetResultObjectUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetExceptionUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultIsExceptionUnknown() throws ConcurrentException; // @Test(expected = UnsupportedOperationException.class) // public void testResultInitializerNamesModify() throws ConcurrentException; // @Test // public void testInitializeRuntimeEx(); // @Test // public void testInitializeEx() throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulTrue() // throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulFalse() // throws ConcurrentException; // @Test // public void testInitializeNested() throws ConcurrentException; // @Override // protected Integer initialize() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testInitializeChildWithExecutor` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the behavior of initialize() if a child initializer has a specific * executor service. Then this service should not be overridden. */
src/test/java/org/apache/commons/lang3/concurrent/MultiBackgroundInitializerTest.java
package org.apache.commons.lang3.concurrent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutorService;
public MultiBackgroundInitializer(); public MultiBackgroundInitializer(final ExecutorService exec); public void addInitializer(final String name, final BackgroundInitializer<?> init); @Override protected int getTaskCount(); @Override protected MultiBackgroundInitializerResults initialize() throws Exception; private MultiBackgroundInitializerResults( final Map<String, BackgroundInitializer<?>> inits, final Map<String, Object> results, final Map<String, ConcurrentException> excepts); public BackgroundInitializer<?> getInitializer(final String name); public Object getResultObject(final String name); public boolean isException(final String name); public ConcurrentException getException(final String name); public Set<String> initializerNames(); public boolean isSuccessful(); private BackgroundInitializer<?> checkName(final String name);
180
testInitializeChildWithExecutor
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutorService; public class MultiBackgroundInitializer extends BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>(); public MultiBackgroundInitializer(); public MultiBackgroundInitializer(final ExecutorService exec); public void addInitializer(final String name, final BackgroundInitializer<?> init); @Override protected int getTaskCount(); @Override protected MultiBackgroundInitializerResults initialize() throws Exception; private MultiBackgroundInitializerResults( final Map<String, BackgroundInitializer<?>> inits, final Map<String, Object> results, final Map<String, ConcurrentException> excepts); public BackgroundInitializer<?> getInitializer(final String name); public Object getResultObject(final String name); public boolean isException(final String name); public ConcurrentException getException(final String name); public Set<String> initializerNames(); public boolean isSuccessful(); private BackgroundInitializer<?> checkName(final String name); } // Abstract Java Test Class package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; public class MultiBackgroundInitializerTest { private static final String CHILD_INIT = "childInitializer"; private MultiBackgroundInitializer initializer; @Before public void setUp() throws Exception; private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException; @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName(); @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit(); @Test public void testInitializeNoChildren() throws ConcurrentException; private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException; @Test public void testInitializeTempExec() throws ConcurrentException; @Test public void testInitializeExternalExec() throws ConcurrentException; @Test public void testInitializeChildWithExecutor() throws ConcurrentException; @Test public void testAddInitializerAfterStart() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException; @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException; @Test public void testInitializeRuntimeEx(); @Test public void testInitializeEx() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException; @Test public void testInitializeNested() throws ConcurrentException; @Override protected Integer initialize() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testInitializeChildWithExecutor` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the behavior of initialize() if a child initializer has a specific * executor service. Then this service should not be overridden. */
163
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.Collections; // import java.util.HashMap; // import java.util.Map; // import java.util.NoSuchElementException; // import java.util.Set; // import java.util.concurrent.ExecutorService; // // // // public class MultiBackgroundInitializer // extends // BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { // private final Map<String, BackgroundInitializer<?>> childInitializers = // new HashMap<String, BackgroundInitializer<?>>(); // // public MultiBackgroundInitializer(); // public MultiBackgroundInitializer(final ExecutorService exec); // public void addInitializer(final String name, final BackgroundInitializer<?> init); // @Override // protected int getTaskCount(); // @Override // protected MultiBackgroundInitializerResults initialize() throws Exception; // private MultiBackgroundInitializerResults( // final Map<String, BackgroundInitializer<?>> inits, // final Map<String, Object> results, // final Map<String, ConcurrentException> excepts); // public BackgroundInitializer<?> getInitializer(final String name); // public Object getResultObject(final String name); // public boolean isException(final String name); // public ConcurrentException getException(final String name); // public Set<String> initializerNames(); // public boolean isSuccessful(); // private BackgroundInitializer<?> checkName(final String name); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.concurrent; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNull; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.util.Iterator; // import java.util.NoSuchElementException; // import java.util.concurrent.ExecutorService; // import java.util.concurrent.Executors; // import org.junit.Before; // import org.junit.Test; // // // // public class MultiBackgroundInitializerTest { // private static final String CHILD_INIT = "childInitializer"; // private MultiBackgroundInitializer initializer; // // @Before // public void setUp() throws Exception; // private void checkChild(final BackgroundInitializer<?> child, // final ExecutorService expExec) throws ConcurrentException; // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullName(); // @Test(expected = IllegalArgumentException.class) // public void testAddInitializerNullInit(); // @Test // public void testInitializeNoChildren() throws ConcurrentException; // private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() // throws ConcurrentException; // @Test // public void testInitializeTempExec() throws ConcurrentException; // @Test // public void testInitializeExternalExec() throws ConcurrentException; // @Test // public void testInitializeChildWithExecutor() throws ConcurrentException; // @Test // public void testAddInitializerAfterStart() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetInitializerUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetResultObjectUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultGetExceptionUnknown() throws ConcurrentException; // @Test(expected = NoSuchElementException.class) // public void testResultIsExceptionUnknown() throws ConcurrentException; // @Test(expected = UnsupportedOperationException.class) // public void testResultInitializerNamesModify() throws ConcurrentException; // @Test // public void testInitializeRuntimeEx(); // @Test // public void testInitializeEx() throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulTrue() // throws ConcurrentException; // @Test // public void testInitializeResultsIsSuccessfulFalse() // throws ConcurrentException; // @Test // public void testInitializeNested() throws ConcurrentException; // @Override // protected Integer initialize() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testInitializeChildWithExecutor` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the behavior of initialize() if a child initializer has a specific * executor service. Then this service should not be overridden. */ @Test public void testInitializeChildWithExecutor() throws ConcurrentException {
/** * Tests the behavior of initialize() if a child initializer has a specific * executor service. Then this service should not be overridden. */
1
org.apache.commons.lang3.concurrent.MultiBackgroundInitializer
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutorService; public class MultiBackgroundInitializer extends BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> { private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>(); public MultiBackgroundInitializer(); public MultiBackgroundInitializer(final ExecutorService exec); public void addInitializer(final String name, final BackgroundInitializer<?> init); @Override protected int getTaskCount(); @Override protected MultiBackgroundInitializerResults initialize() throws Exception; private MultiBackgroundInitializerResults( final Map<String, BackgroundInitializer<?>> inits, final Map<String, Object> results, final Map<String, ConcurrentException> excepts); public BackgroundInitializer<?> getInitializer(final String name); public Object getResultObject(final String name); public boolean isException(final String name); public ConcurrentException getException(final String name); public Set<String> initializerNames(); public boolean isSuccessful(); private BackgroundInitializer<?> checkName(final String name); } // Abstract Java Test Class package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; public class MultiBackgroundInitializerTest { private static final String CHILD_INIT = "childInitializer"; private MultiBackgroundInitializer initializer; @Before public void setUp() throws Exception; private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException; @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName(); @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit(); @Test public void testInitializeNoChildren() throws ConcurrentException; private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException; @Test public void testInitializeTempExec() throws ConcurrentException; @Test public void testInitializeExternalExec() throws ConcurrentException; @Test public void testInitializeChildWithExecutor() throws ConcurrentException; @Test public void testAddInitializerAfterStart() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException; @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException; @Test public void testInitializeRuntimeEx(); @Test public void testInitializeEx() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException; @Test public void testInitializeNested() throws ConcurrentException; @Override protected Integer initialize() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testInitializeChildWithExecutor` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the behavior of initialize() if a child initializer has a specific * executor service. Then this service should not be overridden. */ @Test public void testInitializeChildWithExecutor() throws ConcurrentException { ```
public class MultiBackgroundInitializer extends BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults>
package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test;
@Before public void setUp() throws Exception; private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException; @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName(); @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit(); @Test public void testInitializeNoChildren() throws ConcurrentException; private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException; @Test public void testInitializeTempExec() throws ConcurrentException; @Test public void testInitializeExternalExec() throws ConcurrentException; @Test public void testInitializeChildWithExecutor() throws ConcurrentException; @Test public void testAddInitializerAfterStart() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException; @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException; @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException; @Test public void testInitializeRuntimeEx(); @Test public void testInitializeEx() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException; @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException; @Test public void testInitializeNested() throws ConcurrentException; @Override protected Integer initialize() throws Exception;
ec0f51b31566085e3e11e0f3019f7e049c54bba76a0f7d6ed6d7ae0be97e44e3
[ "org.apache.commons.lang3.concurrent.MultiBackgroundInitializerTest::testInitializeChildWithExecutor" ]
private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>();
@Test public void testInitializeChildWithExecutor() throws ConcurrentException
private static final String CHILD_INIT = "childInitializer"; private MultiBackgroundInitializer initializer;
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; /** * Test class for {@link MultiBackgroundInitializer}. * * @version $Id$ */ public class MultiBackgroundInitializerTest { /** Constant for the names of the child initializers. */ private static final String CHILD_INIT = "childInitializer"; /** The initializer to be tested. */ private MultiBackgroundInitializer initializer; @Before public void setUp() throws Exception { initializer = new MultiBackgroundInitializer(); } /** * Tests whether a child initializer has been executed. Optionally the * expected executor service can be checked, too. * * @param child the child initializer * @param expExec the expected executor service (null if the executor should * not be checked) * @throws ConcurrentException if an error occurs */ private void checkChild(final BackgroundInitializer<?> child, final ExecutorService expExec) throws ConcurrentException { final ChildBackgroundInitializer cinit = (ChildBackgroundInitializer) child; final Integer result = cinit.get(); assertEquals("Wrong result", 1, result.intValue()); assertEquals("Wrong number of executions", 1, cinit.initializeCalls); if (expExec != null) { assertEquals("Wrong executor service", expExec, cinit.currentExecutor); } } /** * Tests addInitializer() if a null name is passed in. This should cause an * exception. */ @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullName() { initializer.addInitializer(null, new ChildBackgroundInitializer()); } /** * Tests addInitializer() if a null initializer is passed in. This should * cause an exception. */ @Test(expected = IllegalArgumentException.class) public void testAddInitializerNullInit() { initializer.addInitializer(CHILD_INIT, null); } /** * Tests the background processing if there are no child initializers. */ @Test public void testInitializeNoChildren() throws ConcurrentException { assertTrue("Wrong result of start()", initializer.start()); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertTrue("Got child initializers", res.initializerNames().isEmpty()); assertTrue("Executor not shutdown", initializer.getActiveExecutor() .isShutdown()); } /** * Helper method for testing the initialize() method. This method can * operate with both an external and a temporary executor service. * * @return the result object produced by the initializer */ private MultiBackgroundInitializer.MultiBackgroundInitializerResults checkInitialize() throws ConcurrentException { final int count = 5; for (int i = 0; i < count; i++) { initializer.addInitializer(CHILD_INIT + i, new ChildBackgroundInitializer()); } initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertEquals("Wrong number of child initializers", count, res .initializerNames().size()); for (int i = 0; i < count; i++) { final String key = CHILD_INIT + i; assertTrue("Name not found: " + key, res.initializerNames() .contains(key)); assertEquals("Wrong result object", Integer.valueOf(1), res .getResultObject(key)); assertFalse("Exception flag", res.isException(key)); assertNull("Got an exception", res.getException(key)); checkChild(res.getInitializer(key), initializer.getActiveExecutor()); } return res; } /** * Tests background processing if a temporary executor is used. */ @Test public void testInitializeTempExec() throws ConcurrentException { checkInitialize(); assertTrue("Executor not shutdown", initializer.getActiveExecutor() .isShutdown()); } /** * Tests background processing if an external executor service is provided. */ @Test public void testInitializeExternalExec() throws ConcurrentException { final ExecutorService exec = Executors.newCachedThreadPool(); try { initializer = new MultiBackgroundInitializer(exec); checkInitialize(); assertEquals("Wrong executor", exec, initializer .getActiveExecutor()); assertFalse("Executor was shutdown", exec.isShutdown()); } finally { exec.shutdown(); } } /** * Tests the behavior of initialize() if a child initializer has a specific * executor service. Then this service should not be overridden. */ @Test public void testInitializeChildWithExecutor() throws ConcurrentException { final String initExec = "childInitializerWithExecutor"; final ExecutorService exec = Executors.newSingleThreadExecutor(); try { final ChildBackgroundInitializer c1 = new ChildBackgroundInitializer(); final ChildBackgroundInitializer c2 = new ChildBackgroundInitializer(); c2.setExternalExecutor(exec); initializer.addInitializer(CHILD_INIT, c1); initializer.addInitializer(initExec, c2); initializer.start(); initializer.get(); checkChild(c1, initializer.getActiveExecutor()); checkChild(c2, exec); } finally { exec.shutdown(); } } /** * Tries to add another child initializer after the start() method has been * called. This should not be allowed. */ @Test public void testAddInitializerAfterStart() throws ConcurrentException { initializer.start(); try { initializer.addInitializer(CHILD_INIT, new ChildBackgroundInitializer()); fail("Could add initializer after start()!"); } catch (final IllegalStateException istex) { initializer.get(); } } /** * Tries to query an unknown child initializer from the results object. This * should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultGetInitializerUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.getInitializer("unknown"); } /** * Tries to query the results of an unknown child initializer from the * results object. This should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultGetResultObjectUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.getResultObject("unknown"); } /** * Tries to query the exception of an unknown child initializer from the * results object. This should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.getException("unknown"); } /** * Tries to query the exception flag of an unknown child initializer from * the results object. This should cause an exception. */ @Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.isException("unknown"); } /** * Tests that the set with the names of the initializers cannot be modified. */ @Test(expected = UnsupportedOperationException.class) public void testResultInitializerNamesModify() throws ConcurrentException { checkInitialize(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); final Iterator<String> it = res.initializerNames().iterator(); it.next(); it.remove(); } /** * Tests the behavior of the initializer if one of the child initializers * throws a runtime exception. */ @Test public void testInitializeRuntimeEx() { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); child.ex = new RuntimeException(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); try { initializer.get(); fail("Runtime exception not thrown!"); } catch (final Exception ex) { assertEquals("Wrong exception", child.ex, ex); } } /** * Tests the behavior of the initializer if one of the child initializers * throws a checked exception. */ @Test public void testInitializeEx() throws ConcurrentException { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); child.ex = new Exception(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertTrue("No exception flag", res.isException(CHILD_INIT)); assertNull("Got a results object", res.getResultObject(CHILD_INIT)); final ConcurrentException cex = res.getException(CHILD_INIT); assertEquals("Wrong cause", child.ex, cex.getCause()); } /** * Tests the isSuccessful() method of the result object if no child * initializer has thrown an exception. */ @Test public void testInitializeResultsIsSuccessfulTrue() throws ConcurrentException { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertTrue("Wrong success flag", res.isSuccessful()); } /** * Tests the isSuccessful() method of the result object if at least one * child initializer has thrown an exception. */ @Test public void testInitializeResultsIsSuccessfulFalse() throws ConcurrentException { final ChildBackgroundInitializer child = new ChildBackgroundInitializer(); child.ex = new Exception(); initializer.addInitializer(CHILD_INIT, child); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); assertFalse("Wrong success flag", res.isSuccessful()); } /** * Tests whether MultiBackgroundInitializers can be combined in a nested * way. */ @Test public void testInitializeNested() throws ConcurrentException { final String nameMulti = "multiChildInitializer"; initializer .addInitializer(CHILD_INIT, new ChildBackgroundInitializer()); final MultiBackgroundInitializer mi2 = new MultiBackgroundInitializer(); final int count = 3; for (int i = 0; i < count; i++) { mi2 .addInitializer(CHILD_INIT + i, new ChildBackgroundInitializer()); } initializer.addInitializer(nameMulti, mi2); initializer.start(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer .get(); final ExecutorService exec = initializer.getActiveExecutor(); checkChild(res.getInitializer(CHILD_INIT), exec); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res2 = (MultiBackgroundInitializer.MultiBackgroundInitializerResults) res .getResultObject(nameMulti); assertEquals("Wrong number of initializers", count, res2 .initializerNames().size()); for (int i = 0; i < count; i++) { checkChild(res2.getInitializer(CHILD_INIT + i), exec); } assertTrue("Executor not shutdown", exec.isShutdown()); } /** * A concrete implementation of {@code BackgroundInitializer} used for * defining background tasks for {@code MultiBackgroundInitializer}. */ private static class ChildBackgroundInitializer extends BackgroundInitializer<Integer> { /** Stores the current executor service. */ volatile ExecutorService currentExecutor; /** A counter for the invocations of initialize(). */ volatile int initializeCalls; /** An exception to be thrown by initialize(). */ Exception ex; /** * Records this invocation. Optionally throws an exception. */ @Override protected Integer initialize() throws Exception { currentExecutor = getActiveExecutor(); initializeCalls++; if (ex != null) { throw ex; } return Integer.valueOf(initializeCalls); } } }
[ { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "addInitializer", "be_test_function_signature": "(Ljava/lang/String;Lorg/apache/commons/lang3/concurrent/BackgroundInitializer;)V", "line_numbers": [ "135", "136", "139", "140", "144", "145", "146", "149", "150", "151" ], "method_line_rate": 0.7 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "getTaskCount", "be_test_function_signature": "()I", "line_numbers": [ "165", "167", "168", "169", "171" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "initialize", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "97" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.MultiBackgroundInitializer", "be_test_function_name": "initialize", "be_test_function_signature": "()Lorg/apache/commons/lang3/concurrent/MultiBackgroundInitializer$MultiBackgroundInitializerResults;", "line_numbers": [ "187", "189", "191", "194", "195", "196", "198", "200", "201", "204", "205", "206", "208", "209", "210", "211", "212", "214" ], "method_line_rate": 0.8888888888888888 } ]
public class ObjectReaderTest extends BaseMapTest
public void testMissingType() throws Exception { ObjectReader r = MAPPER.reader(); try { r.readValue("1"); fail("Should not pass"); } catch (JsonMappingException e) { verifyException(e, "No value type configured"); } }
// @Override // public void writeTree(JsonGenerator g, TreeNode rootNode); // @SuppressWarnings("unchecked") // public <T> T readValue(InputStream src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(Reader src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(String src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src, int offset, int length) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(File src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(URL src) // throws IOException; // @SuppressWarnings({ "unchecked", "resource" }) // public <T> T readValue(JsonNode src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(DataInput src) throws IOException; // public JsonNode readTree(InputStream in) throws IOException; // public JsonNode readTree(Reader r) throws IOException; // public JsonNode readTree(String json) throws IOException; // public JsonNode readTree(DataInput src) throws IOException; // public <T> MappingIterator<T> readValues(JsonParser p) // throws IOException; // public <T> MappingIterator<T> readValues(InputStream src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(Reader src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(String json) // throws IOException; // public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) // throws IOException; // public final <T> MappingIterator<T> readValues(byte[] src) // throws IOException; // public <T> MappingIterator<T> readValues(File src) // throws IOException; // public <T> MappingIterator<T> readValues(URL src) // throws IOException; // public <T> MappingIterator<T> readValues(DataInput src) throws IOException; // @Override // public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; // @Override // public void writeValue(JsonGenerator gen, Object value) throws IOException; // protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; // protected Object _bindAndClose(JsonParser p0) throws IOException; // protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; // protected final JsonNode _bindAsTree(JsonParser p) throws IOException; // protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; // protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, // JavaType rootType, JsonDeserializer<Object> deser) throws IOException; // protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); // protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, // JavaType bindType) // throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; // protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) // throws JsonProcessingException; // protected void _verifySchemaType(FormatSchema schema); // protected DefaultDeserializationContext createDeserializationContext(JsonParser p); // protected InputStream _inputStream(URL src) throws IOException; // protected InputStream _inputStream(File f) throws IOException; // protected void _reportUndetectableSource(Object src) throws JsonProcessingException; // protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.StringWriter; // import java.util.Collections; // import java.util.List; // import java.util.Map; // import java.util.Set; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.databind.cfg.ContextAttributes; // import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; // import com.fasterxml.jackson.databind.node.ArrayNode; // import com.fasterxml.jackson.databind.node.JsonNodeFactory; // import com.fasterxml.jackson.databind.node.ObjectNode; // // // // public class ObjectReaderTest extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testSimpleViaParser() throws Exception; // public void testSimpleAltSources() throws Exception; // public void testParserFeatures() throws Exception; // public void testNodeHandling() throws Exception; // public void testFeatureSettings() throws Exception; // public void testMiscSettings() throws Exception; // @SuppressWarnings("deprecation") // public void testDeprecatedSettings() throws Exception; // public void testNoPrefetch() throws Exception; // public void testNoPointerLoading() throws Exception; // public void testPointerLoading() throws Exception; // public void testPointerLoadingAsJsonNode() throws Exception; // public void testPointerLoadingMappingIteratorOne() throws Exception; // public void testPointerLoadingMappingIteratorMany() throws Exception; // public void testPointerWithArrays() throws Exception; // public void testTreeToValue() throws Exception; // public void testCodecUnsupportedWrites() throws Exception; // public void testMissingType() throws Exception; // public void testSchema() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testMissingType` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, failures, other /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/ObjectReaderTest.java
package com.fasterxml.jackson.databind; import java.io.*; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.filter.FilteringParserDelegate; import com.fasterxml.jackson.core.filter.JsonPointerBasedFilter; import com.fasterxml.jackson.core.filter.TokenFilter; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DataFormatReaders; import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.TreeTraversingParser; import com.fasterxml.jackson.databind.type.SimpleType; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.util.ClassUtil;
protected ObjectReader(ObjectMapper mapper, DeserializationConfig config); protected ObjectReader(ObjectMapper mapper, DeserializationConfig config, JavaType valueType, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues); protected ObjectReader(ObjectReader base, DeserializationConfig config, JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues, DataFormatReaders dataFormatReaders); protected ObjectReader(ObjectReader base, DeserializationConfig config); protected ObjectReader(ObjectReader base, JsonFactory f); protected ObjectReader(ObjectReader base, TokenFilter filter); @Override public Version version(); protected ObjectReader _new(ObjectReader base, JsonFactory f); protected ObjectReader _new(ObjectReader base, DeserializationConfig config); protected ObjectReader _new(ObjectReader base, DeserializationConfig config, JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues, DataFormatReaders dataFormatReaders); protected <T> MappingIterator<T> _newIterator(JsonParser p, DeserializationContext ctxt, JsonDeserializer<?> deser, boolean parserManaged); protected JsonToken _initForReading(DeserializationContext ctxt, JsonParser p) throws IOException; protected void _initForMultiRead(DeserializationContext ctxt, JsonParser p) throws IOException; public ObjectReader with(DeserializationFeature feature); public ObjectReader with(DeserializationFeature first, DeserializationFeature... other); public ObjectReader withFeatures(DeserializationFeature... features); public ObjectReader without(DeserializationFeature feature); public ObjectReader without(DeserializationFeature first, DeserializationFeature... other); public ObjectReader withoutFeatures(DeserializationFeature... features); public ObjectReader with(JsonParser.Feature feature); public ObjectReader withFeatures(JsonParser.Feature... features); public ObjectReader without(JsonParser.Feature feature); public ObjectReader withoutFeatures(JsonParser.Feature... features); public ObjectReader with(FormatFeature feature); public ObjectReader withFeatures(FormatFeature... features); public ObjectReader without(FormatFeature feature); public ObjectReader withoutFeatures(FormatFeature... features); public ObjectReader at(final String value); public ObjectReader at(final JsonPointer pointer); public ObjectReader with(DeserializationConfig config); public ObjectReader with(InjectableValues injectableValues); public ObjectReader with(JsonNodeFactory f); public ObjectReader with(JsonFactory f); public ObjectReader withRootName(String rootName); public ObjectReader withRootName(PropertyName rootName); public ObjectReader withoutRootName(); public ObjectReader with(FormatSchema schema); public ObjectReader forType(JavaType valueType); public ObjectReader forType(Class<?> valueType); public ObjectReader forType(TypeReference<?> valueTypeRef); @Deprecated public ObjectReader withType(JavaType valueType); @Deprecated public ObjectReader withType(Class<?> valueType); @Deprecated public ObjectReader withType(java.lang.reflect.Type valueType); @Deprecated public ObjectReader withType(TypeReference<?> valueTypeRef); public ObjectReader withValueToUpdate(Object value); public ObjectReader withView(Class<?> activeView); public ObjectReader with(Locale l); public ObjectReader with(TimeZone tz); public ObjectReader withHandler(DeserializationProblemHandler h); public ObjectReader with(Base64Variant defaultBase64); public ObjectReader withFormatDetection(ObjectReader... readers); public ObjectReader withFormatDetection(DataFormatReaders readers); public ObjectReader with(ContextAttributes attrs); public ObjectReader withAttributes(Map<?,?> attrs); public ObjectReader withAttribute(Object key, Object value); public ObjectReader withoutAttribute(Object key); protected ObjectReader _with(DeserializationConfig newConfig); public boolean isEnabled(DeserializationFeature f); public boolean isEnabled(MapperFeature f); public boolean isEnabled(JsonParser.Feature f); public DeserializationConfig getConfig(); @Override public JsonFactory getFactory(); public TypeFactory getTypeFactory(); public ContextAttributes getAttributes(); public InjectableValues getInjectableValues(); @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p) throws IOException; @SuppressWarnings("unchecked") @Override public <T> T readValue(JsonParser p, Class<T> valueType) throws IOException; @SuppressWarnings("unchecked") @Override public <T> T readValue(JsonParser p, TypeReference<?> valueTypeRef) throws IOException; @Override @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p, ResolvedType valueType) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p, JavaType valueType) throws IOException; @Override public <T> Iterator<T> readValues(JsonParser p, Class<T> valueType) throws IOException; @Override public <T> Iterator<T> readValues(JsonParser p, TypeReference<?> valueTypeRef) throws IOException; @Override public <T> Iterator<T> readValues(JsonParser p, ResolvedType valueType) throws IOException; public <T> Iterator<T> readValues(JsonParser p, JavaType valueType) throws IOException; @Override public JsonNode createArrayNode(); @Override public JsonNode createObjectNode(); @Override public JsonParser treeAsTokens(TreeNode n); @SuppressWarnings("unchecked") @Override public <T extends TreeNode> T readTree(JsonParser p) throws IOException; @Override public void writeTree(JsonGenerator g, TreeNode rootNode); @SuppressWarnings("unchecked") public <T> T readValue(InputStream src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(String src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(File src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(URL src) throws IOException; @SuppressWarnings({ "unchecked", "resource" }) public <T> T readValue(JsonNode src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src) throws IOException; public JsonNode readTree(InputStream in) throws IOException; public JsonNode readTree(Reader r) throws IOException; public JsonNode readTree(String json) throws IOException; public JsonNode readTree(DataInput src) throws IOException; public <T> MappingIterator<T> readValues(JsonParser p) throws IOException; public <T> MappingIterator<T> readValues(InputStream src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(String json) throws IOException; public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException; public final <T> MappingIterator<T> readValues(byte[] src) throws IOException; public <T> MappingIterator<T> readValues(File src) throws IOException; public <T> MappingIterator<T> readValues(URL src) throws IOException; public <T> MappingIterator<T> readValues(DataInput src) throws IOException; @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; @Override public void writeValue(JsonGenerator gen, Object value) throws IOException; protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; protected Object _bindAndClose(JsonParser p0) throws IOException; protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; protected final JsonNode _bindAsTree(JsonParser p) throws IOException; protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) throws JsonProcessingException; protected void _verifySchemaType(FormatSchema schema); protected DefaultDeserializationContext createDeserializationContext(JsonParser p); protected InputStream _inputStream(URL src) throws IOException; protected InputStream _inputStream(File f) throws IOException; protected void _reportUndetectableSource(Object src) throws JsonProcessingException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType);
307
testMissingType
```java @Override public void writeTree(JsonGenerator g, TreeNode rootNode); @SuppressWarnings("unchecked") public <T> T readValue(InputStream src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(String src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(File src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(URL src) throws IOException; @SuppressWarnings({ "unchecked", "resource" }) public <T> T readValue(JsonNode src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src) throws IOException; public JsonNode readTree(InputStream in) throws IOException; public JsonNode readTree(Reader r) throws IOException; public JsonNode readTree(String json) throws IOException; public JsonNode readTree(DataInput src) throws IOException; public <T> MappingIterator<T> readValues(JsonParser p) throws IOException; public <T> MappingIterator<T> readValues(InputStream src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(String json) throws IOException; public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException; public final <T> MappingIterator<T> readValues(byte[] src) throws IOException; public <T> MappingIterator<T> readValues(File src) throws IOException; public <T> MappingIterator<T> readValues(URL src) throws IOException; public <T> MappingIterator<T> readValues(DataInput src) throws IOException; @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; @Override public void writeValue(JsonGenerator gen, Object value) throws IOException; protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; protected Object _bindAndClose(JsonParser p0) throws IOException; protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; protected final JsonNode _bindAsTree(JsonParser p) throws IOException; protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) throws JsonProcessingException; protected void _verifySchemaType(FormatSchema schema); protected DefaultDeserializationContext createDeserializationContext(JsonParser p); protected InputStream _inputStream(URL src) throws IOException; protected InputStream _inputStream(File f) throws IOException; protected void _reportUndetectableSource(Object src) throws JsonProcessingException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectReaderTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleViaParser() throws Exception; public void testSimpleAltSources() throws Exception; public void testParserFeatures() throws Exception; public void testNodeHandling() throws Exception; public void testFeatureSettings() throws Exception; public void testMiscSettings() throws Exception; @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception; public void testNoPrefetch() throws Exception; public void testNoPointerLoading() throws Exception; public void testPointerLoading() throws Exception; public void testPointerLoadingAsJsonNode() throws Exception; public void testPointerLoadingMappingIteratorOne() throws Exception; public void testPointerLoadingMappingIteratorMany() throws Exception; public void testPointerWithArrays() throws Exception; public void testTreeToValue() throws Exception; public void testCodecUnsupportedWrites() throws Exception; public void testMissingType() throws Exception; public void testSchema() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testMissingType` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, failures, other /********************************************************** */
298
// @Override // public void writeTree(JsonGenerator g, TreeNode rootNode); // @SuppressWarnings("unchecked") // public <T> T readValue(InputStream src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(Reader src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(String src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src, int offset, int length) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(File src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(URL src) // throws IOException; // @SuppressWarnings({ "unchecked", "resource" }) // public <T> T readValue(JsonNode src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(DataInput src) throws IOException; // public JsonNode readTree(InputStream in) throws IOException; // public JsonNode readTree(Reader r) throws IOException; // public JsonNode readTree(String json) throws IOException; // public JsonNode readTree(DataInput src) throws IOException; // public <T> MappingIterator<T> readValues(JsonParser p) // throws IOException; // public <T> MappingIterator<T> readValues(InputStream src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(Reader src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(String json) // throws IOException; // public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) // throws IOException; // public final <T> MappingIterator<T> readValues(byte[] src) // throws IOException; // public <T> MappingIterator<T> readValues(File src) // throws IOException; // public <T> MappingIterator<T> readValues(URL src) // throws IOException; // public <T> MappingIterator<T> readValues(DataInput src) throws IOException; // @Override // public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; // @Override // public void writeValue(JsonGenerator gen, Object value) throws IOException; // protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; // protected Object _bindAndClose(JsonParser p0) throws IOException; // protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; // protected final JsonNode _bindAsTree(JsonParser p) throws IOException; // protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; // protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, // JavaType rootType, JsonDeserializer<Object> deser) throws IOException; // protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); // protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, // JavaType bindType) // throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; // protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) // throws JsonProcessingException; // protected void _verifySchemaType(FormatSchema schema); // protected DefaultDeserializationContext createDeserializationContext(JsonParser p); // protected InputStream _inputStream(URL src) throws IOException; // protected InputStream _inputStream(File f) throws IOException; // protected void _reportUndetectableSource(Object src) throws JsonProcessingException; // protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.StringWriter; // import java.util.Collections; // import java.util.List; // import java.util.Map; // import java.util.Set; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.databind.cfg.ContextAttributes; // import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; // import com.fasterxml.jackson.databind.node.ArrayNode; // import com.fasterxml.jackson.databind.node.JsonNodeFactory; // import com.fasterxml.jackson.databind.node.ObjectNode; // // // // public class ObjectReaderTest extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testSimpleViaParser() throws Exception; // public void testSimpleAltSources() throws Exception; // public void testParserFeatures() throws Exception; // public void testNodeHandling() throws Exception; // public void testFeatureSettings() throws Exception; // public void testMiscSettings() throws Exception; // @SuppressWarnings("deprecation") // public void testDeprecatedSettings() throws Exception; // public void testNoPrefetch() throws Exception; // public void testNoPointerLoading() throws Exception; // public void testPointerLoading() throws Exception; // public void testPointerLoadingAsJsonNode() throws Exception; // public void testPointerLoadingMappingIteratorOne() throws Exception; // public void testPointerLoadingMappingIteratorMany() throws Exception; // public void testPointerWithArrays() throws Exception; // public void testTreeToValue() throws Exception; // public void testCodecUnsupportedWrites() throws Exception; // public void testMissingType() throws Exception; // public void testSchema() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testMissingType` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, failures, other /********************************************************** */ public void testMissingType() throws Exception {
/* /********************************************************** /* Test methods, failures, other /********************************************************** */
112
com.fasterxml.jackson.databind.ObjectReader
src/test/java
```java @Override public void writeTree(JsonGenerator g, TreeNode rootNode); @SuppressWarnings("unchecked") public <T> T readValue(InputStream src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(String src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(File src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(URL src) throws IOException; @SuppressWarnings({ "unchecked", "resource" }) public <T> T readValue(JsonNode src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src) throws IOException; public JsonNode readTree(InputStream in) throws IOException; public JsonNode readTree(Reader r) throws IOException; public JsonNode readTree(String json) throws IOException; public JsonNode readTree(DataInput src) throws IOException; public <T> MappingIterator<T> readValues(JsonParser p) throws IOException; public <T> MappingIterator<T> readValues(InputStream src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(String json) throws IOException; public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException; public final <T> MappingIterator<T> readValues(byte[] src) throws IOException; public <T> MappingIterator<T> readValues(File src) throws IOException; public <T> MappingIterator<T> readValues(URL src) throws IOException; public <T> MappingIterator<T> readValues(DataInput src) throws IOException; @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; @Override public void writeValue(JsonGenerator gen, Object value) throws IOException; protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; protected Object _bindAndClose(JsonParser p0) throws IOException; protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; protected final JsonNode _bindAsTree(JsonParser p) throws IOException; protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) throws JsonProcessingException; protected void _verifySchemaType(FormatSchema schema); protected DefaultDeserializationContext createDeserializationContext(JsonParser p); protected InputStream _inputStream(URL src) throws IOException; protected InputStream _inputStream(File f) throws IOException; protected void _reportUndetectableSource(Object src) throws JsonProcessingException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectReaderTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleViaParser() throws Exception; public void testSimpleAltSources() throws Exception; public void testParserFeatures() throws Exception; public void testNodeHandling() throws Exception; public void testFeatureSettings() throws Exception; public void testMiscSettings() throws Exception; @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception; public void testNoPrefetch() throws Exception; public void testNoPointerLoading() throws Exception; public void testPointerLoading() throws Exception; public void testPointerLoadingAsJsonNode() throws Exception; public void testPointerLoadingMappingIteratorOne() throws Exception; public void testPointerLoadingMappingIteratorMany() throws Exception; public void testPointerWithArrays() throws Exception; public void testTreeToValue() throws Exception; public void testCodecUnsupportedWrites() throws Exception; public void testMissingType() throws Exception; public void testSchema() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testMissingType` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, failures, other /********************************************************** */ public void testMissingType() throws Exception { ```
public class ObjectReader extends ObjectCodec implements Versioned, java.io.Serializable // since 2.1
package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode;
public void testSimpleViaParser() throws Exception; public void testSimpleAltSources() throws Exception; public void testParserFeatures() throws Exception; public void testNodeHandling() throws Exception; public void testFeatureSettings() throws Exception; public void testMiscSettings() throws Exception; @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception; public void testNoPrefetch() throws Exception; public void testNoPointerLoading() throws Exception; public void testPointerLoading() throws Exception; public void testPointerLoadingAsJsonNode() throws Exception; public void testPointerLoadingMappingIteratorOne() throws Exception; public void testPointerLoadingMappingIteratorMany() throws Exception; public void testPointerWithArrays() throws Exception; public void testTreeToValue() throws Exception; public void testCodecUnsupportedWrites() throws Exception; public void testMissingType() throws Exception; public void testSchema() throws Exception;
ef6430945ddbb82b731645c3cd140b088ab82fd5e8a6c76a366bb30ce956cde5
[ "com.fasterxml.jackson.databind.ObjectReaderTest::testMissingType" ]
private static final long serialVersionUID = 2L; private final static JavaType JSON_NODE_TYPE = SimpleType.constructUnsafe(JsonNode.class); protected final DeserializationConfig _config; protected final DefaultDeserializationContext _context; protected final JsonFactory _parserFactory; protected final boolean _unwrapRoot; private final TokenFilter _filter; protected final JavaType _valueType; protected final JsonDeserializer<Object> _rootDeserializer; protected final Object _valueToUpdate; protected final FormatSchema _schema; protected final InjectableValues _injectableValues; protected final DataFormatReaders _dataFormatReaders; final protected ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers;
public void testMissingType() throws Exception
final ObjectMapper MAPPER = new ObjectMapper();
JacksonDatabind
package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectReaderTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); static class POJO { public Map<String, Object> name; } public void testSimpleViaParser() throws Exception { final String JSON = "[1]"; JsonParser p = MAPPER.getFactory().createParser(JSON); Object ob = MAPPER.readerFor(Object.class) .readValue(p); p.close(); assertTrue(ob instanceof List<?>); } public void testSimpleAltSources() throws Exception { final String JSON = "[1]"; final byte[] BYTES = JSON.getBytes("UTF-8"); Object ob = MAPPER.readerFor(Object.class) .readValue(BYTES); assertTrue(ob instanceof List<?>); ob = MAPPER.readerFor(Object.class) .readValue(BYTES, 0, BYTES.length); assertTrue(ob instanceof List<?>); assertEquals(1, ((List<?>) ob).size()); } public void testParserFeatures() throws Exception { final String JSON = "[ /* foo */ 7 ]"; // default won't accept comments, let's change that: ObjectReader reader = MAPPER.readerFor(int[].class) .with(JsonParser.Feature.ALLOW_COMMENTS); int[] value = reader.readValue(JSON); assertNotNull(value); assertEquals(1, value.length); assertEquals(7, value[0]); // but also can go back try { reader.without(JsonParser.Feature.ALLOW_COMMENTS).readValue(JSON); fail("Should not have passed"); } catch (JsonProcessingException e) { verifyException(e, "foo"); } } public void testNodeHandling() throws Exception { JsonNodeFactory nodes = new JsonNodeFactory(true); ObjectReader r = MAPPER.reader().with(nodes); // but also no further changes if attempting again assertSame(r, r.with(nodes)); assertTrue(r.createArrayNode().isArray()); assertTrue(r.createObjectNode().isObject()); } public void testFeatureSettings() throws Exception { ObjectReader r = MAPPER.reader(); assertFalse(r.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)); assertFalse(r.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); r = r.withoutFeatures(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, DeserializationFeature.FAIL_ON_INVALID_SUBTYPE); assertFalse(r.isEnabled(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)); assertFalse(r.isEnabled(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)); r = r.withFeatures(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, DeserializationFeature.FAIL_ON_INVALID_SUBTYPE); assertTrue(r.isEnabled(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)); assertTrue(r.isEnabled(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)); // alternative method too... can't recall why two assertSame(r, r.with(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)); } public void testMiscSettings() throws Exception { ObjectReader r = MAPPER.reader(); assertSame(MAPPER.getFactory(), r.getFactory()); JsonFactory f = new JsonFactory(); r = r.with(f); assertSame(f, r.getFactory()); assertSame(r, r.with(f)); assertNotNull(r.getTypeFactory()); assertNull(r.getInjectableValues()); r = r.withAttributes(Collections.emptyMap()); ContextAttributes attrs = r.getAttributes(); assertNotNull(attrs); assertNull(attrs.getAttribute("abc")); assertSame(r, r.withoutAttribute("foo")); ObjectReader newR = r.forType(MAPPER.constructType(String.class)); assertNotSame(r, newR); assertSame(newR, newR.forType(String.class)); DeserializationProblemHandler probH = new DeserializationProblemHandler() { }; newR = r.withHandler(probH); assertNotSame(r, newR); assertSame(newR, newR.withHandler(probH)); r = newR; } @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception { ObjectReader r = MAPPER.reader(); // and deprecated variants ObjectReader newR = r.forType(MAPPER.constructType(String.class)); assertSame(newR, newR.withType(String.class)); assertSame(newR, newR.withType(MAPPER.constructType(String.class))); newR = newR.withRootName(PropertyName.construct("foo")); assertNotSame(r, newR); assertSame(newR, newR.withRootName(PropertyName.construct("foo"))); } public void testNoPrefetch() throws Exception { ObjectReader r = MAPPER.reader() .without(DeserializationFeature.EAGER_DESERIALIZER_FETCH); Number n = r.forType(Integer.class).readValue("123 "); assertEquals(Integer.valueOf(123), n); } /* /********************************************************** /* Test methods, JsonPointer /********************************************************** */ public void testNoPointerLoading() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; JsonNode tree = MAPPER.readTree(source); JsonNode node = tree.at("/foo/bar/caller"); POJO pojo = MAPPER.treeToValue(node, POJO.class); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); } public void testPointerLoading() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at("/foo/bar/caller"); POJO pojo = reader.readValue(source); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); } public void testPointerLoadingAsJsonNode() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at(JsonPointer.compile("/foo/bar/caller")); JsonNode node = reader.readTree(source); assertTrue(node.has("name")); assertEquals("{\"value\":1234}", node.get("name").toString()); } public void testPointerLoadingMappingIteratorOne() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at("/foo/bar/caller"); MappingIterator<POJO> itr = reader.readValues(source); POJO pojo = itr.next(); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); assertFalse(itr.hasNext()); itr.close(); } public void testPointerLoadingMappingIteratorMany() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":[{\"name\":{\"value\":1234}}, {\"name\":{\"value\":5678}}]}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at("/foo/bar/caller"); MappingIterator<POJO> itr = reader.readValues(source); POJO pojo = itr.next(); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); assertTrue(itr.hasNext()); pojo = itr.next(); assertNotNull(pojo.name); assertTrue(pojo.name.containsKey("value")); assertEquals(5678, pojo.name.get("value")); assertFalse(itr.hasNext()); itr.close(); } // [databind#1637] public void testPointerWithArrays() throws Exception { final String json = aposToQuotes("{\n'wrapper1': {\n" + " 'set1': ['one', 'two', 'three'],\n" + " 'set2': ['four', 'five', 'six']\n" + "},\n" + "'wrapper2': {\n" + " 'set1': ['one', 'two', 'three'],\n" + " 'set2': ['four', 'five', 'six']\n" + "}\n}"); final Pojo1637 testObject = MAPPER.readerFor(Pojo1637.class) .at("/wrapper1") .readValue(json); assertNotNull(testObject); assertNotNull(testObject.set1); assertTrue(!testObject.set1.isEmpty()); assertNotNull(testObject.set2); assertTrue(!testObject.set2.isEmpty()); } public static class Pojo1637 { public Set<String> set1; public Set<String> set2; } /* /********************************************************** /* Test methods, ObjectCodec /********************************************************** */ public void testTreeToValue() throws Exception { ArrayNode n = MAPPER.createArrayNode(); n.add("xyz"); ObjectReader r = MAPPER.readerFor(String.class); List<?> list = r.treeToValue(n, List.class); assertEquals(1, list.size()); } public void testCodecUnsupportedWrites() throws Exception { ObjectReader r = MAPPER.readerFor(String.class); JsonGenerator g = MAPPER.getFactory().createGenerator(new StringWriter()); ObjectNode n = MAPPER.createObjectNode(); try { r.writeTree(g, n); fail("Should not pass"); } catch (UnsupportedOperationException e) { ; } try { r.writeValue(g, "Foo"); fail("Should not pass"); } catch (UnsupportedOperationException e) { ; } g.close(); g.close(); } /* /********************************************************** /* Test methods, failures, other /********************************************************** */ public void testMissingType() throws Exception { ObjectReader r = MAPPER.reader(); try { r.readValue("1"); fail("Should not pass"); } catch (JsonMappingException e) { verifyException(e, "No value type configured"); } } public void testSchema() throws Exception { ObjectReader r = MAPPER.readerFor(String.class); // Ok to try to set `null` schema, always: r = r.with((FormatSchema) null); try { // but not schema that doesn't match format (no schema exists for json) r = r.with(new BogusSchema()) .readValue(quote("foo")); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "Cannot use FormatSchema"); } } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_bindAndClose", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser;)Ljava/lang/Object;", "line_numbers": [ "1592", "1595", "1596", "1597", "1598", "1599", "1601", "1603", "1604", "1606", "1607", "1608", "1610", "1611", "1613", "1614", "1618", "1619", "1621", "1622" ], "method_line_rate": 0.35 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_considerFilter", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser;Z)Lcom/fasterxml/jackson/core/JsonParser;", "line_numbers": [ "1726" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_findRootDeserializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/DeserializationContext;)Lcom/fasterxml/jackson/databind/JsonDeserializer;", "line_numbers": [ "1879", "1880", "1884", "1885", "1886", "1890", "1891", "1892", "1895", "1896", "1897", "1899", "1900" ], "method_line_rate": 0.3076923076923077 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_initForReading", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/DeserializationContext;Lcom/fasterxml/jackson/core/JsonParser;)Lcom/fasterxml/jackson/core/JsonToken;", "line_numbers": [ "344", "345", "347", "353", "354", "355", "356", "358", "362" ], "method_line_rate": 0.7777777777777778 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_prefetchRootDeserializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JsonDeserializer;", "line_numbers": [ "1929", "1930", "1933", "1934", "1937", "1938", "1939", "1940", "1942", "1943", "1947" ], "method_line_rate": 0.18181818181818182 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "createDeserializationContext", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser;)Lcom/fasterxml/jackson/databind/deser/DefaultDeserializationContext;", "line_numbers": [ "1849" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "readValue", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/Object;", "line_numbers": [ "1215", "1216", "1219" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "with", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/InjectableValues;)Lcom/fasterxml/jackson/databind/ObjectReader;", "line_numbers": [ "568", "569", "571" ], "method_line_rate": 0.6666666666666666 } ]
public class ObjectReaderTest extends BaseMapTest
public void testTreeToValue() throws Exception { ArrayNode n = MAPPER.createArrayNode(); n.add("xyz"); ObjectReader r = MAPPER.readerFor(String.class); List<?> list = r.treeToValue(n, List.class); assertEquals(1, list.size()); }
// @Override // public void writeTree(JsonGenerator g, TreeNode rootNode); // @SuppressWarnings("unchecked") // public <T> T readValue(InputStream src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(Reader src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(String src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src, int offset, int length) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(File src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(URL src) // throws IOException; // @SuppressWarnings({ "unchecked", "resource" }) // public <T> T readValue(JsonNode src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(DataInput src) throws IOException; // public JsonNode readTree(InputStream in) throws IOException; // public JsonNode readTree(Reader r) throws IOException; // public JsonNode readTree(String json) throws IOException; // public JsonNode readTree(DataInput src) throws IOException; // public <T> MappingIterator<T> readValues(JsonParser p) // throws IOException; // public <T> MappingIterator<T> readValues(InputStream src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(Reader src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(String json) // throws IOException; // public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) // throws IOException; // public final <T> MappingIterator<T> readValues(byte[] src) // throws IOException; // public <T> MappingIterator<T> readValues(File src) // throws IOException; // public <T> MappingIterator<T> readValues(URL src) // throws IOException; // public <T> MappingIterator<T> readValues(DataInput src) throws IOException; // @Override // public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; // @Override // public void writeValue(JsonGenerator gen, Object value) throws IOException; // protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; // protected Object _bindAndClose(JsonParser p0) throws IOException; // protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; // protected final JsonNode _bindAsTree(JsonParser p) throws IOException; // protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; // protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, // JavaType rootType, JsonDeserializer<Object> deser) throws IOException; // protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); // protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, // JavaType bindType) // throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; // protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) // throws JsonProcessingException; // protected void _verifySchemaType(FormatSchema schema); // protected DefaultDeserializationContext createDeserializationContext(JsonParser p); // protected InputStream _inputStream(URL src) throws IOException; // protected InputStream _inputStream(File f) throws IOException; // protected void _reportUndetectableSource(Object src) throws JsonProcessingException; // protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.StringWriter; // import java.util.Collections; // import java.util.List; // import java.util.Map; // import java.util.Set; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.databind.cfg.ContextAttributes; // import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; // import com.fasterxml.jackson.databind.node.ArrayNode; // import com.fasterxml.jackson.databind.node.JsonNodeFactory; // import com.fasterxml.jackson.databind.node.ObjectNode; // // // // public class ObjectReaderTest extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testSimpleViaParser() throws Exception; // public void testSimpleAltSources() throws Exception; // public void testParserFeatures() throws Exception; // public void testNodeHandling() throws Exception; // public void testFeatureSettings() throws Exception; // public void testMiscSettings() throws Exception; // @SuppressWarnings("deprecation") // public void testDeprecatedSettings() throws Exception; // public void testNoPrefetch() throws Exception; // public void testNoPointerLoading() throws Exception; // public void testPointerLoading() throws Exception; // public void testPointerLoadingAsJsonNode() throws Exception; // public void testPointerLoadingMappingIteratorOne() throws Exception; // public void testPointerLoadingMappingIteratorMany() throws Exception; // public void testPointerWithArrays() throws Exception; // public void testTreeToValue() throws Exception; // public void testCodecUnsupportedWrites() throws Exception; // public void testMissingType() throws Exception; // public void testSchema() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testTreeToValue` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, ObjectCodec /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/ObjectReaderTest.java
package com.fasterxml.jackson.databind; import java.io.*; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.filter.FilteringParserDelegate; import com.fasterxml.jackson.core.filter.JsonPointerBasedFilter; import com.fasterxml.jackson.core.filter.TokenFilter; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DataFormatReaders; import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.TreeTraversingParser; import com.fasterxml.jackson.databind.type.SimpleType; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.util.ClassUtil;
protected ObjectReader(ObjectMapper mapper, DeserializationConfig config); protected ObjectReader(ObjectMapper mapper, DeserializationConfig config, JavaType valueType, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues); protected ObjectReader(ObjectReader base, DeserializationConfig config, JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues, DataFormatReaders dataFormatReaders); protected ObjectReader(ObjectReader base, DeserializationConfig config); protected ObjectReader(ObjectReader base, JsonFactory f); protected ObjectReader(ObjectReader base, TokenFilter filter); @Override public Version version(); protected ObjectReader _new(ObjectReader base, JsonFactory f); protected ObjectReader _new(ObjectReader base, DeserializationConfig config); protected ObjectReader _new(ObjectReader base, DeserializationConfig config, JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues, DataFormatReaders dataFormatReaders); protected <T> MappingIterator<T> _newIterator(JsonParser p, DeserializationContext ctxt, JsonDeserializer<?> deser, boolean parserManaged); protected JsonToken _initForReading(DeserializationContext ctxt, JsonParser p) throws IOException; protected void _initForMultiRead(DeserializationContext ctxt, JsonParser p) throws IOException; public ObjectReader with(DeserializationFeature feature); public ObjectReader with(DeserializationFeature first, DeserializationFeature... other); public ObjectReader withFeatures(DeserializationFeature... features); public ObjectReader without(DeserializationFeature feature); public ObjectReader without(DeserializationFeature first, DeserializationFeature... other); public ObjectReader withoutFeatures(DeserializationFeature... features); public ObjectReader with(JsonParser.Feature feature); public ObjectReader withFeatures(JsonParser.Feature... features); public ObjectReader without(JsonParser.Feature feature); public ObjectReader withoutFeatures(JsonParser.Feature... features); public ObjectReader with(FormatFeature feature); public ObjectReader withFeatures(FormatFeature... features); public ObjectReader without(FormatFeature feature); public ObjectReader withoutFeatures(FormatFeature... features); public ObjectReader at(final String value); public ObjectReader at(final JsonPointer pointer); public ObjectReader with(DeserializationConfig config); public ObjectReader with(InjectableValues injectableValues); public ObjectReader with(JsonNodeFactory f); public ObjectReader with(JsonFactory f); public ObjectReader withRootName(String rootName); public ObjectReader withRootName(PropertyName rootName); public ObjectReader withoutRootName(); public ObjectReader with(FormatSchema schema); public ObjectReader forType(JavaType valueType); public ObjectReader forType(Class<?> valueType); public ObjectReader forType(TypeReference<?> valueTypeRef); @Deprecated public ObjectReader withType(JavaType valueType); @Deprecated public ObjectReader withType(Class<?> valueType); @Deprecated public ObjectReader withType(java.lang.reflect.Type valueType); @Deprecated public ObjectReader withType(TypeReference<?> valueTypeRef); public ObjectReader withValueToUpdate(Object value); public ObjectReader withView(Class<?> activeView); public ObjectReader with(Locale l); public ObjectReader with(TimeZone tz); public ObjectReader withHandler(DeserializationProblemHandler h); public ObjectReader with(Base64Variant defaultBase64); public ObjectReader withFormatDetection(ObjectReader... readers); public ObjectReader withFormatDetection(DataFormatReaders readers); public ObjectReader with(ContextAttributes attrs); public ObjectReader withAttributes(Map<?,?> attrs); public ObjectReader withAttribute(Object key, Object value); public ObjectReader withoutAttribute(Object key); protected ObjectReader _with(DeserializationConfig newConfig); public boolean isEnabled(DeserializationFeature f); public boolean isEnabled(MapperFeature f); public boolean isEnabled(JsonParser.Feature f); public DeserializationConfig getConfig(); @Override public JsonFactory getFactory(); public TypeFactory getTypeFactory(); public ContextAttributes getAttributes(); public InjectableValues getInjectableValues(); @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p) throws IOException; @SuppressWarnings("unchecked") @Override public <T> T readValue(JsonParser p, Class<T> valueType) throws IOException; @SuppressWarnings("unchecked") @Override public <T> T readValue(JsonParser p, TypeReference<?> valueTypeRef) throws IOException; @Override @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p, ResolvedType valueType) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p, JavaType valueType) throws IOException; @Override public <T> Iterator<T> readValues(JsonParser p, Class<T> valueType) throws IOException; @Override public <T> Iterator<T> readValues(JsonParser p, TypeReference<?> valueTypeRef) throws IOException; @Override public <T> Iterator<T> readValues(JsonParser p, ResolvedType valueType) throws IOException; public <T> Iterator<T> readValues(JsonParser p, JavaType valueType) throws IOException; @Override public JsonNode createArrayNode(); @Override public JsonNode createObjectNode(); @Override public JsonParser treeAsTokens(TreeNode n); @SuppressWarnings("unchecked") @Override public <T extends TreeNode> T readTree(JsonParser p) throws IOException; @Override public void writeTree(JsonGenerator g, TreeNode rootNode); @SuppressWarnings("unchecked") public <T> T readValue(InputStream src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(String src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(File src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(URL src) throws IOException; @SuppressWarnings({ "unchecked", "resource" }) public <T> T readValue(JsonNode src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src) throws IOException; public JsonNode readTree(InputStream in) throws IOException; public JsonNode readTree(Reader r) throws IOException; public JsonNode readTree(String json) throws IOException; public JsonNode readTree(DataInput src) throws IOException; public <T> MappingIterator<T> readValues(JsonParser p) throws IOException; public <T> MappingIterator<T> readValues(InputStream src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(String json) throws IOException; public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException; public final <T> MappingIterator<T> readValues(byte[] src) throws IOException; public <T> MappingIterator<T> readValues(File src) throws IOException; public <T> MappingIterator<T> readValues(URL src) throws IOException; public <T> MappingIterator<T> readValues(DataInput src) throws IOException; @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; @Override public void writeValue(JsonGenerator gen, Object value) throws IOException; protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; protected Object _bindAndClose(JsonParser p0) throws IOException; protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; protected final JsonNode _bindAsTree(JsonParser p) throws IOException; protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) throws JsonProcessingException; protected void _verifySchemaType(FormatSchema schema); protected DefaultDeserializationContext createDeserializationContext(JsonParser p); protected InputStream _inputStream(URL src) throws IOException; protected InputStream _inputStream(File f) throws IOException; protected void _reportUndetectableSource(Object src) throws JsonProcessingException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType);
268
testTreeToValue
```java @Override public void writeTree(JsonGenerator g, TreeNode rootNode); @SuppressWarnings("unchecked") public <T> T readValue(InputStream src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(String src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(File src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(URL src) throws IOException; @SuppressWarnings({ "unchecked", "resource" }) public <T> T readValue(JsonNode src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src) throws IOException; public JsonNode readTree(InputStream in) throws IOException; public JsonNode readTree(Reader r) throws IOException; public JsonNode readTree(String json) throws IOException; public JsonNode readTree(DataInput src) throws IOException; public <T> MappingIterator<T> readValues(JsonParser p) throws IOException; public <T> MappingIterator<T> readValues(InputStream src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(String json) throws IOException; public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException; public final <T> MappingIterator<T> readValues(byte[] src) throws IOException; public <T> MappingIterator<T> readValues(File src) throws IOException; public <T> MappingIterator<T> readValues(URL src) throws IOException; public <T> MappingIterator<T> readValues(DataInput src) throws IOException; @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; @Override public void writeValue(JsonGenerator gen, Object value) throws IOException; protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; protected Object _bindAndClose(JsonParser p0) throws IOException; protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; protected final JsonNode _bindAsTree(JsonParser p) throws IOException; protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) throws JsonProcessingException; protected void _verifySchemaType(FormatSchema schema); protected DefaultDeserializationContext createDeserializationContext(JsonParser p); protected InputStream _inputStream(URL src) throws IOException; protected InputStream _inputStream(File f) throws IOException; protected void _reportUndetectableSource(Object src) throws JsonProcessingException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectReaderTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleViaParser() throws Exception; public void testSimpleAltSources() throws Exception; public void testParserFeatures() throws Exception; public void testNodeHandling() throws Exception; public void testFeatureSettings() throws Exception; public void testMiscSettings() throws Exception; @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception; public void testNoPrefetch() throws Exception; public void testNoPointerLoading() throws Exception; public void testPointerLoading() throws Exception; public void testPointerLoadingAsJsonNode() throws Exception; public void testPointerLoadingMappingIteratorOne() throws Exception; public void testPointerLoadingMappingIteratorMany() throws Exception; public void testPointerWithArrays() throws Exception; public void testTreeToValue() throws Exception; public void testCodecUnsupportedWrites() throws Exception; public void testMissingType() throws Exception; public void testSchema() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testTreeToValue` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, ObjectCodec /********************************************************** */
261
// @Override // public void writeTree(JsonGenerator g, TreeNode rootNode); // @SuppressWarnings("unchecked") // public <T> T readValue(InputStream src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(Reader src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(String src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src) throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(byte[] src, int offset, int length) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(File src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(URL src) // throws IOException; // @SuppressWarnings({ "unchecked", "resource" }) // public <T> T readValue(JsonNode src) // throws IOException; // @SuppressWarnings("unchecked") // public <T> T readValue(DataInput src) throws IOException; // public JsonNode readTree(InputStream in) throws IOException; // public JsonNode readTree(Reader r) throws IOException; // public JsonNode readTree(String json) throws IOException; // public JsonNode readTree(DataInput src) throws IOException; // public <T> MappingIterator<T> readValues(JsonParser p) // throws IOException; // public <T> MappingIterator<T> readValues(InputStream src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(Reader src) // throws IOException; // @SuppressWarnings("resource") // public <T> MappingIterator<T> readValues(String json) // throws IOException; // public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) // throws IOException; // public final <T> MappingIterator<T> readValues(byte[] src) // throws IOException; // public <T> MappingIterator<T> readValues(File src) // throws IOException; // public <T> MappingIterator<T> readValues(URL src) // throws IOException; // public <T> MappingIterator<T> readValues(DataInput src) throws IOException; // @Override // public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; // @Override // public void writeValue(JsonGenerator gen, Object value) throws IOException; // protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; // protected Object _bindAndClose(JsonParser p0) throws IOException; // protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; // protected final JsonNode _bindAsTree(JsonParser p) throws IOException; // protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; // protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, // JavaType rootType, JsonDeserializer<Object> deser) throws IOException; // protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); // protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, // JavaType bindType) // throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; // @SuppressWarnings("resource") // protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) // throws IOException; // @SuppressWarnings("resource") // protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; // protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) // throws JsonProcessingException; // protected void _verifySchemaType(FormatSchema schema); // protected DefaultDeserializationContext createDeserializationContext(JsonParser p); // protected InputStream _inputStream(URL src) throws IOException; // protected InputStream _inputStream(File f) throws IOException; // protected void _reportUndetectableSource(Object src) throws JsonProcessingException; // protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) // throws JsonMappingException; // protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.StringWriter; // import java.util.Collections; // import java.util.List; // import java.util.Map; // import java.util.Set; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.databind.cfg.ContextAttributes; // import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; // import com.fasterxml.jackson.databind.node.ArrayNode; // import com.fasterxml.jackson.databind.node.JsonNodeFactory; // import com.fasterxml.jackson.databind.node.ObjectNode; // // // // public class ObjectReaderTest extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testSimpleViaParser() throws Exception; // public void testSimpleAltSources() throws Exception; // public void testParserFeatures() throws Exception; // public void testNodeHandling() throws Exception; // public void testFeatureSettings() throws Exception; // public void testMiscSettings() throws Exception; // @SuppressWarnings("deprecation") // public void testDeprecatedSettings() throws Exception; // public void testNoPrefetch() throws Exception; // public void testNoPointerLoading() throws Exception; // public void testPointerLoading() throws Exception; // public void testPointerLoadingAsJsonNode() throws Exception; // public void testPointerLoadingMappingIteratorOne() throws Exception; // public void testPointerLoadingMappingIteratorMany() throws Exception; // public void testPointerWithArrays() throws Exception; // public void testTreeToValue() throws Exception; // public void testCodecUnsupportedWrites() throws Exception; // public void testMissingType() throws Exception; // public void testSchema() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testTreeToValue` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, ObjectCodec /********************************************************** */ public void testTreeToValue() throws Exception {
/* /********************************************************** /* Test methods, ObjectCodec /********************************************************** */
112
com.fasterxml.jackson.databind.ObjectReader
src/test/java
```java @Override public void writeTree(JsonGenerator g, TreeNode rootNode); @SuppressWarnings("unchecked") public <T> T readValue(InputStream src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(String src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(File src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(URL src) throws IOException; @SuppressWarnings({ "unchecked", "resource" }) public <T> T readValue(JsonNode src) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src) throws IOException; public JsonNode readTree(InputStream in) throws IOException; public JsonNode readTree(Reader r) throws IOException; public JsonNode readTree(String json) throws IOException; public JsonNode readTree(DataInput src) throws IOException; public <T> MappingIterator<T> readValues(JsonParser p) throws IOException; public <T> MappingIterator<T> readValues(InputStream src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException; @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(String json) throws IOException; public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException; public final <T> MappingIterator<T> readValues(byte[] src) throws IOException; public <T> MappingIterator<T> readValues(File src) throws IOException; public <T> MappingIterator<T> readValues(URL src) throws IOException; public <T> MappingIterator<T> readValues(DataInput src) throws IOException; @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; @Override public void writeValue(JsonGenerator gen, Object value) throws IOException; protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException; protected Object _bindAndClose(JsonParser p0) throws IOException; protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException; protected final JsonNode _bindAsTree(JsonParser p) throws IOException; protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected JsonParser _considerFilter(final JsonParser p, boolean multiValue); protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException; @SuppressWarnings("resource") protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing) throws IOException; @SuppressWarnings("resource") protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException; protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match) throws JsonProcessingException; protected void _verifySchemaType(FormatSchema schema); protected DefaultDeserializationContext createDeserializationContext(JsonParser p); protected InputStream _inputStream(URL src) throws IOException; protected InputStream _inputStream(File f) throws IOException; protected void _reportUndetectableSource(Object src) throws JsonProcessingException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt) throws JsonMappingException; protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType); } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectReaderTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleViaParser() throws Exception; public void testSimpleAltSources() throws Exception; public void testParserFeatures() throws Exception; public void testNodeHandling() throws Exception; public void testFeatureSettings() throws Exception; public void testMiscSettings() throws Exception; @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception; public void testNoPrefetch() throws Exception; public void testNoPointerLoading() throws Exception; public void testPointerLoading() throws Exception; public void testPointerLoadingAsJsonNode() throws Exception; public void testPointerLoadingMappingIteratorOne() throws Exception; public void testPointerLoadingMappingIteratorMany() throws Exception; public void testPointerWithArrays() throws Exception; public void testTreeToValue() throws Exception; public void testCodecUnsupportedWrites() throws Exception; public void testMissingType() throws Exception; public void testSchema() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testTreeToValue` for the `ObjectReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, ObjectCodec /********************************************************** */ public void testTreeToValue() throws Exception { ```
public class ObjectReader extends ObjectCodec implements Versioned, java.io.Serializable // since 2.1
package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode;
public void testSimpleViaParser() throws Exception; public void testSimpleAltSources() throws Exception; public void testParserFeatures() throws Exception; public void testNodeHandling() throws Exception; public void testFeatureSettings() throws Exception; public void testMiscSettings() throws Exception; @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception; public void testNoPrefetch() throws Exception; public void testNoPointerLoading() throws Exception; public void testPointerLoading() throws Exception; public void testPointerLoadingAsJsonNode() throws Exception; public void testPointerLoadingMappingIteratorOne() throws Exception; public void testPointerLoadingMappingIteratorMany() throws Exception; public void testPointerWithArrays() throws Exception; public void testTreeToValue() throws Exception; public void testCodecUnsupportedWrites() throws Exception; public void testMissingType() throws Exception; public void testSchema() throws Exception;
efb2fe8592566ccfa3656439cb33dde777d7c84d8ea27103cd2dbd7674afaef7
[ "com.fasterxml.jackson.databind.ObjectReaderTest::testTreeToValue" ]
private static final long serialVersionUID = 2L; private final static JavaType JSON_NODE_TYPE = SimpleType.constructUnsafe(JsonNode.class); protected final DeserializationConfig _config; protected final DefaultDeserializationContext _context; protected final JsonFactory _parserFactory; protected final boolean _unwrapRoot; private final TokenFilter _filter; protected final JavaType _valueType; protected final JsonDeserializer<Object> _rootDeserializer; protected final Object _valueToUpdate; protected final FormatSchema _schema; protected final InjectableValues _injectableValues; protected final DataFormatReaders _dataFormatReaders; final protected ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers;
public void testTreeToValue() throws Exception
final ObjectMapper MAPPER = new ObjectMapper();
JacksonDatabind
package com.fasterxml.jackson.databind; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.cfg.ContextAttributes; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; public class ObjectReaderTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); static class POJO { public Map<String, Object> name; } public void testSimpleViaParser() throws Exception { final String JSON = "[1]"; JsonParser p = MAPPER.getFactory().createParser(JSON); Object ob = MAPPER.readerFor(Object.class) .readValue(p); p.close(); assertTrue(ob instanceof List<?>); } public void testSimpleAltSources() throws Exception { final String JSON = "[1]"; final byte[] BYTES = JSON.getBytes("UTF-8"); Object ob = MAPPER.readerFor(Object.class) .readValue(BYTES); assertTrue(ob instanceof List<?>); ob = MAPPER.readerFor(Object.class) .readValue(BYTES, 0, BYTES.length); assertTrue(ob instanceof List<?>); assertEquals(1, ((List<?>) ob).size()); } public void testParserFeatures() throws Exception { final String JSON = "[ /* foo */ 7 ]"; // default won't accept comments, let's change that: ObjectReader reader = MAPPER.readerFor(int[].class) .with(JsonParser.Feature.ALLOW_COMMENTS); int[] value = reader.readValue(JSON); assertNotNull(value); assertEquals(1, value.length); assertEquals(7, value[0]); // but also can go back try { reader.without(JsonParser.Feature.ALLOW_COMMENTS).readValue(JSON); fail("Should not have passed"); } catch (JsonProcessingException e) { verifyException(e, "foo"); } } public void testNodeHandling() throws Exception { JsonNodeFactory nodes = new JsonNodeFactory(true); ObjectReader r = MAPPER.reader().with(nodes); // but also no further changes if attempting again assertSame(r, r.with(nodes)); assertTrue(r.createArrayNode().isArray()); assertTrue(r.createObjectNode().isObject()); } public void testFeatureSettings() throws Exception { ObjectReader r = MAPPER.reader(); assertFalse(r.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)); assertFalse(r.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); r = r.withoutFeatures(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, DeserializationFeature.FAIL_ON_INVALID_SUBTYPE); assertFalse(r.isEnabled(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)); assertFalse(r.isEnabled(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)); r = r.withFeatures(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, DeserializationFeature.FAIL_ON_INVALID_SUBTYPE); assertTrue(r.isEnabled(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)); assertTrue(r.isEnabled(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)); // alternative method too... can't recall why two assertSame(r, r.with(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)); } public void testMiscSettings() throws Exception { ObjectReader r = MAPPER.reader(); assertSame(MAPPER.getFactory(), r.getFactory()); JsonFactory f = new JsonFactory(); r = r.with(f); assertSame(f, r.getFactory()); assertSame(r, r.with(f)); assertNotNull(r.getTypeFactory()); assertNull(r.getInjectableValues()); r = r.withAttributes(Collections.emptyMap()); ContextAttributes attrs = r.getAttributes(); assertNotNull(attrs); assertNull(attrs.getAttribute("abc")); assertSame(r, r.withoutAttribute("foo")); ObjectReader newR = r.forType(MAPPER.constructType(String.class)); assertNotSame(r, newR); assertSame(newR, newR.forType(String.class)); DeserializationProblemHandler probH = new DeserializationProblemHandler() { }; newR = r.withHandler(probH); assertNotSame(r, newR); assertSame(newR, newR.withHandler(probH)); r = newR; } @SuppressWarnings("deprecation") public void testDeprecatedSettings() throws Exception { ObjectReader r = MAPPER.reader(); // and deprecated variants ObjectReader newR = r.forType(MAPPER.constructType(String.class)); assertSame(newR, newR.withType(String.class)); assertSame(newR, newR.withType(MAPPER.constructType(String.class))); newR = newR.withRootName(PropertyName.construct("foo")); assertNotSame(r, newR); assertSame(newR, newR.withRootName(PropertyName.construct("foo"))); } public void testNoPrefetch() throws Exception { ObjectReader r = MAPPER.reader() .without(DeserializationFeature.EAGER_DESERIALIZER_FETCH); Number n = r.forType(Integer.class).readValue("123 "); assertEquals(Integer.valueOf(123), n); } /* /********************************************************** /* Test methods, JsonPointer /********************************************************** */ public void testNoPointerLoading() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; JsonNode tree = MAPPER.readTree(source); JsonNode node = tree.at("/foo/bar/caller"); POJO pojo = MAPPER.treeToValue(node, POJO.class); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); } public void testPointerLoading() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at("/foo/bar/caller"); POJO pojo = reader.readValue(source); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); } public void testPointerLoadingAsJsonNode() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at(JsonPointer.compile("/foo/bar/caller")); JsonNode node = reader.readTree(source); assertTrue(node.has("name")); assertEquals("{\"value\":1234}", node.get("name").toString()); } public void testPointerLoadingMappingIteratorOne() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":{\"name\":{\"value\":1234}}}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at("/foo/bar/caller"); MappingIterator<POJO> itr = reader.readValues(source); POJO pojo = itr.next(); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); assertFalse(itr.hasNext()); itr.close(); } public void testPointerLoadingMappingIteratorMany() throws Exception { final String source = "{\"foo\":{\"bar\":{\"caller\":[{\"name\":{\"value\":1234}}, {\"name\":{\"value\":5678}}]}}}"; ObjectReader reader = MAPPER.readerFor(POJO.class).at("/foo/bar/caller"); MappingIterator<POJO> itr = reader.readValues(source); POJO pojo = itr.next(); assertTrue(pojo.name.containsKey("value")); assertEquals(1234, pojo.name.get("value")); assertTrue(itr.hasNext()); pojo = itr.next(); assertNotNull(pojo.name); assertTrue(pojo.name.containsKey("value")); assertEquals(5678, pojo.name.get("value")); assertFalse(itr.hasNext()); itr.close(); } // [databind#1637] public void testPointerWithArrays() throws Exception { final String json = aposToQuotes("{\n'wrapper1': {\n" + " 'set1': ['one', 'two', 'three'],\n" + " 'set2': ['four', 'five', 'six']\n" + "},\n" + "'wrapper2': {\n" + " 'set1': ['one', 'two', 'three'],\n" + " 'set2': ['four', 'five', 'six']\n" + "}\n}"); final Pojo1637 testObject = MAPPER.readerFor(Pojo1637.class) .at("/wrapper1") .readValue(json); assertNotNull(testObject); assertNotNull(testObject.set1); assertTrue(!testObject.set1.isEmpty()); assertNotNull(testObject.set2); assertTrue(!testObject.set2.isEmpty()); } public static class Pojo1637 { public Set<String> set1; public Set<String> set2; } /* /********************************************************** /* Test methods, ObjectCodec /********************************************************** */ public void testTreeToValue() throws Exception { ArrayNode n = MAPPER.createArrayNode(); n.add("xyz"); ObjectReader r = MAPPER.readerFor(String.class); List<?> list = r.treeToValue(n, List.class); assertEquals(1, list.size()); } public void testCodecUnsupportedWrites() throws Exception { ObjectReader r = MAPPER.readerFor(String.class); JsonGenerator g = MAPPER.getFactory().createGenerator(new StringWriter()); ObjectNode n = MAPPER.createObjectNode(); try { r.writeTree(g, n); fail("Should not pass"); } catch (UnsupportedOperationException e) { ; } try { r.writeValue(g, "Foo"); fail("Should not pass"); } catch (UnsupportedOperationException e) { ; } g.close(); g.close(); } /* /********************************************************** /* Test methods, failures, other /********************************************************** */ public void testMissingType() throws Exception { ObjectReader r = MAPPER.reader(); try { r.readValue("1"); fail("Should not pass"); } catch (JsonMappingException e) { verifyException(e, "No value type configured"); } } public void testSchema() throws Exception { ObjectReader r = MAPPER.readerFor(String.class); // Ok to try to set `null` schema, always: r = r.with((FormatSchema) null); try { // but not schema that doesn't match format (no schema exists for json) r = r.with(new BogusSchema()) .readValue(quote("foo")); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "Cannot use FormatSchema"); } } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_bind", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser;Ljava/lang/Object;)Ljava/lang/Object;", "line_numbers": [ "1558", "1559", "1560", "1561", "1562", "1564", "1566", "1567", "1569", "1570", "1571", "1573", "1574", "1578", "1583", "1584", "1585", "1587" ], "method_line_rate": 0.6111111111111112 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_findRootDeserializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/DeserializationContext;)Lcom/fasterxml/jackson/databind/JsonDeserializer;", "line_numbers": [ "1879", "1880", "1884", "1885", "1886", "1890", "1891", "1892", "1895", "1896", "1897", "1899", "1900" ], "method_line_rate": 0.15384615384615385 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_initForReading", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/DeserializationContext;Lcom/fasterxml/jackson/core/JsonParser;)Lcom/fasterxml/jackson/core/JsonToken;", "line_numbers": [ "344", "345", "347", "353", "354", "355", "356", "358", "362" ], "method_line_rate": 0.7777777777777778 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_new", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/ObjectReader;Lcom/fasterxml/jackson/databind/DeserializationConfig;Lcom/fasterxml/jackson/databind/JavaType;Lcom/fasterxml/jackson/databind/JsonDeserializer;Ljava/lang/Object;Lcom/fasterxml/jackson/core/FormatSchema;Lcom/fasterxml/jackson/databind/InjectableValues;Lcom/fasterxml/jackson/databind/deser/DataFormatReaders;)Lcom/fasterxml/jackson/databind/ObjectReader;", "line_numbers": [ "318" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "_prefetchRootDeserializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JsonDeserializer;", "line_numbers": [ "1929", "1930", "1933", "1934", "1937", "1938", "1939", "1940", "1942", "1943", "1947" ], "method_line_rate": 0.7272727272727273 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "createDeserializationContext", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser;)Lcom/fasterxml/jackson/databind/deser/DefaultDeserializationContext;", "line_numbers": [ "1849" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "forType", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/ObjectReader;", "line_numbers": [ "674", "675", "677", "679", "680", "681", "683" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "forType", "be_test_function_signature": "(Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/ObjectReader;", "line_numbers": [ "697" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "readValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser;)Ljava/lang/Object;", "line_numbers": [ "965" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "readValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonParser;Ljava/lang/Class;)Ljava/lang/Object;", "line_numbers": [ "982" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "treeAsTokens", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/TreeNode;)Lcom/fasterxml/jackson/core/JsonParser;", "line_numbers": [ "1144", "1145" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "treeToValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/TreeNode;Ljava/lang/Class;)Ljava/lang/Object;", "line_numbers": [ "1530", "1531", "1532", "1533", "1534" ], "method_line_rate": 0.2 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectReader.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectReader", "be_test_function_name": "withValueToUpdate", "be_test_function_signature": "(Ljava/lang/Object;)Lcom/fasterxml/jackson/databind/ObjectReader;", "line_numbers": [ "755", "756", "759", "768", "769", "771", "773" ], "method_line_rate": 0.14285714285714285 } ]
public final class LaguerreSolverTest
@Test public void testQuinticFunction2() { // p(x) = x^5 + 4x^3 + x^2 + 4 = (x+1)(x^2-x+1)(x^2+4) final double[] coefficients = { 4.0, 0.0, 1.0, 4.0, 0.0, 1.0 }; final LaguerreSolver solver = new LaguerreSolver(); final Complex[] result = solver.solveAllComplex(coefficients, 0); for (Complex expected : new Complex[] { new Complex(0, -2), new Complex(0, 2), new Complex(0.5, 0.5 * FastMath.sqrt(3)), new Complex(-1, 0), new Complex(0.5, -0.5 * FastMath.sqrt(3.0)) }) { final double tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected.abs() * solver.getRelativeAccuracy())); TestUtils.assertContains(result, expected, tolerance); } }
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.solvers; // // import org.apache.commons.math3.complex.Complex; // import org.apache.commons.math3.complex.ComplexUtils; // import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; // import org.apache.commons.math3.exception.NoBracketingException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.TooManyEvaluationsException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.util.FastMath; // // // // public class LaguerreSolver extends AbstractPolynomialSolver { // private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; // private final ComplexSolver complexSolver = new ComplexSolver(); // // public LaguerreSolver(); // public LaguerreSolver(double absoluteAccuracy); // public LaguerreSolver(double relativeAccuracy, // double absoluteAccuracy); // public LaguerreSolver(double relativeAccuracy, // double absoluteAccuracy, // double functionValueAccuracy); // @Override // public double doSolve() // throws TooManyEvaluationsException, // NumberIsTooLargeException, // NoBracketingException; // @Deprecated // public double laguerre(double lo, double hi, // double fLo, double fHi); // public Complex[] solveAllComplex(double[] coefficients, // double initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // public Complex solveComplex(double[] coefficients, // double initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // public boolean isRoot(double min, double max, Complex z); // public Complex[] solveAll(Complex coefficients[], Complex initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // public Complex solve(Complex coefficients[], Complex initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.solvers; // // import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.NoBracketingException; // import org.apache.commons.math3.complex.Complex; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.TestUtils; // import org.junit.Assert; // import org.junit.Test; // // // // public final class LaguerreSolverTest { // // // @Test // public void testLinearFunction(); // @Test // public void testQuadraticFunction(); // @Test // public void testQuinticFunction(); // @Test // public void testQuinticFunction2(); // @Test // public void testParameters(); // } // You are a professional Java test case writer, please create a test case named `testQuinticFunction2` for the `LaguerreSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of solver for the quintic function using * {@link LaguerreSolver#solveAllComplex(double[],double) solveAllComplex}. */
src/test/java/org/apache/commons/math3/analysis/solvers/LaguerreSolverTest.java
package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.complex.ComplexUtils; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath;
public LaguerreSolver(); public LaguerreSolver(double absoluteAccuracy); public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy); public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy, double functionValueAccuracy); @Override public double doSolve() throws TooManyEvaluationsException, NumberIsTooLargeException, NoBracketingException; @Deprecated public double laguerre(double lo, double hi, double fLo, double fHi); public Complex[] solveAllComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public Complex solveComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public boolean isRoot(double min, double max, Complex z); public Complex[] solveAll(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public Complex solve(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException;
133
testQuinticFunction2
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.complex.ComplexUtils; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; public class LaguerreSolver extends AbstractPolynomialSolver { private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; private final ComplexSolver complexSolver = new ComplexSolver(); public LaguerreSolver(); public LaguerreSolver(double absoluteAccuracy); public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy); public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy, double functionValueAccuracy); @Override public double doSolve() throws TooManyEvaluationsException, NumberIsTooLargeException, NoBracketingException; @Deprecated public double laguerre(double lo, double hi, double fLo, double fHi); public Complex[] solveAllComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public Complex solveComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public boolean isRoot(double min, double max, Complex z); public Complex[] solveAll(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public Complex solve(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.TestUtils; import org.junit.Assert; import org.junit.Test; public final class LaguerreSolverTest { @Test public void testLinearFunction(); @Test public void testQuadraticFunction(); @Test public void testQuinticFunction(); @Test public void testQuinticFunction2(); @Test public void testParameters(); } ``` You are a professional Java test case writer, please create a test case named `testQuinticFunction2` for the `LaguerreSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of solver for the quintic function using * {@link LaguerreSolver#solveAllComplex(double[],double) solveAllComplex}. */
117
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.solvers; // // import org.apache.commons.math3.complex.Complex; // import org.apache.commons.math3.complex.ComplexUtils; // import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; // import org.apache.commons.math3.exception.NoBracketingException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.TooManyEvaluationsException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.util.FastMath; // // // // public class LaguerreSolver extends AbstractPolynomialSolver { // private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; // private final ComplexSolver complexSolver = new ComplexSolver(); // // public LaguerreSolver(); // public LaguerreSolver(double absoluteAccuracy); // public LaguerreSolver(double relativeAccuracy, // double absoluteAccuracy); // public LaguerreSolver(double relativeAccuracy, // double absoluteAccuracy, // double functionValueAccuracy); // @Override // public double doSolve() // throws TooManyEvaluationsException, // NumberIsTooLargeException, // NoBracketingException; // @Deprecated // public double laguerre(double lo, double hi, // double fLo, double fHi); // public Complex[] solveAllComplex(double[] coefficients, // double initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // public Complex solveComplex(double[] coefficients, // double initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // public boolean isRoot(double min, double max, Complex z); // public Complex[] solveAll(Complex coefficients[], Complex initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // public Complex solve(Complex coefficients[], Complex initial) // throws NullArgumentException, // NoDataException, // TooManyEvaluationsException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.solvers; // // import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.NoBracketingException; // import org.apache.commons.math3.complex.Complex; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.TestUtils; // import org.junit.Assert; // import org.junit.Test; // // // // public final class LaguerreSolverTest { // // // @Test // public void testLinearFunction(); // @Test // public void testQuadraticFunction(); // @Test // public void testQuinticFunction(); // @Test // public void testQuinticFunction2(); // @Test // public void testParameters(); // } // You are a professional Java test case writer, please create a test case named `testQuinticFunction2` for the `LaguerreSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of solver for the quintic function using * {@link LaguerreSolver#solveAllComplex(double[],double) solveAllComplex}. */ @Test public void testQuinticFunction2() {
/** * Test of solver for the quintic function using * {@link LaguerreSolver#solveAllComplex(double[],double) solveAllComplex}. */
1
org.apache.commons.math3.analysis.solvers.LaguerreSolver
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.complex.ComplexUtils; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; public class LaguerreSolver extends AbstractPolynomialSolver { private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; private final ComplexSolver complexSolver = new ComplexSolver(); public LaguerreSolver(); public LaguerreSolver(double absoluteAccuracy); public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy); public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy, double functionValueAccuracy); @Override public double doSolve() throws TooManyEvaluationsException, NumberIsTooLargeException, NoBracketingException; @Deprecated public double laguerre(double lo, double hi, double fLo, double fHi); public Complex[] solveAllComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public Complex solveComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public boolean isRoot(double min, double max, Complex z); public Complex[] solveAll(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; public Complex solve(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.TestUtils; import org.junit.Assert; import org.junit.Test; public final class LaguerreSolverTest { @Test public void testLinearFunction(); @Test public void testQuadraticFunction(); @Test public void testQuinticFunction(); @Test public void testQuinticFunction2(); @Test public void testParameters(); } ``` You are a professional Java test case writer, please create a test case named `testQuinticFunction2` for the `LaguerreSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of solver for the quintic function using * {@link LaguerreSolver#solveAllComplex(double[],double) solveAllComplex}. */ @Test public void testQuinticFunction2() { ```
public class LaguerreSolver extends AbstractPolynomialSolver
package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.TestUtils; import org.junit.Assert; import org.junit.Test;
@Test public void testLinearFunction(); @Test public void testQuadraticFunction(); @Test public void testQuinticFunction(); @Test public void testQuinticFunction2(); @Test public void testParameters();
f02f7a1ff35a21c356ba0813730422903693d725b75f0670976e02ad78aca237
[ "org.apache.commons.math3.analysis.solvers.LaguerreSolverTest::testQuinticFunction2" ]
private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; private final ComplexSolver complexSolver = new ComplexSolver();
@Test public void testQuinticFunction2()
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.TestUtils; import org.junit.Assert; import org.junit.Test; /** * Test case for Laguerre solver. * <p> * Laguerre's method is very efficient in solving polynomials. Test runs * show that for a default absolute accuracy of 1E-6, it generally takes * less than 5 iterations to find one root, provided solveAll() is not * invoked, and 15 to 20 iterations to find all roots for quintic function. * * @version $Id$ */ public final class LaguerreSolverTest { /** * Test of solver for the linear function. */ @Test public void testLinearFunction() { double min, max, expected, result, tolerance; // p(x) = 4x - 1 double coefficients[] = { -1.0, 4.0 }; PolynomialFunction f = new PolynomialFunction(coefficients); LaguerreSolver solver = new LaguerreSolver(); min = 0.0; max = 1.0; expected = 0.25; tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected * solver.getRelativeAccuracy())); result = solver.solve(100, f, min, max); Assert.assertEquals(expected, result, tolerance); } /** * Test of solver for the quadratic function. */ @Test public void testQuadraticFunction() { double min, max, expected, result, tolerance; // p(x) = 2x^2 + 5x - 3 = (x+3)(2x-1) double coefficients[] = { -3.0, 5.0, 2.0 }; PolynomialFunction f = new PolynomialFunction(coefficients); LaguerreSolver solver = new LaguerreSolver(); min = 0.0; max = 2.0; expected = 0.5; tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected * solver.getRelativeAccuracy())); result = solver.solve(100, f, min, max); Assert.assertEquals(expected, result, tolerance); min = -4.0; max = -1.0; expected = -3.0; tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected * solver.getRelativeAccuracy())); result = solver.solve(100, f, min, max); Assert.assertEquals(expected, result, tolerance); } /** * Test of solver for the quintic function. */ @Test public void testQuinticFunction() { double min, max, expected, result, tolerance; // p(x) = x^5 - x^4 - 12x^3 + x^2 - x - 12 = (x+1)(x+3)(x-4)(x^2-x+1) double coefficients[] = { -12.0, -1.0, 1.0, -12.0, -1.0, 1.0 }; PolynomialFunction f = new PolynomialFunction(coefficients); LaguerreSolver solver = new LaguerreSolver(); min = -2.0; max = 2.0; expected = -1.0; tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected * solver.getRelativeAccuracy())); result = solver.solve(100, f, min, max); Assert.assertEquals(expected, result, tolerance); min = -5.0; max = -2.5; expected = -3.0; tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected * solver.getRelativeAccuracy())); result = solver.solve(100, f, min, max); Assert.assertEquals(expected, result, tolerance); min = 3.0; max = 6.0; expected = 4.0; tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected * solver.getRelativeAccuracy())); result = solver.solve(100, f, min, max); Assert.assertEquals(expected, result, tolerance); } /** * Test of solver for the quintic function using * {@link LaguerreSolver#solveAllComplex(double[],double) solveAllComplex}. */ @Test public void testQuinticFunction2() { // p(x) = x^5 + 4x^3 + x^2 + 4 = (x+1)(x^2-x+1)(x^2+4) final double[] coefficients = { 4.0, 0.0, 1.0, 4.0, 0.0, 1.0 }; final LaguerreSolver solver = new LaguerreSolver(); final Complex[] result = solver.solveAllComplex(coefficients, 0); for (Complex expected : new Complex[] { new Complex(0, -2), new Complex(0, 2), new Complex(0.5, 0.5 * FastMath.sqrt(3)), new Complex(-1, 0), new Complex(0.5, -0.5 * FastMath.sqrt(3.0)) }) { final double tolerance = FastMath.max(solver.getAbsoluteAccuracy(), FastMath.abs(expected.abs() * solver.getRelativeAccuracy())); TestUtils.assertContains(result, expected, tolerance); } } /** * Test of parameters for the solver. */ @Test public void testParameters() { double coefficients[] = { -3.0, 5.0, 2.0 }; PolynomialFunction f = new PolynomialFunction(coefficients); LaguerreSolver solver = new LaguerreSolver(); try { // bad interval solver.solve(100, f, 1, -1); Assert.fail("Expecting NumberIsTooLargeException - bad interval"); } catch (NumberIsTooLargeException ex) { // expected } try { // no bracketing solver.solve(100, f, 2, 3); Assert.fail("Expecting NoBracketingException - no bracketing"); } catch (NoBracketingException ex) { // expected } } }
[ { "be_test_class_file": "org/apache/commons/math3/analysis/solvers/LaguerreSolver.java", "be_test_class_name": "org.apache.commons.math3.analysis.solvers.LaguerreSolver", "be_test_function_name": "solveAllComplex", "be_test_function_signature": "([DD)[Lorg/apache/commons/math3/complex/Complex;", "line_numbers": [ "198", "203" ], "method_line_rate": 1 } ]
public class DateAxisTests extends TestCase
public void testPreviousStandardDateMillisecondB() { MyDateAxis axis = new MyDateAxis("Millisecond"); Millisecond m0 = new Millisecond(458, 58, 31, 12, 1, 4, 2007); Millisecond m1 = new Millisecond(459, 58, 31, 12, 1, 4, 2007); Date d0 = new Date(m0.getFirstMillisecond()); Date end = new Date(m1.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.MILLISECOND, 10); axis.setTickUnit(unit); // START: check d0 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); // MIDDLE: check d0 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d0, end); psd = axis.previousStandardDate(d0, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); // END: check d0 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d0, end); psd = axis.previousStandardDate(d0, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); }
// public double dateToJava2D(Date date, Rectangle2D area, // RectangleEdge edge); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // public Date calculateLowestVisibleTickValue(DateTickUnit unit); // public Date calculateHighestVisibleTickValue(DateTickUnit unit); // protected Date previousStandardDate(Date date, DateTickUnit unit); // private Date calculateDateForPosition(RegularTimePeriod period, // DateTickMarkPosition position); // protected Date nextStandardDate(Date date, DateTickUnit unit); // public static TickUnitSource createStandardDateTickUnits(); // public static TickUnitSource createStandardDateTickUnits(TimeZone zone); // public static TickUnitSource createStandardDateTickUnits(TimeZone zone, // Locale locale); // protected void autoAdjustRange(); // protected void selectAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, // RectangleEdge edge); // protected void selectHorizontalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // protected void selectVerticalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, // RectangleEdge edge); // private double estimateMaximumTickLabelWidth(Graphics2D g2, // DateTickUnit unit); // private double estimateMaximumTickLabelHeight(Graphics2D g2, // DateTickUnit unit); // public List refreshTicks(Graphics2D g2, // AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // private Date correctTickDateForPosition(Date time, DateTickUnit unit, // DateTickMarkPosition position); // protected List refreshTicksHorizontal(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // protected List refreshTicksVertical(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // public void zoomRange(double lowerPercent, double upperPercent); // public boolean equals(Object obj); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // public long toTimelineValue(long millisecond); // public long toTimelineValue(Date date); // public long toMillisecond(long value); // public boolean containsDomainValue(long millisecond); // public boolean containsDomainValue(Date date); // public boolean containsDomainRange(long from, long to); // public boolean containsDomainRange(Date from, Date to); // public boolean equals(Object object); // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.Graphics2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import java.text.SimpleDateFormat; // import java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.List; // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.axis.AxisState; // import org.jfree.chart.axis.DateAxis; // import org.jfree.chart.axis.DateTick; // import org.jfree.chart.axis.DateTickMarkPosition; // import org.jfree.chart.axis.DateTickUnit; // import org.jfree.chart.axis.DateTickUnitType; // import org.jfree.chart.axis.SegmentedTimeline; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.data.time.DateRange; // import org.jfree.data.time.Day; // import org.jfree.data.time.Hour; // import org.jfree.data.time.Millisecond; // import org.jfree.data.time.Month; // import org.jfree.data.time.Second; // import org.jfree.data.time.Year; // // // // public class DateAxisTests extends TestCase { // // // public static Test suite(); // public DateAxisTests(String name); // public void testEquals(); // public void test1472942(); // public void testHashCode(); // public void testCloning(); // public void testSetRange(); // public void testSetMaximumDate(); // public void testSetMinimumDate(); // private boolean same(double d1, double d2, double tolerance); // public void testJava2DToValue(); // public void testSerialization(); // public void testPreviousStandardDateYearA(); // public void testPreviousStandardDateYearB(); // public void testPreviousStandardDateMonthA(); // public void testPreviousStandardDateMonthB(); // public void testPreviousStandardDateDayA(); // public void testPreviousStandardDateDayB(); // public void testPreviousStandardDateHourA(); // public void testPreviousStandardDateHourB(); // public void testPreviousStandardDateSecondA(); // public void testPreviousStandardDateSecondB(); // public void testPreviousStandardDateMillisecondA(); // public void testPreviousStandardDateMillisecondB(); // public void testBug2201869(); // public MyDateAxis(String label); // public Date previousStandardDate(Date d, DateTickUnit unit); // } // You are a professional Java test case writer, please create a test case named `testPreviousStandardDateMillisecondB` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 milliseconds (just for the sake of having a multiple). */
tests/org/jfree/chart/axis/junit/DateAxisTests.java
package org.jfree.chart.axis; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueAxisPlot; import org.jfree.chart.text.TextAnchor; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.Range; import org.jfree.data.time.DateRange; import org.jfree.data.time.Month; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.Year;
public DateAxis(); public DateAxis(String label); public DateAxis(String label, TimeZone zone); public DateAxis(String label, TimeZone zone, Locale locale); public TimeZone getTimeZone(); public void setTimeZone(TimeZone zone); public Timeline getTimeline(); public void setTimeline(Timeline timeline); public DateTickUnit getTickUnit(); public void setTickUnit(DateTickUnit unit); public void setTickUnit(DateTickUnit unit, boolean notify, boolean turnOffAutoSelection); public DateFormat getDateFormatOverride(); public void setDateFormatOverride(DateFormat formatter); public void setRange(Range range); public void setRange(Range range, boolean turnOffAutoRange, boolean notify); public void setRange(Date lower, Date upper); public void setRange(double lower, double upper); public Date getMinimumDate(); public void setMinimumDate(Date date); public Date getMaximumDate(); public void setMaximumDate(Date maximumDate); public DateTickMarkPosition getTickMarkPosition(); public void setTickMarkPosition(DateTickMarkPosition position); public void configure(); public boolean isHiddenValue(long millis); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public double dateToJava2D(Date date, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); public Date calculateLowestVisibleTickValue(DateTickUnit unit); public Date calculateHighestVisibleTickValue(DateTickUnit unit); protected Date previousStandardDate(Date date, DateTickUnit unit); private Date calculateDateForPosition(RegularTimePeriod period, DateTickMarkPosition position); protected Date nextStandardDate(Date date, DateTickUnit unit); public static TickUnitSource createStandardDateTickUnits(); public static TickUnitSource createStandardDateTickUnits(TimeZone zone); public static TickUnitSource createStandardDateTickUnits(TimeZone zone, Locale locale); protected void autoAdjustRange(); protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectHorizontalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectVerticalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); private double estimateMaximumTickLabelWidth(Graphics2D g2, DateTickUnit unit); private double estimateMaximumTickLabelHeight(Graphics2D g2, DateTickUnit unit); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); private Date correctTickDateForPosition(Date time, DateTickUnit unit, DateTickMarkPosition position); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public void zoomRange(double lowerPercent, double upperPercent); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; public long toTimelineValue(long millisecond); public long toTimelineValue(Date date); public long toMillisecond(long value); public boolean containsDomainValue(long millisecond); public boolean containsDomainValue(Date date); public boolean containsDomainRange(long from, long to); public boolean containsDomainRange(Date from, Date to); public boolean equals(Object object);
1,145
testPreviousStandardDateMillisecondB
```java public double dateToJava2D(Date date, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); public Date calculateLowestVisibleTickValue(DateTickUnit unit); public Date calculateHighestVisibleTickValue(DateTickUnit unit); protected Date previousStandardDate(Date date, DateTickUnit unit); private Date calculateDateForPosition(RegularTimePeriod period, DateTickMarkPosition position); protected Date nextStandardDate(Date date, DateTickUnit unit); public static TickUnitSource createStandardDateTickUnits(); public static TickUnitSource createStandardDateTickUnits(TimeZone zone); public static TickUnitSource createStandardDateTickUnits(TimeZone zone, Locale locale); protected void autoAdjustRange(); protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectHorizontalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectVerticalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); private double estimateMaximumTickLabelWidth(Graphics2D g2, DateTickUnit unit); private double estimateMaximumTickLabelHeight(Graphics2D g2, DateTickUnit unit); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); private Date correctTickDateForPosition(Date time, DateTickUnit unit, DateTickMarkPosition position); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public void zoomRange(double lowerPercent, double upperPercent); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; public long toTimelineValue(long millisecond); public long toTimelineValue(Date date); public long toMillisecond(long value); public boolean containsDomainValue(long millisecond); public boolean containsDomainValue(Date date); public boolean containsDomainRange(long from, long to); public boolean containsDomainRange(Date from, Date to); public boolean equals(Object object); } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.DateTick; import org.jfree.chart.axis.DateTickMarkPosition; import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.chart.axis.SegmentedTimeline; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Millisecond; import org.jfree.data.time.Month; import org.jfree.data.time.Second; import org.jfree.data.time.Year; public class DateAxisTests extends TestCase { public static Test suite(); public DateAxisTests(String name); public void testEquals(); public void test1472942(); public void testHashCode(); public void testCloning(); public void testSetRange(); public void testSetMaximumDate(); public void testSetMinimumDate(); private boolean same(double d1, double d2, double tolerance); public void testJava2DToValue(); public void testSerialization(); public void testPreviousStandardDateYearA(); public void testPreviousStandardDateYearB(); public void testPreviousStandardDateMonthA(); public void testPreviousStandardDateMonthB(); public void testPreviousStandardDateDayA(); public void testPreviousStandardDateDayB(); public void testPreviousStandardDateHourA(); public void testPreviousStandardDateHourB(); public void testPreviousStandardDateSecondA(); public void testPreviousStandardDateSecondB(); public void testPreviousStandardDateMillisecondA(); public void testPreviousStandardDateMillisecondB(); public void testBug2201869(); public MyDateAxis(String label); public Date previousStandardDate(Date d, DateTickUnit unit); } ``` You are a professional Java test case writer, please create a test case named `testPreviousStandardDateMillisecondB` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 milliseconds (just for the sake of having a multiple). */
1,108
// public double dateToJava2D(Date date, Rectangle2D area, // RectangleEdge edge); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // public Date calculateLowestVisibleTickValue(DateTickUnit unit); // public Date calculateHighestVisibleTickValue(DateTickUnit unit); // protected Date previousStandardDate(Date date, DateTickUnit unit); // private Date calculateDateForPosition(RegularTimePeriod period, // DateTickMarkPosition position); // protected Date nextStandardDate(Date date, DateTickUnit unit); // public static TickUnitSource createStandardDateTickUnits(); // public static TickUnitSource createStandardDateTickUnits(TimeZone zone); // public static TickUnitSource createStandardDateTickUnits(TimeZone zone, // Locale locale); // protected void autoAdjustRange(); // protected void selectAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, // RectangleEdge edge); // protected void selectHorizontalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // protected void selectVerticalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, // RectangleEdge edge); // private double estimateMaximumTickLabelWidth(Graphics2D g2, // DateTickUnit unit); // private double estimateMaximumTickLabelHeight(Graphics2D g2, // DateTickUnit unit); // public List refreshTicks(Graphics2D g2, // AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // private Date correctTickDateForPosition(Date time, DateTickUnit unit, // DateTickMarkPosition position); // protected List refreshTicksHorizontal(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // protected List refreshTicksVertical(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // public void zoomRange(double lowerPercent, double upperPercent); // public boolean equals(Object obj); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // public long toTimelineValue(long millisecond); // public long toTimelineValue(Date date); // public long toMillisecond(long value); // public boolean containsDomainValue(long millisecond); // public boolean containsDomainValue(Date date); // public boolean containsDomainRange(long from, long to); // public boolean containsDomainRange(Date from, Date to); // public boolean equals(Object object); // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.Graphics2D; // import java.awt.geom.Rectangle2D; // import java.awt.image.BufferedImage; // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInput; // import java.io.ObjectInputStream; // import java.io.ObjectOutput; // import java.io.ObjectOutputStream; // import java.text.SimpleDateFormat; // import java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.List; // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.axis.AxisState; // import org.jfree.chart.axis.DateAxis; // import org.jfree.chart.axis.DateTick; // import org.jfree.chart.axis.DateTickMarkPosition; // import org.jfree.chart.axis.DateTickUnit; // import org.jfree.chart.axis.DateTickUnitType; // import org.jfree.chart.axis.SegmentedTimeline; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.data.time.DateRange; // import org.jfree.data.time.Day; // import org.jfree.data.time.Hour; // import org.jfree.data.time.Millisecond; // import org.jfree.data.time.Month; // import org.jfree.data.time.Second; // import org.jfree.data.time.Year; // // // // public class DateAxisTests extends TestCase { // // // public static Test suite(); // public DateAxisTests(String name); // public void testEquals(); // public void test1472942(); // public void testHashCode(); // public void testCloning(); // public void testSetRange(); // public void testSetMaximumDate(); // public void testSetMinimumDate(); // private boolean same(double d1, double d2, double tolerance); // public void testJava2DToValue(); // public void testSerialization(); // public void testPreviousStandardDateYearA(); // public void testPreviousStandardDateYearB(); // public void testPreviousStandardDateMonthA(); // public void testPreviousStandardDateMonthB(); // public void testPreviousStandardDateDayA(); // public void testPreviousStandardDateDayB(); // public void testPreviousStandardDateHourA(); // public void testPreviousStandardDateHourB(); // public void testPreviousStandardDateSecondA(); // public void testPreviousStandardDateSecondB(); // public void testPreviousStandardDateMillisecondA(); // public void testPreviousStandardDateMillisecondB(); // public void testBug2201869(); // public MyDateAxis(String label); // public Date previousStandardDate(Date d, DateTickUnit unit); // } // You are a professional Java test case writer, please create a test case named `testPreviousStandardDateMillisecondB` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 milliseconds (just for the sake of having a multiple). */ public void testPreviousStandardDateMillisecondB() {
/** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 milliseconds (just for the sake of having a multiple). */
1
org.jfree.chart.axis.DateAxis
tests
```java public double dateToJava2D(Date date, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); public Date calculateLowestVisibleTickValue(DateTickUnit unit); public Date calculateHighestVisibleTickValue(DateTickUnit unit); protected Date previousStandardDate(Date date, DateTickUnit unit); private Date calculateDateForPosition(RegularTimePeriod period, DateTickMarkPosition position); protected Date nextStandardDate(Date date, DateTickUnit unit); public static TickUnitSource createStandardDateTickUnits(); public static TickUnitSource createStandardDateTickUnits(TimeZone zone); public static TickUnitSource createStandardDateTickUnits(TimeZone zone, Locale locale); protected void autoAdjustRange(); protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectHorizontalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectVerticalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); private double estimateMaximumTickLabelWidth(Graphics2D g2, DateTickUnit unit); private double estimateMaximumTickLabelHeight(Graphics2D g2, DateTickUnit unit); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); private Date correctTickDateForPosition(Date time, DateTickUnit unit, DateTickMarkPosition position); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public void zoomRange(double lowerPercent, double upperPercent); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; public long toTimelineValue(long millisecond); public long toTimelineValue(Date date); public long toMillisecond(long value); public boolean containsDomainValue(long millisecond); public boolean containsDomainValue(Date date); public boolean containsDomainRange(long from, long to); public boolean containsDomainRange(Date from, Date to); public boolean equals(Object object); } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.DateTick; import org.jfree.chart.axis.DateTickMarkPosition; import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.chart.axis.SegmentedTimeline; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Millisecond; import org.jfree.data.time.Month; import org.jfree.data.time.Second; import org.jfree.data.time.Year; public class DateAxisTests extends TestCase { public static Test suite(); public DateAxisTests(String name); public void testEquals(); public void test1472942(); public void testHashCode(); public void testCloning(); public void testSetRange(); public void testSetMaximumDate(); public void testSetMinimumDate(); private boolean same(double d1, double d2, double tolerance); public void testJava2DToValue(); public void testSerialization(); public void testPreviousStandardDateYearA(); public void testPreviousStandardDateYearB(); public void testPreviousStandardDateMonthA(); public void testPreviousStandardDateMonthB(); public void testPreviousStandardDateDayA(); public void testPreviousStandardDateDayB(); public void testPreviousStandardDateHourA(); public void testPreviousStandardDateHourB(); public void testPreviousStandardDateSecondA(); public void testPreviousStandardDateSecondB(); public void testPreviousStandardDateMillisecondA(); public void testPreviousStandardDateMillisecondB(); public void testBug2201869(); public MyDateAxis(String label); public Date previousStandardDate(Date d, DateTickUnit unit); } ``` You are a professional Java test case writer, please create a test case named `testPreviousStandardDateMillisecondB` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 milliseconds (just for the sake of having a multiple). */ public void testPreviousStandardDateMillisecondB() { ```
public class DateAxis extends ValueAxis implements Cloneable, Serializable
package org.jfree.chart.axis.junit; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.DateTick; import org.jfree.chart.axis.DateTickMarkPosition; import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.chart.axis.SegmentedTimeline; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Millisecond; import org.jfree.data.time.Month; import org.jfree.data.time.Second; import org.jfree.data.time.Year;
public static Test suite(); public DateAxisTests(String name); public void testEquals(); public void test1472942(); public void testHashCode(); public void testCloning(); public void testSetRange(); public void testSetMaximumDate(); public void testSetMinimumDate(); private boolean same(double d1, double d2, double tolerance); public void testJava2DToValue(); public void testSerialization(); public void testPreviousStandardDateYearA(); public void testPreviousStandardDateYearB(); public void testPreviousStandardDateMonthA(); public void testPreviousStandardDateMonthB(); public void testPreviousStandardDateDayA(); public void testPreviousStandardDateDayB(); public void testPreviousStandardDateHourA(); public void testPreviousStandardDateHourB(); public void testPreviousStandardDateSecondA(); public void testPreviousStandardDateSecondB(); public void testPreviousStandardDateMillisecondA(); public void testPreviousStandardDateMillisecondB(); public void testBug2201869(); public MyDateAxis(String label); public Date previousStandardDate(Date d, DateTickUnit unit);
f2c788ff1ac833e865c458590d8f2ecd0a4ad985be7eb1828d54d2e386b4ef86
[ "org.jfree.chart.axis.junit.DateAxisTests::testPreviousStandardDateMillisecondB" ]
private static final long serialVersionUID = -1013460999649007604L; public static final DateRange DEFAULT_DATE_RANGE = new DateRange(); public static final double DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS = 2.0; public static final DateTickUnit DEFAULT_DATE_TICK_UNIT = new DateTickUnit(DateTickUnitType.DAY, 1, new SimpleDateFormat()); public static final Date DEFAULT_ANCHOR_DATE = new Date(); private DateTickUnit tickUnit; private DateFormat dateFormatOverride; private DateTickMarkPosition tickMarkPosition = DateTickMarkPosition.START; private static final Timeline DEFAULT_TIMELINE = new DefaultTimeline(); private TimeZone timeZone; private Locale locale; private Timeline timeline;
public void testPreviousStandardDateMillisecondB()
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * DateAxisTests.java * ------------------ * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 22-Apr-2003 : Version 1 (DG); * 07-Jan-2005 : Added test for hashCode() method (DG); * 25-Sep-2005 : New tests for bug 1564977 (DG); * 19-Apr-2007 : Added further checks for setMinimumDate() and * setMaximumDate() (DG); * 03-May-2007 : Replaced the tests for the previousStandardDate() method with * new tests that check that the previousStandardDate and the * next standard date do in fact span the reference date (DG); * 25-Nov-2008 : Added testBug2201869 (DG); * */ package org.jfree.chart.axis.junit; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.DateTick; import org.jfree.chart.axis.DateTickMarkPosition; import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.chart.axis.SegmentedTimeline; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Millisecond; import org.jfree.data.time.Month; import org.jfree.data.time.Second; import org.jfree.data.time.Year; /** * Tests for the {@link DateAxis} class. */ public class DateAxisTests extends TestCase { static class MyDateAxis extends DateAxis { /** * Creates a new instance. * * @param label the label. */ public MyDateAxis(String label) { super(label); } public Date previousStandardDate(Date d, DateTickUnit unit) { return super.previousStandardDate(d, unit); } } /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DateAxisTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DateAxisTests(String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { DateAxis a1 = new DateAxis("Test"); DateAxis a2 = new DateAxis("Test"); assertTrue(a1.equals(a2)); assertFalse(a1.equals(null)); assertFalse(a1.equals("Some non-DateAxis object")); // tickUnit a1.setTickUnit(new DateTickUnit(DateTickUnitType.DAY, 7)); assertFalse(a1.equals(a2)); a2.setTickUnit(new DateTickUnit(DateTickUnitType.DAY, 7)); assertTrue(a1.equals(a2)); // dateFormatOverride a1.setDateFormatOverride(new SimpleDateFormat("yyyy")); assertFalse(a1.equals(a2)); a2.setDateFormatOverride(new SimpleDateFormat("yyyy")); assertTrue(a1.equals(a2)); // tickMarkPosition a1.setTickMarkPosition(DateTickMarkPosition.END); assertFalse(a1.equals(a2)); a2.setTickMarkPosition(DateTickMarkPosition.END); assertTrue(a1.equals(a2)); // timeline a1.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline()); assertFalse(a1.equals(a2)); a2.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline()); assertTrue(a1.equals(a2)); } /** * A test for bug report 1472942. The DateFormat.equals() method is not * checking the range attribute. */ public void test1472942() { DateAxis a1 = new DateAxis("Test"); DateAxis a2 = new DateAxis("Test"); assertTrue(a1.equals(a2)); // range a1.setRange(new Date(1L), new Date(2L)); assertFalse(a1.equals(a2)); a2.setRange(new Date(1L), new Date(2L)); assertTrue(a1.equals(a2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { DateAxis a1 = new DateAxis("Test"); DateAxis a2 = new DateAxis("Test"); assertTrue(a1.equals(a2)); int h1 = a1.hashCode(); int h2 = a2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { DateAxis a1 = new DateAxis("Test"); DateAxis a2 = null; try { a2 = (DateAxis) a1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(a1 != a2); assertTrue(a1.getClass() == a2.getClass()); assertTrue(a1.equals(a2)); } /** * Test that the setRange() method works. */ public void testSetRange() { DateAxis axis = new DateAxis("Test Axis"); Calendar calendar = Calendar.getInstance(); calendar.set(1999, Calendar.JANUARY, 3); Date d1 = calendar.getTime(); calendar.set(1999, Calendar.JANUARY, 31); Date d2 = calendar.getTime(); axis.setRange(d1, d2); DateRange range = (DateRange) axis.getRange(); assertEquals(d1, range.getLowerDate()); assertEquals(d2, range.getUpperDate()); } /** * Test that the setMaximumDate() method works. */ public void testSetMaximumDate() { DateAxis axis = new DateAxis("Test Axis"); Date date = new Date(); axis.setMaximumDate(date); assertEquals(date, axis.getMaximumDate()); // check that setting the max date to something on or before the // current min date works... Date d1 = new Date(); Date d2 = new Date(d1.getTime() + 1); Date d0 = new Date(d1.getTime() - 1); axis.setMaximumDate(d2); axis.setMinimumDate(d1); axis.setMaximumDate(d1); assertEquals(d0, axis.getMinimumDate()); } /** * Test that the setMinimumDate() method works. */ public void testSetMinimumDate() { DateAxis axis = new DateAxis("Test Axis"); Date d1 = new Date(); Date d2 = new Date(d1.getTime() + 1); axis.setMaximumDate(d2); axis.setMinimumDate(d1); assertEquals(d1, axis.getMinimumDate()); // check that setting the min date to something on or after the // current min date works... Date d3 = new Date(d2.getTime() + 1); axis.setMinimumDate(d2); assertEquals(d3, axis.getMaximumDate()); } /** * Tests two doubles for 'near enough' equality. * * @param d1 number 1. * @param d2 number 2. * @param tolerance maximum tolerance. * * @return A boolean. */ private boolean same(double d1, double d2, double tolerance) { return (Math.abs(d1 - d2) < tolerance); } /** * Test the translation of Java2D values to data values. */ public void testJava2DToValue() { DateAxis axis = new DateAxis(); axis.setRange(50.0, 100.0); Rectangle2D dataArea = new Rectangle2D.Double(10.0, 50.0, 400.0, 300.0); double y1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT); assertTrue(same(y1, 95.8333333, 1.0)); double y2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertTrue(same(y2, 95.8333333, 1.0)); double x1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertTrue(same(x1, 58.125, 1.0)); double x2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertTrue(same(x2, 58.125, 1.0)); axis.setInverted(true); double y3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT); assertTrue(same(y3, 54.1666667, 1.0)); double y4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertTrue(same(y4, 54.1666667, 1.0)); double x3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertTrue(same(x3, 91.875, 1.0)); double x4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertTrue(same(x4, 91.875, 1.0)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { DateAxis a1 = new DateAxis("Test Axis"); DateAxis a2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(a1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); a2 = (DateAxis) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } boolean b = a1.equals(a2); assertTrue(b); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 1 year. */ public void testPreviousStandardDateYearA() { MyDateAxis axis = new MyDateAxis("Year"); Year y2006 = new Year(2006); Year y2007 = new Year(2007); // five dates to check... Date d0 = new Date(y2006.getFirstMillisecond()); Date d1 = new Date(y2006.getFirstMillisecond() + 500L); Date d2 = new Date(y2006.getMiddleMillisecond()); Date d3 = new Date(y2006.getMiddleMillisecond() + 500L); Date d4 = new Date(y2006.getLastMillisecond()); Date end = new Date(y2007.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.YEAR, 1); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 years (just for the sake of having a multiple). */ public void testPreviousStandardDateYearB() { MyDateAxis axis = new MyDateAxis("Year"); Year y2006 = new Year(2006); Year y2007 = new Year(2007); // five dates to check... Date d0 = new Date(y2006.getFirstMillisecond()); Date d1 = new Date(y2006.getFirstMillisecond() + 500L); Date d2 = new Date(y2006.getMiddleMillisecond()); Date d3 = new Date(y2006.getMiddleMillisecond() + 500L); Date d4 = new Date(y2006.getLastMillisecond()); Date end = new Date(y2007.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.YEAR, 10); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 1 month. */ public void testPreviousStandardDateMonthA() { MyDateAxis axis = new MyDateAxis("Month"); Month nov2006 = new Month(11, 2006); Month dec2006 = new Month(12, 2006); // five dates to check... Date d0 = new Date(nov2006.getFirstMillisecond()); Date d1 = new Date(nov2006.getFirstMillisecond() + 500L); Date d2 = new Date(nov2006.getMiddleMillisecond()); Date d3 = new Date(nov2006.getMiddleMillisecond() + 500L); Date d4 = new Date(nov2006.getLastMillisecond()); Date end = new Date(dec2006.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.MONTH, 1); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 3 months (just for the sake of having a multiple). */ public void testPreviousStandardDateMonthB() { MyDateAxis axis = new MyDateAxis("Month"); Month nov2006 = new Month(11, 2006); Month dec2006 = new Month(12, 2006); // five dates to check... Date d0 = new Date(nov2006.getFirstMillisecond()); Date d1 = new Date(nov2006.getFirstMillisecond() + 500L); Date d2 = new Date(nov2006.getMiddleMillisecond()); Date d3 = new Date(nov2006.getMiddleMillisecond() + 500L); Date d4 = new Date(nov2006.getLastMillisecond()); Date end = new Date(dec2006.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.MONTH, 3); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 1 day. */ public void testPreviousStandardDateDayA() { MyDateAxis axis = new MyDateAxis("Day"); Day apr12007 = new Day(1, 4, 2007); Day apr22007 = new Day(2, 4, 2007); // five dates to check... Date d0 = new Date(apr12007.getFirstMillisecond()); Date d1 = new Date(apr12007.getFirstMillisecond() + 500L); Date d2 = new Date(apr12007.getMiddleMillisecond()); Date d3 = new Date(apr12007.getMiddleMillisecond() + 500L); Date d4 = new Date(apr12007.getLastMillisecond()); Date end = new Date(apr22007.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.DAY, 1); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 7 days (just for the sake of having a multiple). */ public void testPreviousStandardDateDayB() { MyDateAxis axis = new MyDateAxis("Day"); Day apr12007 = new Day(1, 4, 2007); Day apr22007 = new Day(2, 4, 2007); // five dates to check... Date d0 = new Date(apr12007.getFirstMillisecond()); Date d1 = new Date(apr12007.getFirstMillisecond() + 500L); Date d2 = new Date(apr12007.getMiddleMillisecond()); Date d3 = new Date(apr12007.getMiddleMillisecond() + 500L); Date d4 = new Date(apr12007.getLastMillisecond()); Date end = new Date(apr22007.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.DAY, 7); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 1 hour. */ public void testPreviousStandardDateHourA() { MyDateAxis axis = new MyDateAxis("Hour"); Hour h0 = new Hour(12, 1, 4, 2007); Hour h1 = new Hour(13, 1, 4, 2007); // five dates to check... Date d0 = new Date(h0.getFirstMillisecond()); Date d1 = new Date(h0.getFirstMillisecond() + 500L); Date d2 = new Date(h0.getMiddleMillisecond()); Date d3 = new Date(h0.getMiddleMillisecond() + 500L); Date d4 = new Date(h0.getLastMillisecond()); Date end = new Date(h1.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.HOUR, 1); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 6 hours (just for the sake of having a multiple). */ public void testPreviousStandardDateHourB() { MyDateAxis axis = new MyDateAxis("Hour"); Hour h0 = new Hour(12, 1, 4, 2007); Hour h1 = new Hour(13, 1, 4, 2007); // five dates to check... Date d0 = new Date(h0.getFirstMillisecond()); Date d1 = new Date(h0.getFirstMillisecond() + 500L); Date d2 = new Date(h0.getMiddleMillisecond()); Date d3 = new Date(h0.getMiddleMillisecond() + 500L); Date d4 = new Date(h0.getLastMillisecond()); Date end = new Date(h1.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.HOUR, 6); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 1 second. */ public void testPreviousStandardDateSecondA() { MyDateAxis axis = new MyDateAxis("Second"); Second s0 = new Second(58, 31, 12, 1, 4, 2007); Second s1 = new Second(59, 31, 12, 1, 4, 2007); // five dates to check... Date d0 = new Date(s0.getFirstMillisecond()); Date d1 = new Date(s0.getFirstMillisecond() + 50L); Date d2 = new Date(s0.getMiddleMillisecond()); Date d3 = new Date(s0.getMiddleMillisecond() + 50L); Date d4 = new Date(s0.getLastMillisecond()); Date end = new Date(s1.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.SECOND, 1); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 5 seconds (just for the sake of having a multiple). */ public void testPreviousStandardDateSecondB() { MyDateAxis axis = new MyDateAxis("Second"); Second s0 = new Second(58, 31, 12, 1, 4, 2007); Second s1 = new Second(59, 31, 12, 1, 4, 2007); // five dates to check... Date d0 = new Date(s0.getFirstMillisecond()); Date d1 = new Date(s0.getFirstMillisecond() + 50L); Date d2 = new Date(s0.getMiddleMillisecond()); Date d3 = new Date(s0.getMiddleMillisecond() + 50L); Date d4 = new Date(s0.getLastMillisecond()); Date end = new Date(s1.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.SECOND, 5); axis.setTickUnit(unit); // START: check d0 and d1 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); // MIDDLE: check d1, d2 and d3 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d1, end); psd = axis.previousStandardDate(d1, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d1.getTime()); assertTrue(nsd.getTime() >= d1.getTime()); axis.setRange(d2, end); psd = axis.previousStandardDate(d2, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d2.getTime()); assertTrue(nsd.getTime() >= d2.getTime()); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); // END: check d3 and d4 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d3, end); psd = axis.previousStandardDate(d3, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d3.getTime()); assertTrue(nsd.getTime() >= d3.getTime()); axis.setRange(d4, end); psd = axis.previousStandardDate(d4, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d4.getTime()); assertTrue(nsd.getTime() >= d4.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 1 millisecond. */ public void testPreviousStandardDateMillisecondA() { MyDateAxis axis = new MyDateAxis("Millisecond"); Millisecond m0 = new Millisecond(458, 58, 31, 12, 1, 4, 2007); Millisecond m1 = new Millisecond(459, 58, 31, 12, 1, 4, 2007); Date d0 = new Date(m0.getFirstMillisecond()); Date end = new Date(m1.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.MILLISECOND, 1); axis.setTickUnit(unit); // START: check d0 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); // MIDDLE: check d0 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d0, end); psd = axis.previousStandardDate(d0, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); // END: check d0 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d0, end); psd = axis.previousStandardDate(d0, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); } /** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 milliseconds (just for the sake of having a multiple). */ public void testPreviousStandardDateMillisecondB() { MyDateAxis axis = new MyDateAxis("Millisecond"); Millisecond m0 = new Millisecond(458, 58, 31, 12, 1, 4, 2007); Millisecond m1 = new Millisecond(459, 58, 31, 12, 1, 4, 2007); Date d0 = new Date(m0.getFirstMillisecond()); Date end = new Date(m1.getLastMillisecond()); DateTickUnit unit = new DateTickUnit(DateTickUnitType.MILLISECOND, 10); axis.setTickUnit(unit); // START: check d0 axis.setTickMarkPosition(DateTickMarkPosition.START); axis.setRange(d0, end); Date psd = axis.previousStandardDate(d0, unit); Date nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); // MIDDLE: check d0 axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); axis.setRange(d0, end); psd = axis.previousStandardDate(d0, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); // END: check d0 axis.setTickMarkPosition(DateTickMarkPosition.END); axis.setRange(d0, end); psd = axis.previousStandardDate(d0, unit); nsd = unit.addToDate(psd, TimeZone.getDefault()); assertTrue(psd.getTime() < d0.getTime()); assertTrue(nsd.getTime() >= d0.getTime()); } /** * A test to reproduce bug 2201869. */ public void testBug2201869() { TimeZone tz = TimeZone.getTimeZone("GMT"); GregorianCalendar c = new GregorianCalendar(tz, Locale.UK); DateAxis axis = new DateAxis("Date", tz, Locale.UK); SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy", Locale.UK); sdf.setCalendar(c); axis.setTickUnit(new DateTickUnit(DateTickUnitType.MONTH, 1, sdf)); Day d1 = new Day(1, 3, 2008); d1.peg(c); Day d2 = new Day(30, 6, 2008); d2.peg(c); axis.setRange(d1.getStart(), d2.getEnd()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, 200, 100); axis.setTickMarkPosition(DateTickMarkPosition.END); List ticks = axis.refreshTicks(g2, new AxisState(), area, RectangleEdge.BOTTOM); assertEquals(3, ticks.size()); DateTick t1 = (DateTick) ticks.get(0); assertEquals("31-Mar-2008", t1.getText()); DateTick t2 = (DateTick) ticks.get(1); assertEquals("30-Apr-2008", t2.getText()); DateTick t3 = (DateTick) ticks.get(2); assertEquals("31-May-2008", t3.getText()); // now repeat for a vertical axis ticks = axis.refreshTicks(g2, new AxisState(), area, RectangleEdge.LEFT); assertEquals(3, ticks.size()); t1 = (DateTick) ticks.get(0); assertEquals("31-Mar-2008", t1.getText()); t2 = (DateTick) ticks.get(1); assertEquals("30-Apr-2008", t2.getText()); t3 = (DateTick) ticks.get(2); assertEquals("31-May-2008", t3.getText()); } }
[ { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "autoAdjustRange", "be_test_function_signature": "()V", "line_numbers": [ "1277", "1279", "1280", "1283", "1284", "1286", "1287", "1288", "1290", "1296", "1300", "1303", "1304", "1305", "1308", "1309", "1310", "1311", "1312", "1313", "1314", "1316", "1317", "1320", "1321", "1322", "1323", "1326" ], "method_line_rate": 0.10714285714285714 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "createStandardDateTickUnits", "be_test_function_signature": "(Ljava/util/TimeZone;Ljava/util/Locale;)Lorg/jfree/chart/axis/TickUnitSource;", "line_numbers": [ "1150", "1151", "1153", "1154", "1156", "1159", "1160", "1161", "1162", "1163", "1164", "1165", "1167", "1168", "1169", "1170", "1171", "1172", "1173", "1176", "1177", "1179", "1181", "1183", "1185", "1187", "1189", "1193", "1195", "1197", "1199", "1203", "1205", "1207", "1209", "1211", "1213", "1215", "1219", "1221", "1223", "1225", "1227", "1231", "1233", "1235", "1237", "1241", "1243", "1245", "1247", "1249", "1253", "1255", "1257", "1259", "1261", "1263", "1265", "1268" ], "method_line_rate": 0.9666666666666667 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "previousStandardDate", "be_test_function_signature": "(Ljava/util/Date;Lorg/jfree/chart/axis/DateTickUnit;)Ljava/util/Date;", "line_numbers": [ "883", "884", "885", "886", "887", "889", "890", "891", "892", "893", "894", "895", "896", "897", "898", "899", "900", "901", "902", "904", "906", "907", "908", "909", "910", "911", "912", "913", "915", "916", "919", "921", "922", "923", "924", "925", "926", "928", "930", "931", "932", "933", "934", "935", "936", "938", "939", "942", "944", "945", "946", "947", "948", "949", "951", "953", "954", "955", "956", "957", "958", "959", "961", "962", "963", "966", "967", "969", "970", "971", "972", "973", "974", "976", "978", "979", "980", "981", "982", "983", "984", "986", "987", "988", "989", "992", "993", "994", "996", "997", "1000", "1001", "1002", "1003", "1005", "1007", "1008", "1009", "1010", "1011", "1013", "1015", "1016", "1017", "1020", "1021", "1024", "1026", "1027", "1028", "1029", "1031", "1032", "1033", "1036", "1037", "1039", "1040", "1041", "1042", "1043", "1044", "1046", "1049" ], "method_line_rate": 0.14516129032258066 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "setRange", "be_test_function_signature": "(Ljava/util/Date;Ljava/util/Date;)V", "line_numbers": [ "570", "571", "573", "574" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "setRange", "be_test_function_signature": "(Lorg/jfree/data/Range;)V", "line_numbers": [ "535", "536" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "setRange", "be_test_function_signature": "(Lorg/jfree/data/Range;ZZ)V", "line_numbers": [ "551", "552", "556", "557", "559", "560" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "setTickMarkPosition", "be_test_function_signature": "(Lorg/jfree/chart/axis/DateTickMarkPosition;)V", "line_numbers": [ "706", "707", "709", "710", "711" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "setTickUnit", "be_test_function_signature": "(Lorg/jfree/chart/axis/DateTickUnit;)V", "line_numbers": [ "481", "482" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/DateAxis.java", "be_test_class_name": "org.jfree.chart.axis.DateAxis", "be_test_function_name": "setTickUnit", "be_test_function_signature": "(Lorg/jfree/chart/axis/DateTickUnit;ZZ)V", "line_numbers": [ "496", "497", "498", "500", "501", "504" ], "method_line_rate": 1 } ]
public class DateUtilsTest
@Test public void testRound() throws Exception { // tests for public static Date round(Date date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round(date2, Calendar.MONTH)); assertEquals("round semimonth-0 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date0, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round(date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round(date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round(date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round(date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round(date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round(date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round(date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round(date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round(date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round(date2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round(dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round(dateAmPm4, Calendar.AM_PM)); // tests for public static Date round(Object date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round((Object) date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round((Object) date2, Calendar.MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round((Object) date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round((Object) date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round((Object) date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round((Object) date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round((Object) date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round((Object) date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) date2, Calendar.SECOND)); assertEquals("round calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) cal1, Calendar.SECOND)); assertEquals("round calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) cal2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm4, Calendar.AM_PM)); try { DateUtils.round((Date) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.round((Calendar) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.round((Object) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.round("", Calendar.SECOND); fail(); } catch (final ClassCastException ex) {} try { DateUtils.round(date1, -9999); fail(); } catch(final IllegalArgumentException ex) {} assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm4, Calendar.AM_PM)); // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 / LANG-13 // Test rounding across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round(date4, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round(date7, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date rounding tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); }
// public static long getFragmentInSeconds(final Date date, final int fragment); // public static long getFragmentInMinutes(final Date date, final int fragment); // public static long getFragmentInHours(final Date date, final int fragment); // public static long getFragmentInDays(final Date date, final int fragment); // public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment); // public static long getFragmentInSeconds(final Calendar calendar, final int fragment); // public static long getFragmentInMinutes(final Calendar calendar, final int fragment); // public static long getFragmentInHours(final Calendar calendar, final int fragment); // public static long getFragmentInDays(final Calendar calendar, final int fragment); // private static long getFragment(final Date date, final int fragment, final int unit); // private static long getFragment(final Calendar calendar, final int fragment, final int unit); // public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field); // public static boolean truncatedEquals(final Date date1, final Date date2, final int field); // public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field); // public static int truncatedCompareTo(final Date date1, final Date date2, final int field); // private static long getMillisPerUnit(final int unit); // DateIterator(final Calendar startFinal, final Calendar endFinal); // @Override // public boolean hasNext(); // @Override // public Calendar next(); // @Override // public void remove(); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.time; // // import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNotNull; // import static org.junit.Assert.assertNotSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import java.text.DateFormat; // import java.text.ParseException; // import java.text.SimpleDateFormat; // import java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.Iterator; // import java.util.Locale; // import java.util.NoSuchElementException; // import java.util.TimeZone; // import junit.framework.AssertionFailedError; // import org.apache.commons.lang3.SystemUtils; // import org.junit.Before; // import org.junit.Test; // // // // public class DateUtilsTest { // private static final long MILLIS_TEST; // DateFormat dateParser = null; // DateFormat dateTimeParser = null; // DateFormat timeZoneDateParser = null; // Date dateAmPm1 = null; // Date dateAmPm2 = null; // Date dateAmPm3 = null; // Date dateAmPm4 = null; // Date date0 = null; // Date date1 = null; // Date date2 = null; // Date date3 = null; // Date date4 = null; // Date date5 = null; // Date date6 = null; // Date date7 = null; // Date date8 = null; // Calendar calAmPm1 = null; // Calendar calAmPm2 = null; // Calendar calAmPm3 = null; // Calendar calAmPm4 = null; // Calendar cal1 = null; // Calendar cal2 = null; // Calendar cal3 = null; // Calendar cal4 = null; // Calendar cal5 = null; // Calendar cal6 = null; // Calendar cal7 = null; // Calendar cal8 = null; // TimeZone zone = null; // TimeZone defaultZone = null; // // @Before // public void setUp() throws Exception; // @Test // public void testConstructor(); // @Test // public void testIsSameDay_Date(); // @Test // public void testIsSameDay_Cal(); // @Test // public void testIsSameInstant_Date(); // @Test // public void testIsSameInstant_Cal(); // @Test // public void testIsSameLocalTime_Cal(); // @Test // public void testParseDate() throws Exception; // @Test // public void testParseDateWithLeniency() throws Exception; // @Test // public void testAddYears() throws Exception; // @Test // public void testAddMonths() throws Exception; // @Test // public void testAddWeeks() throws Exception; // @Test // public void testAddDays() throws Exception; // @Test // public void testAddHours() throws Exception; // @Test // public void testAddMinutes() throws Exception; // @Test // public void testAddSeconds() throws Exception; // @Test // public void testAddMilliseconds() throws Exception; // @Test // public void testSetYears() throws Exception; // @Test // public void testSetMonths() throws Exception; // @Test // public void testSetDays() throws Exception; // @Test // public void testSetHours() throws Exception; // @Test // public void testSetMinutes() throws Exception; // @Test // public void testSetSeconds() throws Exception; // @Test // public void testSetMilliseconds() throws Exception; // private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception; // @Test // public void testToCalendar(); // @Test // public void testRound() throws Exception; // @Test // public void testRoundLang346() throws Exception; // @Test // public void testTruncate() throws Exception; // @Test // public void testTruncateLang59() throws Exception; // @Test // public void testLang530() throws ParseException; // @Test // public void testCeil() throws Exception; // @Test // public void testIteratorEx() throws Exception; // @Test // public void testWeekIterator() throws Exception; // @Test // public void testMonthIterator() throws Exception; // @Test // public void testLANG799_EN_OK() throws ParseException; // @Test(expected=ParseException.class) // public void testLANG799_EN_FAIL() throws ParseException; // @Test // public void testLANG799_DE_OK() throws ParseException; // @Test(expected=ParseException.class) // public void testLANG799_DE_FAIL() throws ParseException; // @Test // public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException; // private static void assertWeekIterator(final Iterator<?> it, final Calendar start); // private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end); // private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end); // private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta); // void warn(final String msg); // } // You are a professional Java test case writer, please create a test case named `testRound` for the `DateUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests various values with the round method */
src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
package org.apache.commons.lang3.time; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException;
public DateUtils(); public static boolean isSameDay(final Date date1, final Date date2); public static boolean isSameDay(final Calendar cal1, final Calendar cal2); public static boolean isSameInstant(final Date date1, final Date date2); public static boolean isSameInstant(final Calendar cal1, final Calendar cal2); public static boolean isSameLocalTime(final Calendar cal1, final Calendar cal2); public static Date parseDate(final String str, final String... parsePatterns) throws ParseException; public static Date parseDate(final String str, final Locale locale, final String... parsePatterns) throws ParseException; public static Date parseDateStrictly(final String str, final String... parsePatterns) throws ParseException; public static Date parseDateStrictly(final String str, final Locale locale, final String... parsePatterns) throws ParseException; private static Date parseDateWithLeniency( final String str, final Locale locale, final String[] parsePatterns, final boolean lenient) throws ParseException; public static Date addYears(final Date date, final int amount); public static Date addMonths(final Date date, final int amount); public static Date addWeeks(final Date date, final int amount); public static Date addDays(final Date date, final int amount); public static Date addHours(final Date date, final int amount); public static Date addMinutes(final Date date, final int amount); public static Date addSeconds(final Date date, final int amount); public static Date addMilliseconds(final Date date, final int amount); private static Date add(final Date date, final int calendarField, final int amount); public static Date setYears(final Date date, final int amount); public static Date setMonths(final Date date, final int amount); public static Date setDays(final Date date, final int amount); public static Date setHours(final Date date, final int amount); public static Date setMinutes(final Date date, final int amount); public static Date setSeconds(final Date date, final int amount); public static Date setMilliseconds(final Date date, final int amount); private static Date set(final Date date, final int calendarField, final int amount); public static Calendar toCalendar(final Date date); public static Date round(final Date date, final int field); public static Calendar round(final Calendar date, final int field); public static Date round(final Object date, final int field); public static Date truncate(final Date date, final int field); public static Calendar truncate(final Calendar date, final int field); public static Date truncate(final Object date, final int field); public static Date ceiling(final Date date, final int field); public static Calendar ceiling(final Calendar date, final int field); public static Date ceiling(final Object date, final int field); private static void modify(final Calendar val, final int field, final int modType); public static Iterator<Calendar> iterator(final Date focus, final int rangeStyle); public static Iterator<Calendar> iterator(final Calendar focus, final int rangeStyle); public static Iterator<?> iterator(final Object focus, final int rangeStyle); public static long getFragmentInMilliseconds(final Date date, final int fragment); public static long getFragmentInSeconds(final Date date, final int fragment); public static long getFragmentInMinutes(final Date date, final int fragment); public static long getFragmentInHours(final Date date, final int fragment); public static long getFragmentInDays(final Date date, final int fragment); public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment); public static long getFragmentInSeconds(final Calendar calendar, final int fragment); public static long getFragmentInMinutes(final Calendar calendar, final int fragment); public static long getFragmentInHours(final Calendar calendar, final int fragment); public static long getFragmentInDays(final Calendar calendar, final int fragment); private static long getFragment(final Date date, final int fragment, final int unit); private static long getFragment(final Calendar calendar, final int fragment, final int unit); public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field); public static boolean truncatedEquals(final Date date1, final Date date2, final int field); public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field); public static int truncatedCompareTo(final Date date1, final Date date2, final int field); private static long getMillisPerUnit(final int unit); DateIterator(final Calendar startFinal, final Calendar endFinal); @Override public boolean hasNext(); @Override public Calendar next(); @Override public void remove();
871
testRound
```java public static long getFragmentInSeconds(final Date date, final int fragment); public static long getFragmentInMinutes(final Date date, final int fragment); public static long getFragmentInHours(final Date date, final int fragment); public static long getFragmentInDays(final Date date, final int fragment); public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment); public static long getFragmentInSeconds(final Calendar calendar, final int fragment); public static long getFragmentInMinutes(final Calendar calendar, final int fragment); public static long getFragmentInHours(final Calendar calendar, final int fragment); public static long getFragmentInDays(final Calendar calendar, final int fragment); private static long getFragment(final Date date, final int fragment, final int unit); private static long getFragment(final Calendar calendar, final int fragment, final int unit); public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field); public static boolean truncatedEquals(final Date date1, final Date date2, final int field); public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field); public static int truncatedCompareTo(final Date date1, final Date date2, final int field); private static long getMillisPerUnit(final int unit); DateIterator(final Calendar startFinal, final Calendar endFinal); @Override public boolean hasNext(); @Override public Calendar next(); @Override public void remove(); } // Abstract Java Test Class package org.apache.commons.lang3.time; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.apache.commons.lang3.SystemUtils; import org.junit.Before; import org.junit.Test; public class DateUtilsTest { private static final long MILLIS_TEST; DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; @Before public void setUp() throws Exception; @Test public void testConstructor(); @Test public void testIsSameDay_Date(); @Test public void testIsSameDay_Cal(); @Test public void testIsSameInstant_Date(); @Test public void testIsSameInstant_Cal(); @Test public void testIsSameLocalTime_Cal(); @Test public void testParseDate() throws Exception; @Test public void testParseDateWithLeniency() throws Exception; @Test public void testAddYears() throws Exception; @Test public void testAddMonths() throws Exception; @Test public void testAddWeeks() throws Exception; @Test public void testAddDays() throws Exception; @Test public void testAddHours() throws Exception; @Test public void testAddMinutes() throws Exception; @Test public void testAddSeconds() throws Exception; @Test public void testAddMilliseconds() throws Exception; @Test public void testSetYears() throws Exception; @Test public void testSetMonths() throws Exception; @Test public void testSetDays() throws Exception; @Test public void testSetHours() throws Exception; @Test public void testSetMinutes() throws Exception; @Test public void testSetSeconds() throws Exception; @Test public void testSetMilliseconds() throws Exception; private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception; @Test public void testToCalendar(); @Test public void testRound() throws Exception; @Test public void testRoundLang346() throws Exception; @Test public void testTruncate() throws Exception; @Test public void testTruncateLang59() throws Exception; @Test public void testLang530() throws ParseException; @Test public void testCeil() throws Exception; @Test public void testIteratorEx() throws Exception; @Test public void testWeekIterator() throws Exception; @Test public void testMonthIterator() throws Exception; @Test public void testLANG799_EN_OK() throws ParseException; @Test(expected=ParseException.class) public void testLANG799_EN_FAIL() throws ParseException; @Test public void testLANG799_DE_OK() throws ParseException; @Test(expected=ParseException.class) public void testLANG799_DE_FAIL() throws ParseException; @Test public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException; private static void assertWeekIterator(final Iterator<?> it, final Calendar start); private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end); private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end); private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta); void warn(final String msg); } ``` You are a professional Java test case writer, please create a test case named `testRound` for the `DateUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests various values with the round method */
653
// public static long getFragmentInSeconds(final Date date, final int fragment); // public static long getFragmentInMinutes(final Date date, final int fragment); // public static long getFragmentInHours(final Date date, final int fragment); // public static long getFragmentInDays(final Date date, final int fragment); // public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment); // public static long getFragmentInSeconds(final Calendar calendar, final int fragment); // public static long getFragmentInMinutes(final Calendar calendar, final int fragment); // public static long getFragmentInHours(final Calendar calendar, final int fragment); // public static long getFragmentInDays(final Calendar calendar, final int fragment); // private static long getFragment(final Date date, final int fragment, final int unit); // private static long getFragment(final Calendar calendar, final int fragment, final int unit); // public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field); // public static boolean truncatedEquals(final Date date1, final Date date2, final int field); // public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field); // public static int truncatedCompareTo(final Date date1, final Date date2, final int field); // private static long getMillisPerUnit(final int unit); // DateIterator(final Calendar startFinal, final Calendar endFinal); // @Override // public boolean hasNext(); // @Override // public Calendar next(); // @Override // public void remove(); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.time; // // import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNotNull; // import static org.junit.Assert.assertNotSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import java.text.DateFormat; // import java.text.ParseException; // import java.text.SimpleDateFormat; // import java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.Iterator; // import java.util.Locale; // import java.util.NoSuchElementException; // import java.util.TimeZone; // import junit.framework.AssertionFailedError; // import org.apache.commons.lang3.SystemUtils; // import org.junit.Before; // import org.junit.Test; // // // // public class DateUtilsTest { // private static final long MILLIS_TEST; // DateFormat dateParser = null; // DateFormat dateTimeParser = null; // DateFormat timeZoneDateParser = null; // Date dateAmPm1 = null; // Date dateAmPm2 = null; // Date dateAmPm3 = null; // Date dateAmPm4 = null; // Date date0 = null; // Date date1 = null; // Date date2 = null; // Date date3 = null; // Date date4 = null; // Date date5 = null; // Date date6 = null; // Date date7 = null; // Date date8 = null; // Calendar calAmPm1 = null; // Calendar calAmPm2 = null; // Calendar calAmPm3 = null; // Calendar calAmPm4 = null; // Calendar cal1 = null; // Calendar cal2 = null; // Calendar cal3 = null; // Calendar cal4 = null; // Calendar cal5 = null; // Calendar cal6 = null; // Calendar cal7 = null; // Calendar cal8 = null; // TimeZone zone = null; // TimeZone defaultZone = null; // // @Before // public void setUp() throws Exception; // @Test // public void testConstructor(); // @Test // public void testIsSameDay_Date(); // @Test // public void testIsSameDay_Cal(); // @Test // public void testIsSameInstant_Date(); // @Test // public void testIsSameInstant_Cal(); // @Test // public void testIsSameLocalTime_Cal(); // @Test // public void testParseDate() throws Exception; // @Test // public void testParseDateWithLeniency() throws Exception; // @Test // public void testAddYears() throws Exception; // @Test // public void testAddMonths() throws Exception; // @Test // public void testAddWeeks() throws Exception; // @Test // public void testAddDays() throws Exception; // @Test // public void testAddHours() throws Exception; // @Test // public void testAddMinutes() throws Exception; // @Test // public void testAddSeconds() throws Exception; // @Test // public void testAddMilliseconds() throws Exception; // @Test // public void testSetYears() throws Exception; // @Test // public void testSetMonths() throws Exception; // @Test // public void testSetDays() throws Exception; // @Test // public void testSetHours() throws Exception; // @Test // public void testSetMinutes() throws Exception; // @Test // public void testSetSeconds() throws Exception; // @Test // public void testSetMilliseconds() throws Exception; // private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception; // @Test // public void testToCalendar(); // @Test // public void testRound() throws Exception; // @Test // public void testRoundLang346() throws Exception; // @Test // public void testTruncate() throws Exception; // @Test // public void testTruncateLang59() throws Exception; // @Test // public void testLang530() throws ParseException; // @Test // public void testCeil() throws Exception; // @Test // public void testIteratorEx() throws Exception; // @Test // public void testWeekIterator() throws Exception; // @Test // public void testMonthIterator() throws Exception; // @Test // public void testLANG799_EN_OK() throws ParseException; // @Test(expected=ParseException.class) // public void testLANG799_EN_FAIL() throws ParseException; // @Test // public void testLANG799_DE_OK() throws ParseException; // @Test(expected=ParseException.class) // public void testLANG799_DE_FAIL() throws ParseException; // @Test // public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException; // private static void assertWeekIterator(final Iterator<?> it, final Calendar start); // private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end); // private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end); // private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta); // void warn(final String msg); // } // You are a professional Java test case writer, please create a test case named `testRound` for the `DateUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests various values with the round method */ //----------------------------------------------------------------------- @Test public void testRound() throws Exception {
/** * Tests various values with the round method */ //-----------------------------------------------------------------------
1
org.apache.commons.lang3.time.DateUtils
src/test/java
```java public static long getFragmentInSeconds(final Date date, final int fragment); public static long getFragmentInMinutes(final Date date, final int fragment); public static long getFragmentInHours(final Date date, final int fragment); public static long getFragmentInDays(final Date date, final int fragment); public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment); public static long getFragmentInSeconds(final Calendar calendar, final int fragment); public static long getFragmentInMinutes(final Calendar calendar, final int fragment); public static long getFragmentInHours(final Calendar calendar, final int fragment); public static long getFragmentInDays(final Calendar calendar, final int fragment); private static long getFragment(final Date date, final int fragment, final int unit); private static long getFragment(final Calendar calendar, final int fragment, final int unit); public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field); public static boolean truncatedEquals(final Date date1, final Date date2, final int field); public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field); public static int truncatedCompareTo(final Date date1, final Date date2, final int field); private static long getMillisPerUnit(final int unit); DateIterator(final Calendar startFinal, final Calendar endFinal); @Override public boolean hasNext(); @Override public Calendar next(); @Override public void remove(); } // Abstract Java Test Class package org.apache.commons.lang3.time; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.apache.commons.lang3.SystemUtils; import org.junit.Before; import org.junit.Test; public class DateUtilsTest { private static final long MILLIS_TEST; DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; @Before public void setUp() throws Exception; @Test public void testConstructor(); @Test public void testIsSameDay_Date(); @Test public void testIsSameDay_Cal(); @Test public void testIsSameInstant_Date(); @Test public void testIsSameInstant_Cal(); @Test public void testIsSameLocalTime_Cal(); @Test public void testParseDate() throws Exception; @Test public void testParseDateWithLeniency() throws Exception; @Test public void testAddYears() throws Exception; @Test public void testAddMonths() throws Exception; @Test public void testAddWeeks() throws Exception; @Test public void testAddDays() throws Exception; @Test public void testAddHours() throws Exception; @Test public void testAddMinutes() throws Exception; @Test public void testAddSeconds() throws Exception; @Test public void testAddMilliseconds() throws Exception; @Test public void testSetYears() throws Exception; @Test public void testSetMonths() throws Exception; @Test public void testSetDays() throws Exception; @Test public void testSetHours() throws Exception; @Test public void testSetMinutes() throws Exception; @Test public void testSetSeconds() throws Exception; @Test public void testSetMilliseconds() throws Exception; private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception; @Test public void testToCalendar(); @Test public void testRound() throws Exception; @Test public void testRoundLang346() throws Exception; @Test public void testTruncate() throws Exception; @Test public void testTruncateLang59() throws Exception; @Test public void testLang530() throws ParseException; @Test public void testCeil() throws Exception; @Test public void testIteratorEx() throws Exception; @Test public void testWeekIterator() throws Exception; @Test public void testMonthIterator() throws Exception; @Test public void testLANG799_EN_OK() throws ParseException; @Test(expected=ParseException.class) public void testLANG799_EN_FAIL() throws ParseException; @Test public void testLANG799_DE_OK() throws ParseException; @Test(expected=ParseException.class) public void testLANG799_DE_FAIL() throws ParseException; @Test public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException; private static void assertWeekIterator(final Iterator<?> it, final Calendar start); private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end); private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end); private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta); void warn(final String msg); } ``` You are a professional Java test case writer, please create a test case named `testRound` for the `DateUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests various values with the round method */ //----------------------------------------------------------------------- @Test public void testRound() throws Exception { ```
public class DateUtils
package org.apache.commons.lang3.time; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.apache.commons.lang3.SystemUtils; import org.junit.Before; import org.junit.Test;
@Before public void setUp() throws Exception; @Test public void testConstructor(); @Test public void testIsSameDay_Date(); @Test public void testIsSameDay_Cal(); @Test public void testIsSameInstant_Date(); @Test public void testIsSameInstant_Cal(); @Test public void testIsSameLocalTime_Cal(); @Test public void testParseDate() throws Exception; @Test public void testParseDateWithLeniency() throws Exception; @Test public void testAddYears() throws Exception; @Test public void testAddMonths() throws Exception; @Test public void testAddWeeks() throws Exception; @Test public void testAddDays() throws Exception; @Test public void testAddHours() throws Exception; @Test public void testAddMinutes() throws Exception; @Test public void testAddSeconds() throws Exception; @Test public void testAddMilliseconds() throws Exception; @Test public void testSetYears() throws Exception; @Test public void testSetMonths() throws Exception; @Test public void testSetDays() throws Exception; @Test public void testSetHours() throws Exception; @Test public void testSetMinutes() throws Exception; @Test public void testSetSeconds() throws Exception; @Test public void testSetMilliseconds() throws Exception; private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception; @Test public void testToCalendar(); @Test public void testRound() throws Exception; @Test public void testRoundLang346() throws Exception; @Test public void testTruncate() throws Exception; @Test public void testTruncateLang59() throws Exception; @Test public void testLang530() throws ParseException; @Test public void testCeil() throws Exception; @Test public void testIteratorEx() throws Exception; @Test public void testWeekIterator() throws Exception; @Test public void testMonthIterator() throws Exception; @Test public void testLANG799_EN_OK() throws ParseException; @Test(expected=ParseException.class) public void testLANG799_EN_FAIL() throws ParseException; @Test public void testLANG799_DE_OK() throws ParseException; @Test(expected=ParseException.class) public void testLANG799_DE_FAIL() throws ParseException; @Test public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException; private static void assertWeekIterator(final Iterator<?> it, final Calendar start); private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end); private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end); private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta); void warn(final String msg);
f33df2f4f91d0e0af951145915c7f80cbac40b5f022b8897885e86c4fd0f8e01
[ "org.apache.commons.lang3.time.DateUtilsTest::testRound" ]
public static final long MILLIS_PER_SECOND = 1000; public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; public static final int SEMI_MONTH = 1001; private static final int[][] fields = { {Calendar.MILLISECOND}, {Calendar.SECOND}, {Calendar.MINUTE}, {Calendar.HOUR_OF_DAY, Calendar.HOUR}, {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */ }, {Calendar.MONTH, DateUtils.SEMI_MONTH}, {Calendar.YEAR}, {Calendar.ERA}}; public static final int RANGE_WEEK_SUNDAY = 1; public static final int RANGE_WEEK_MONDAY = 2; public static final int RANGE_WEEK_RELATIVE = 3; public static final int RANGE_WEEK_CENTER = 4; public static final int RANGE_MONTH_SUNDAY = 5; public static final int RANGE_MONTH_MONDAY = 6; private static final int MODIFY_TRUNCATE = 0; private static final int MODIFY_ROUND = 1; private static final int MODIFY_CEILING = 2;
@Test public void testRound() throws Exception
private static final long MILLIS_TEST; DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null;
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.apache.commons.lang3.SystemUtils; import org.junit.Before; import org.junit.Test; /** * Unit tests {@link org.apache.commons.lang3.time.DateUtils}. * */ public class DateUtilsTest { private static final long MILLIS_TEST; static { final GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2); cal.set(Calendar.MILLISECOND, 1); MILLIS_TEST = cal.getTime().getTime(); System.out.println("DateUtilsTest: Default Locale="+Locale.getDefault()); } DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; @Before public void setUp() throws Exception { dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH); dateAmPm1 = dateTimeParser.parse("February 3, 2002 01:10:00.000"); dateAmPm2 = dateTimeParser.parse("February 3, 2002 11:10:00.000"); dateAmPm3 = dateTimeParser.parse("February 3, 2002 13:10:00.000"); dateAmPm4 = dateTimeParser.parse("February 3, 2002 19:10:00.000"); date0 = dateTimeParser.parse("February 3, 2002 12:34:56.789"); date1 = dateTimeParser.parse("February 12, 2002 12:34:56.789"); date2 = dateTimeParser.parse("November 18, 2001 1:23:11.321"); defaultZone = TimeZone.getDefault(); zone = TimeZone.getTimeZone("MET"); TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); date3 = dateTimeParser.parse("March 30, 2003 05:30:45.000"); date4 = dateTimeParser.parse("March 30, 2003 01:10:00.000"); date5 = dateTimeParser.parse("March 30, 2003 01:40:00.000"); date6 = dateTimeParser.parse("March 30, 2003 02:10:00.000"); date7 = dateTimeParser.parse("March 30, 2003 02:40:00.000"); date8 = dateTimeParser.parse("October 26, 2003 05:30:45.000"); dateTimeParser.setTimeZone(defaultZone); TimeZone.setDefault(defaultZone); calAmPm1 = Calendar.getInstance(); calAmPm1.setTime(dateAmPm1); calAmPm2 = Calendar.getInstance(); calAmPm2.setTime(dateAmPm2); calAmPm3 = Calendar.getInstance(); calAmPm3.setTime(dateAmPm3); calAmPm4 = Calendar.getInstance(); calAmPm4.setTime(dateAmPm4); cal1 = Calendar.getInstance(); cal1.setTime(date1); cal2 = Calendar.getInstance(); cal2.setTime(date2); TimeZone.setDefault(zone); cal3 = Calendar.getInstance(); cal3.setTime(date3); cal4 = Calendar.getInstance(); cal4.setTime(date4); cal5 = Calendar.getInstance(); cal5.setTime(date5); cal6 = Calendar.getInstance(); cal6.setTime(date6); cal7 = Calendar.getInstance(); cal7.setTime(date7); cal8 = Calendar.getInstance(); cal8.setTime(date8); TimeZone.setDefault(defaultZone); } //----------------------------------------------------------------------- @Test public void testConstructor() { assertNotNull(new DateUtils()); final Constructor<?>[] cons = DateUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(DateUtils.class.getModifiers())); assertFalse(Modifier.isFinal(DateUtils.class.getModifiers())); } //----------------------------------------------------------------------- @Test public void testIsSameDay_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertTrue(DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertFalse(DateUtils.isSameDay(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertTrue(DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertFalse(DateUtils.isSameDay(date1, date2)); try { DateUtils.isSameDay((Date) null, (Date) null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Test public void testIsSameDay_Cal() { final GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45); final GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45); assertTrue(DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.DAY_OF_YEAR, 1); assertFalse(DateUtils.isSameDay(cal1, cal2)); cal1.add(Calendar.DAY_OF_YEAR, 1); assertTrue(DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.YEAR, 1); assertFalse(DateUtils.isSameDay(cal1, cal2)); try { DateUtils.isSameDay((Calendar) null, (Calendar) null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Test public void testIsSameInstant_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertTrue(DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertFalse(DateUtils.isSameInstant(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertTrue(DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertFalse(DateUtils.isSameInstant(date1, date2)); try { DateUtils.isSameInstant((Date) null, (Date) null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Test public void testIsSameInstant_Cal() { final GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); final GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertFalse(DateUtils.isSameInstant(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertTrue(DateUtils.isSameInstant(cal1, cal2)); try { DateUtils.isSameInstant((Calendar) null, (Calendar) null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Test public void testIsSameLocalTime_Cal() { final GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); final GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertTrue(DateUtils.isSameLocalTime(cal1, cal2)); final Calendar cal3 = Calendar.getInstance(); final Calendar cal4 = Calendar.getInstance(); cal3.set(2004, 6, 9, 4, 0, 0); cal4.set(2004, 6, 9, 16, 0, 0); cal3.set(Calendar.MILLISECOND, 0); cal4.set(Calendar.MILLISECOND, 0); assertFalse("LANG-677", DateUtils.isSameLocalTime(cal3, cal4)); cal2.set(2004, 6, 9, 11, 45, 0); assertFalse(DateUtils.isSameLocalTime(cal1, cal2)); try { DateUtils.isSameLocalTime((Calendar) null, (Calendar) null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Test public void testParseDate() throws Exception { final GregorianCalendar cal = new GregorianCalendar(1972, 11, 3); String dateStr = "1972-12-03"; final String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "1972-338"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "19721203"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { DateUtils.parseDate("PURPLE", parsers); fail(); } catch (final ParseException ex) {} try { DateUtils.parseDate("197212AB", parsers); fail(); } catch (final ParseException ex) {} try { DateUtils.parseDate(null, parsers); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, (String[]) null); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, new String[0]); fail(); } catch (final ParseException ex) {} } // LANG-486 @Test public void testParseDateWithLeniency() throws Exception { final GregorianCalendar cal = new GregorianCalendar(1998, 6, 30); final String dateStr = "02 942, 1996"; final String[] parsers = new String[] {"MM DDD, yyyy"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { date = DateUtils.parseDateStrictly(dateStr, parsers); fail(); } catch (final ParseException ex) {} } //----------------------------------------------------------------------- @Test public void testAddYears() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addYears(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2001, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 1999, 6, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- @Test public void testAddMonths() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMonths(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 7, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- @Test public void testAddWeeks() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addWeeks(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addWeeks(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 12, 4, 3, 2, 1); result = DateUtils.addWeeks(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // july assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june } //----------------------------------------------------------------------- @Test public void testAddDays() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addDays(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 6, 4, 3, 2, 1); result = DateUtils.addDays(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 4, 4, 3, 2, 1); } //----------------------------------------------------------------------- @Test public void testAddHours() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addHours(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 5, 3, 2, 1); result = DateUtils.addHours(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 3, 3, 2, 1); } //----------------------------------------------------------------------- @Test public void testAddMinutes() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMinutes(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 4, 2, 1); result = DateUtils.addMinutes(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 2, 2, 1); } //----------------------------------------------------------------------- @Test public void testAddSeconds() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addSeconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 3, 1); result = DateUtils.addSeconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 1, 1); } //----------------------------------------------------------------------- @Test public void testAddMilliseconds() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMilliseconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 2); result = DateUtils.addMilliseconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); } // ----------------------------------------------------------------------- @Test public void testSetYears() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.setYears(base, 2000); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2008); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2008, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2005); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2005, 6, 5, 4, 3, 2, 1); } // ----------------------------------------------------------------------- @Test public void testSetMonths() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMonths(base, 5); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); result = DateUtils.setMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 1, 5, 4, 3, 2, 1); try { result = DateUtils.setMonths(base, 12); fail("DateUtils.setMonths did not throw an expected IllegalArguementException."); } catch (final IllegalArgumentException e) { } } // ----------------------------------------------------------------------- @Test public void testSetDays() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.setDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 1, 4, 3, 2, 1); result = DateUtils.setDays(base, 29); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 29, 4, 3, 2, 1); try { result = DateUtils.setDays(base, 32); fail("DateUtils.setDays did not throw an expected IllegalArguementException."); } catch (final IllegalArgumentException e) { } } // ----------------------------------------------------------------------- @Test public void testSetHours() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.setHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 0, 3, 2, 1); result = DateUtils.setHours(base, 23); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 23, 3, 2, 1); try { result = DateUtils.setHours(base, 24); fail("DateUtils.setHours did not throw an expected IllegalArguementException."); } catch (final IllegalArgumentException e) { } } // ----------------------------------------------------------------------- @Test public void testSetMinutes() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 0, 2, 1); result = DateUtils.setMinutes(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 59, 2, 1); try { result = DateUtils.setMinutes(base, 60); fail("DateUtils.setMinutes did not throw an expected IllegalArguementException."); } catch (final IllegalArgumentException e) { } } // ----------------------------------------------------------------------- @Test public void testSetSeconds() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.setSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 0, 1); result = DateUtils.setSeconds(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 59, 1); try { result = DateUtils.setSeconds(base, 60); fail("DateUtils.setSeconds did not throw an expected IllegalArguementException."); } catch (final IllegalArgumentException e) { } } // ----------------------------------------------------------------------- @Test public void testSetMilliseconds() throws Exception { final Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); result = DateUtils.setMilliseconds(base, 999); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 999); try { result = DateUtils.setMilliseconds(base, 1000); fail("DateUtils.setMilliseconds did not throw an expected IllegalArguementException."); } catch (final IllegalArgumentException e) { } } //----------------------------------------------------------------------- private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) throws Exception { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); assertEquals(year, cal.get(Calendar.YEAR)); assertEquals(month, cal.get(Calendar.MONTH)); assertEquals(day, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(min, cal.get(Calendar.MINUTE)); assertEquals(sec, cal.get(Calendar.SECOND)); assertEquals(mil, cal.get(Calendar.MILLISECOND)); } //----------------------------------------------------------------------- @Test public void testToCalendar() { assertEquals("Failed to convert to a Calendar and back", date1, DateUtils.toCalendar(date1).getTime()); try { DateUtils.toCalendar(null); fail("Expected NullPointerException to be thrown"); } catch(final NullPointerException npe) { // expected } } //----------------------------------------------------------------------- /** * Tests various values with the round method */ @Test public void testRound() throws Exception { // tests for public static Date round(Date date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round(date2, Calendar.MONTH)); assertEquals("round semimonth-0 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date0, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round(date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round(date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round(date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round(date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round(date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round(date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round(date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round(date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round(date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round(date2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round(dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round(dateAmPm4, Calendar.AM_PM)); // tests for public static Date round(Object date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round((Object) date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round((Object) date2, Calendar.MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round((Object) date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round((Object) date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round((Object) date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round((Object) date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round((Object) date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round((Object) date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) date2, Calendar.SECOND)); assertEquals("round calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) cal1, Calendar.SECOND)); assertEquals("round calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) cal2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm4, Calendar.AM_PM)); try { DateUtils.round((Date) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.round((Calendar) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.round((Object) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.round("", Calendar.SECOND); fail(); } catch (final ClassCastException ex) {} try { DateUtils.round(date1, -9999); fail(); } catch(final IllegalArgumentException ex) {} assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm4, Calendar.AM_PM)); // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 / LANG-13 // Test rounding across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round(date4, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round(date7, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date rounding tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); } /** * Tests the Changes Made by LANG-346 to the DateUtils.modify() private method invoked * by DateUtils.round(). */ @Test public void testRoundLang346() throws Exception { TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); final Calendar testCalendar = Calendar.getInstance(); testCalendar.set(2007, 6, 2, 8, 8, 50); Date date = testCalendar.getTime(); assertEquals("Minute Round Up Failed", dateTimeParser.parse("July 2, 2007 08:09:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 20); date = testCalendar.getTime(); assertEquals("Minute No Round Failed", dateTimeParser.parse("July 2, 2007 08:08:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 600 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:51.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:50.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:21.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:20.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); date = testCalendar.getTime(); assertEquals("Hour Round Down Failed", dateTimeParser.parse("July 2, 2007 08:00:00.000"), DateUtils.round(date, Calendar.HOUR)); testCalendar.set(2007, 6, 2, 8, 31, 50); date = testCalendar.getTime(); assertEquals("Hour Round Up Failed", dateTimeParser.parse("July 2, 2007 09:00:00.000"), DateUtils.round(date, Calendar.HOUR)); } /** * Tests various values with the trunc method */ @Test public void testTruncate() throws Exception { // tests public static Date truncate(Date date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate(date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate(date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate(date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate(date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate(date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate(date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate(date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate(date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate(date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate(date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate(date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm4, Calendar.AM_PM)); // tests public static Date truncate(Object date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate((Object) date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate((Object) date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate((Object) date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate((Object) date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate((Object) date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate((Object) date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate((Object) date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate((Object) date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate((Object) date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("truncate calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) cal1, Calendar.SECOND)); assertEquals("truncate calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.truncate((Date) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.truncate((Calendar) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.truncate((Object) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.truncate("", Calendar.SECOND); fail(); } catch (final ClassCastException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test truncate across beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate(date3, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate((Object) cal3, Calendar.DATE)); // Test truncate across end of daylight saving time assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate(date8, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate((Object) cal8, Calendar.DATE)); TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis final GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (final ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (final ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); final Calendar cal = DateUtils.truncate(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests for LANG-59 * * see http://issues.apache.org/jira/browse/LANG-59 */ @Test public void testTruncateLang59() throws Exception { if (!SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { this.warn("WARNING: Test for LANG-59 not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); return; } // Set TimeZone to Mountain Time final TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT"); TimeZone.setDefault(MST_MDT); final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); format.setTimeZone(MST_MDT); final Date oct31_01MDT = new Date(1099206000000L); final Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour final Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes final Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds final Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT)); assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT)); assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT)); assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT)); assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT)); // ------- Demonstrate Problem ------- final Calendar gval = Calendar.getInstance(); gval.setTime(new Date(oct31_01MDT.getTime())); gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L); // ---------- Test Truncate ---------- assertEquals("Truncate Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Truncate Calendar.SECOND", oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Truncate Calendar.MINUTE", oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Truncate Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Truncate Calendar.HOUR", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Truncate Calendar.DATE", oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE)); // ---------- Test Round (down) ---------- assertEquals("Round Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Round Calendar.SECOND", oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Round Calendar.MINUTE", oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Round Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Round Calendar.HOUR", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Round Calendar.DATE", oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE)); // restore default time zone TimeZone.setDefault(defaultZone); } // http://issues.apache.org/jira/browse/LANG-530 @Test public void testLang530() throws ParseException { final Date d = new Date(); final String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d); final Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() }); // the format loses milliseconds so have to reintroduce them assertEquals("Date not equal to itself ISO formatted and parsed", d.getTime(), d2.getTime() + d.getTime() % 1000); } /** * Tests various values with the ceiling method */ @Test public void testCeil() throws Exception { // test javadoc assertEquals("ceiling javadoc-1 failed", dateTimeParser.parse("March 28, 2002 14:00:00.000"), DateUtils.ceiling( dateTimeParser.parse("March 28, 2002 13:45:01.231"), Calendar.HOUR)); assertEquals("ceiling javadoc-2 failed", dateTimeParser.parse("April 1, 2002 00:00:00.000"), DateUtils.ceiling( dateTimeParser.parse("March 28, 2002 13:45:01.231"), Calendar.MONTH)); // tests public static Date ceiling(Date date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling(date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling(date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling(date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling(date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling(date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling(date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling(date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling(date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling(date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling(date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling(date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling(date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm4, Calendar.AM_PM)); // tests public static Date ceiling(Object date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling((Object) date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling((Object) date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling((Object) date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling((Object) date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling((Object) date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling((Object) date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling((Object) date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling((Object) date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling((Object) date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("ceiling calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) cal1, Calendar.SECOND)); assertEquals("ceiling calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) cal2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.ceiling((Date) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.ceiling((Calendar) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.ceiling((Object) null, Calendar.SECOND); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.ceiling("", Calendar.SECOND); fail(); } catch (final ClassCastException ex) {} try { DateUtils.ceiling(date1, -9999); fail(); } catch(final IllegalArgumentException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test ceiling across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date7, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date4, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date7, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date ceiling tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis final GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (final ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (final ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); final Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests the iterator exceptions */ @Test public void testIteratorEx() throws Exception { try { DateUtils.iterator(Calendar.getInstance(), -9999); } catch (final IllegalArgumentException ex) {} try { DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (final IllegalArgumentException ex) {} try { DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER); fail(); } catch (final ClassCastException ex) {} } /** * Tests the calendar iterator for week ranges */ @Test public void testWeekIterator() throws Exception { final Calendar now = Calendar.getInstance(); for (int i = 0; i< 7; i++) { final Calendar today = DateUtils.truncate(now, Calendar.DATE); final Calendar sunday = DateUtils.truncate(now, Calendar.DATE); sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK)); final Calendar monday = DateUtils.truncate(now, Calendar.DATE); if (monday.get(Calendar.DAY_OF_WEEK) == 1) { //This is sunday... roll back 6 days monday.add(Calendar.DATE, -6); } else { monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK)); } final Calendar centered = DateUtils.truncate(now, Calendar.DATE); centered.add(Calendar.DATE, -3); Iterator<?> it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_SUNDAY); assertWeekIterator(it, sunday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_MONDAY); assertWeekIterator(it, monday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_RELATIVE); assertWeekIterator(it, today); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); try { it.next(); fail(); } catch (final NoSuchElementException ex) {} it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); it.next(); try { it.remove(); } catch( final UnsupportedOperationException ex) {} now.add(Calendar.DATE,1); } } /** * Tests the calendar iterator for month-based ranges */ @Test public void testMonthIterator() throws Exception { Iterator<?> it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("January 27, 2002"), dateParser.parse("March 2, 2002")); it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("January 28, 2002"), dateParser.parse("March 3, 2002")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("October 28, 2001"), dateParser.parse("December 1, 2001")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("October 29, 2001"), dateParser.parse("December 2, 2001")); } @Test public void testLANG799_EN_OK() throws ParseException { final Locale dflt = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); try { DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"); DateUtils.parseDateStrictly("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"); } finally { Locale.setDefault(dflt); } } // Parse German date with English Locale @Test(expected=ParseException.class) public void testLANG799_EN_FAIL() throws ParseException { final Locale dflt = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); try { DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"); } finally { Locale.setDefault(dflt); } } @Test public void testLANG799_DE_OK() throws ParseException { final Locale dflt = Locale.getDefault(); Locale.setDefault(Locale.GERMAN); try { DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"); DateUtils.parseDateStrictly("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"); } finally { Locale.setDefault(dflt); } } // Parse English date with German Locale @Test(expected=ParseException.class) public void testLANG799_DE_FAIL() throws ParseException { final Locale dflt = Locale.getDefault(); Locale.setDefault(Locale.GERMAN); try { DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"); } finally { Locale.setDefault(dflt); } } // Parse German date with English Locale, specifying German Locale override @Test public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException { final Locale dflt = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); try { DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", Locale.GERMAN, "EEE, dd MMM yyyy HH:mm:ss zzz"); } finally { Locale.setDefault(dflt); } } /** * This checks that this is a 7 element iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other. */ private static void assertWeekIterator(final Iterator<?> it, final Calendar start) { final Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, 6); assertWeekIterator(it, start, end); } /** * Convenience method for when working with Date objects */ private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end) { final Calendar calStart = Calendar.getInstance(); calStart.setTime(start); final Calendar calEnd = Calendar.getInstance(); calEnd.setTime(end); assertWeekIterator(it, calStart, calEnd); } /** * This checks that this is a 7 divisble iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other * (in addition to the proper start and stop dates) */ private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end) { Calendar cal = (Calendar) it.next(); assertCalendarsEquals("", start, cal, 0); Calendar last = null; int count = 1; while (it.hasNext()) { //Check this is just a date (no time component) assertCalendarsEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0); last = cal; cal = (Calendar) it.next(); count++; //Check that this is one day more than the last date last.add(Calendar.DATE, 1); assertCalendarsEquals("", last, cal, 0); } if (count % 7 != 0) { throw new AssertionFailedError("There were " + count + " days in this iterator"); } assertCalendarsEquals("", end, cal, 0); } /** * Used to check that Calendar objects are close enough * delta is in milliseconds */ private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta) { if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) { throw new AssertionFailedError( message + " expected " + cal1.getTime() + " but got " + cal2.getTime()); } } void warn(final String msg) { System.err.println(msg); } }
[ { "be_test_class_file": "org/apache/commons/lang3/time/DateUtils.java", "be_test_class_name": "org.apache.commons.lang3.time.DateUtils", "be_test_function_name": "modify", "be_test_function_signature": "(Ljava/util/Calendar;II)V", "line_numbers": [ "957", "958", "961", "962", "971", "972", "973", "976", "977", "978", "980", "981", "985", "986", "987", "989", "990", "994", "995", "996", "1000", "1001", "1002", "1006", "1007", "1008", "1009", "1011", "1012", "1016", "1017", "1019", "1020", "1023", "1027", "1028", "1030", "1031", "1037", "1040", "1044", "1045", "1047", "1049", "1053", "1056", "1057", "1060", "1061", "1065", "1068", "1069", "1070", "1072", "1073", "1077", "1078", "1079", "1081", "1083", "1086", "1087", "1090" ], "method_line_rate": 0.9365079365079365 }, { "be_test_class_file": "org/apache/commons/lang3/time/DateUtils.java", "be_test_class_name": "org.apache.commons.lang3.time.DateUtils", "be_test_function_name": "round", "be_test_function_signature": "(Ljava/lang/Object;I)Ljava/util/Date;", "line_numbers": [ "774", "775", "777", "778", "779", "780", "782" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/time/DateUtils.java", "be_test_class_name": "org.apache.commons.lang3.time.DateUtils", "be_test_function_name": "round", "be_test_function_signature": "(Ljava/util/Calendar;I)Ljava/util/Calendar;", "line_numbers": [ "737", "738", "740", "741", "742" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/time/DateUtils.java", "be_test_class_name": "org.apache.commons.lang3.time.DateUtils", "be_test_function_name": "round", "be_test_function_signature": "(Ljava/util/Date;I)Ljava/util/Date;", "line_numbers": [ "700", "701", "703", "704", "705", "706" ], "method_line_rate": 1 } ]
public class ComplexTest
@Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty() { // The number 8 has three third roots. One we all already know is the number 2. // But there are two more complex roots. Complex z = new Complex(8,0); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(2.0, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(0.0, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.0, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(1.7320508075688774, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-1.0, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.732050807568877, thirdRootsOfZ[2].getImaginary(), 1.0e-5); }
// public void testScalarAdd(); // @Test // public void testScalarAddNaN(); // @Test // public void testScalarAddInf(); // @Test // public void testConjugate(); // @Test // public void testConjugateNaN(); // @Test // public void testConjugateInfiinite(); // @Test // public void testDivide(); // @Test // public void testDivideReal(); // @Test // public void testDivideImaginary(); // @Test // public void testDivideInf(); // @Test // public void testDivideZero(); // @Test // public void testDivideZeroZero(); // @Test // public void testDivideNaN(); // @Test // public void testDivideNaNInf(); // @Test // public void testScalarDivide(); // @Test // public void testScalarDivideNaN(); // @Test // public void testScalarDivideInf(); // @Test // public void testScalarDivideZero(); // @Test // public void testReciprocal(); // @Test // public void testReciprocalReal(); // @Test // public void testReciprocalImaginary(); // @Test // public void testReciprocalInf(); // @Test // public void testReciprocalZero(); // @Test // public void testReciprocalNaN(); // @Test // public void testMultiply(); // @Test // public void testMultiplyNaN(); // @Test // public void testMultiplyInfInf(); // @Test // public void testMultiplyNaNInf(); // @Test // public void testScalarMultiply(); // @Test // public void testScalarMultiplyNaN(); // @Test // public void testScalarMultiplyInf(); // @Test // public void testNegate(); // @Test // public void testNegateNaN(); // @Test // public void testSubtract(); // @Test // public void testSubtractNaN(); // @Test // public void testSubtractInf(); // @Test // public void testScalarSubtract(); // @Test // public void testScalarSubtractNaN(); // @Test // public void testScalarSubtractInf(); // @Test // public void testEqualsNull(); // @Test // public void testEqualsClass(); // @Test // public void testEqualsSame(); // @Test // public void testEqualsTrue(); // @Test // public void testEqualsRealDifference(); // @Test // public void testEqualsImaginaryDifference(); // @Test // public void testEqualsNaN(); // @Test // public void testHashCode(); // @Test // public void testAcos(); // @Test // public void testAcosInf(); // @Test // public void testAcosNaN(); // @Test // public void testAsin(); // @Test // public void testAsinNaN(); // @Test // public void testAsinInf(); // @Test // public void testAtan(); // @Test // public void testAtanInf(); // @Test // public void testAtanI(); // @Test // public void testAtanNaN(); // @Test // public void testCos(); // @Test // public void testCosNaN(); // @Test // public void testCosInf(); // @Test // public void testCosh(); // @Test // public void testCoshNaN(); // @Test // public void testCoshInf(); // @Test // public void testExp(); // @Test // public void testExpNaN(); // @Test // public void testExpInf(); // @Test // public void testLog(); // @Test // public void testLogNaN(); // @Test // public void testLogInf(); // @Test // public void testLogZero(); // @Test // public void testPow(); // @Test // public void testPowNaNBase(); // @Test // public void testPowNaNExponent(); // @Test // public void testPowInf(); // @Test // public void testPowZero(); // @Test // public void testScalarPow(); // @Test // public void testScalarPowNaNBase(); // @Test // public void testScalarPowNaNExponent(); // @Test // public void testScalarPowInf(); // @Test // public void testScalarPowZero(); // @Test(expected=NullArgumentException.class) // public void testpowNull(); // @Test // public void testSin(); // @Test // public void testSinInf(); // @Test // public void testSinNaN(); // @Test // public void testSinh(); // @Test // public void testSinhNaN(); // @Test // public void testSinhInf(); // @Test // public void testSqrtRealPositive(); // @Test // public void testSqrtRealZero(); // @Test // public void testSqrtRealNegative(); // @Test // public void testSqrtImaginaryZero(); // @Test // public void testSqrtImaginaryNegative(); // @Test // public void testSqrtPolar(); // @Test // public void testSqrtNaN(); // @Test // public void testSqrtInf(); // @Test // public void testSqrt1z(); // @Test // public void testSqrt1zNaN(); // @Test // public void testTan(); // @Test // public void testTanNaN(); // @Test // public void testTanInf(); // @Test // public void testTanCritical(); // @Test // public void testTanh(); // @Test // public void testTanhNaN(); // @Test // public void testTanhInf(); // @Test // public void testTanhCritical(); // @Test // public void testMath221(); // @Test // public void testNthRoot_normal_thirdRoot(); // @Test // public void testNthRoot_normal_fourthRoot(); // @Test // public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty(); // @Test // public void testNthRoot_cornercase_thirdRoot_realPartZero(); // @Test // public void testNthRoot_cornercase_NAN_Inf(); // @Test // public void testGetArgument(); // @Test // public void testGetArgumentInf(); // @Test // public void testGetArgumentNaN(); // @Test // public void testSerial(); // public TestComplex(double real, double imaginary); // public TestComplex(Complex other); // @Override // protected TestComplex createComplex(double real, double imaginary); // } // You are a professional Java test case writer, please create a test case named `testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */
src/test/java/org/apache/commons/math3/complex/ComplexTest.java
package org.apache.commons.math3.complex; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.FieldElement; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils;
public Complex(double real); public Complex(double real, double imaginary); public double abs(); public Complex add(Complex addend) throws NullArgumentException; public Complex add(double addend); public Complex conjugate(); public Complex divide(Complex divisor) throws NullArgumentException; public Complex divide(double divisor); public Complex reciprocal(); @Override public boolean equals(Object other); @Override public int hashCode(); public double getImaginary(); public double getReal(); public boolean isNaN(); public boolean isInfinite(); public Complex multiply(Complex factor) throws NullArgumentException; public Complex multiply(final int factor); public Complex multiply(double factor); public Complex negate(); public Complex subtract(Complex subtrahend) throws NullArgumentException; public Complex subtract(double subtrahend); public Complex acos(); public Complex asin(); public Complex atan(); public Complex cos(); public Complex cosh(); public Complex exp(); public Complex log(); public Complex pow(Complex x) throws NullArgumentException; public Complex pow(double x); public Complex sin(); public Complex sinh(); public Complex sqrt(); public Complex sqrt1z(); public Complex tan(); public Complex tanh(); public double getArgument(); public List<Complex> nthRoot(int n) throws NotPositiveException; protected Complex createComplex(double realPart, double imaginaryPart); public static Complex valueOf(double realPart, double imaginaryPart); public static Complex valueOf(double realPart); protected final Object readResolve(); public ComplexField getField(); @Override public String toString();
1,166
testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty
```java public void testScalarAdd(); @Test public void testScalarAddNaN(); @Test public void testScalarAddInf(); @Test public void testConjugate(); @Test public void testConjugateNaN(); @Test public void testConjugateInfiinite(); @Test public void testDivide(); @Test public void testDivideReal(); @Test public void testDivideImaginary(); @Test public void testDivideInf(); @Test public void testDivideZero(); @Test public void testDivideZeroZero(); @Test public void testDivideNaN(); @Test public void testDivideNaNInf(); @Test public void testScalarDivide(); @Test public void testScalarDivideNaN(); @Test public void testScalarDivideInf(); @Test public void testScalarDivideZero(); @Test public void testReciprocal(); @Test public void testReciprocalReal(); @Test public void testReciprocalImaginary(); @Test public void testReciprocalInf(); @Test public void testReciprocalZero(); @Test public void testReciprocalNaN(); @Test public void testMultiply(); @Test public void testMultiplyNaN(); @Test public void testMultiplyInfInf(); @Test public void testMultiplyNaNInf(); @Test public void testScalarMultiply(); @Test public void testScalarMultiplyNaN(); @Test public void testScalarMultiplyInf(); @Test public void testNegate(); @Test public void testNegateNaN(); @Test public void testSubtract(); @Test public void testSubtractNaN(); @Test public void testSubtractInf(); @Test public void testScalarSubtract(); @Test public void testScalarSubtractNaN(); @Test public void testScalarSubtractInf(); @Test public void testEqualsNull(); @Test public void testEqualsClass(); @Test public void testEqualsSame(); @Test public void testEqualsTrue(); @Test public void testEqualsRealDifference(); @Test public void testEqualsImaginaryDifference(); @Test public void testEqualsNaN(); @Test public void testHashCode(); @Test public void testAcos(); @Test public void testAcosInf(); @Test public void testAcosNaN(); @Test public void testAsin(); @Test public void testAsinNaN(); @Test public void testAsinInf(); @Test public void testAtan(); @Test public void testAtanInf(); @Test public void testAtanI(); @Test public void testAtanNaN(); @Test public void testCos(); @Test public void testCosNaN(); @Test public void testCosInf(); @Test public void testCosh(); @Test public void testCoshNaN(); @Test public void testCoshInf(); @Test public void testExp(); @Test public void testExpNaN(); @Test public void testExpInf(); @Test public void testLog(); @Test public void testLogNaN(); @Test public void testLogInf(); @Test public void testLogZero(); @Test public void testPow(); @Test public void testPowNaNBase(); @Test public void testPowNaNExponent(); @Test public void testPowInf(); @Test public void testPowZero(); @Test public void testScalarPow(); @Test public void testScalarPowNaNBase(); @Test public void testScalarPowNaNExponent(); @Test public void testScalarPowInf(); @Test public void testScalarPowZero(); @Test(expected=NullArgumentException.class) public void testpowNull(); @Test public void testSin(); @Test public void testSinInf(); @Test public void testSinNaN(); @Test public void testSinh(); @Test public void testSinhNaN(); @Test public void testSinhInf(); @Test public void testSqrtRealPositive(); @Test public void testSqrtRealZero(); @Test public void testSqrtRealNegative(); @Test public void testSqrtImaginaryZero(); @Test public void testSqrtImaginaryNegative(); @Test public void testSqrtPolar(); @Test public void testSqrtNaN(); @Test public void testSqrtInf(); @Test public void testSqrt1z(); @Test public void testSqrt1zNaN(); @Test public void testTan(); @Test public void testTanNaN(); @Test public void testTanInf(); @Test public void testTanCritical(); @Test public void testTanh(); @Test public void testTanhNaN(); @Test public void testTanhInf(); @Test public void testTanhCritical(); @Test public void testMath221(); @Test public void testNthRoot_normal_thirdRoot(); @Test public void testNthRoot_normal_fourthRoot(); @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty(); @Test public void testNthRoot_cornercase_thirdRoot_realPartZero(); @Test public void testNthRoot_cornercase_NAN_Inf(); @Test public void testGetArgument(); @Test public void testGetArgumentInf(); @Test public void testGetArgumentNaN(); @Test public void testSerial(); public TestComplex(double real, double imaginary); public TestComplex(Complex other); @Override protected TestComplex createComplex(double real, double imaginary); } ``` You are a professional Java test case writer, please create a test case named `testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */
1,148
// public void testScalarAdd(); // @Test // public void testScalarAddNaN(); // @Test // public void testScalarAddInf(); // @Test // public void testConjugate(); // @Test // public void testConjugateNaN(); // @Test // public void testConjugateInfiinite(); // @Test // public void testDivide(); // @Test // public void testDivideReal(); // @Test // public void testDivideImaginary(); // @Test // public void testDivideInf(); // @Test // public void testDivideZero(); // @Test // public void testDivideZeroZero(); // @Test // public void testDivideNaN(); // @Test // public void testDivideNaNInf(); // @Test // public void testScalarDivide(); // @Test // public void testScalarDivideNaN(); // @Test // public void testScalarDivideInf(); // @Test // public void testScalarDivideZero(); // @Test // public void testReciprocal(); // @Test // public void testReciprocalReal(); // @Test // public void testReciprocalImaginary(); // @Test // public void testReciprocalInf(); // @Test // public void testReciprocalZero(); // @Test // public void testReciprocalNaN(); // @Test // public void testMultiply(); // @Test // public void testMultiplyNaN(); // @Test // public void testMultiplyInfInf(); // @Test // public void testMultiplyNaNInf(); // @Test // public void testScalarMultiply(); // @Test // public void testScalarMultiplyNaN(); // @Test // public void testScalarMultiplyInf(); // @Test // public void testNegate(); // @Test // public void testNegateNaN(); // @Test // public void testSubtract(); // @Test // public void testSubtractNaN(); // @Test // public void testSubtractInf(); // @Test // public void testScalarSubtract(); // @Test // public void testScalarSubtractNaN(); // @Test // public void testScalarSubtractInf(); // @Test // public void testEqualsNull(); // @Test // public void testEqualsClass(); // @Test // public void testEqualsSame(); // @Test // public void testEqualsTrue(); // @Test // public void testEqualsRealDifference(); // @Test // public void testEqualsImaginaryDifference(); // @Test // public void testEqualsNaN(); // @Test // public void testHashCode(); // @Test // public void testAcos(); // @Test // public void testAcosInf(); // @Test // public void testAcosNaN(); // @Test // public void testAsin(); // @Test // public void testAsinNaN(); // @Test // public void testAsinInf(); // @Test // public void testAtan(); // @Test // public void testAtanInf(); // @Test // public void testAtanI(); // @Test // public void testAtanNaN(); // @Test // public void testCos(); // @Test // public void testCosNaN(); // @Test // public void testCosInf(); // @Test // public void testCosh(); // @Test // public void testCoshNaN(); // @Test // public void testCoshInf(); // @Test // public void testExp(); // @Test // public void testExpNaN(); // @Test // public void testExpInf(); // @Test // public void testLog(); // @Test // public void testLogNaN(); // @Test // public void testLogInf(); // @Test // public void testLogZero(); // @Test // public void testPow(); // @Test // public void testPowNaNBase(); // @Test // public void testPowNaNExponent(); // @Test // public void testPowInf(); // @Test // public void testPowZero(); // @Test // public void testScalarPow(); // @Test // public void testScalarPowNaNBase(); // @Test // public void testScalarPowNaNExponent(); // @Test // public void testScalarPowInf(); // @Test // public void testScalarPowZero(); // @Test(expected=NullArgumentException.class) // public void testpowNull(); // @Test // public void testSin(); // @Test // public void testSinInf(); // @Test // public void testSinNaN(); // @Test // public void testSinh(); // @Test // public void testSinhNaN(); // @Test // public void testSinhInf(); // @Test // public void testSqrtRealPositive(); // @Test // public void testSqrtRealZero(); // @Test // public void testSqrtRealNegative(); // @Test // public void testSqrtImaginaryZero(); // @Test // public void testSqrtImaginaryNegative(); // @Test // public void testSqrtPolar(); // @Test // public void testSqrtNaN(); // @Test // public void testSqrtInf(); // @Test // public void testSqrt1z(); // @Test // public void testSqrt1zNaN(); // @Test // public void testTan(); // @Test // public void testTanNaN(); // @Test // public void testTanInf(); // @Test // public void testTanCritical(); // @Test // public void testTanh(); // @Test // public void testTanhNaN(); // @Test // public void testTanhInf(); // @Test // public void testTanhCritical(); // @Test // public void testMath221(); // @Test // public void testNthRoot_normal_thirdRoot(); // @Test // public void testNthRoot_normal_fourthRoot(); // @Test // public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty(); // @Test // public void testNthRoot_cornercase_thirdRoot_realPartZero(); // @Test // public void testNthRoot_cornercase_NAN_Inf(); // @Test // public void testGetArgument(); // @Test // public void testGetArgumentInf(); // @Test // public void testGetArgumentNaN(); // @Test // public void testSerial(); // public TestComplex(double real, double imaginary); // public TestComplex(Complex other); // @Override // protected TestComplex createComplex(double real, double imaginary); // } // You are a professional Java test case writer, please create a test case named `testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty() {
/** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */
1
org.apache.commons.math3.complex.Complex
src/test/java
```java public void testScalarAdd(); @Test public void testScalarAddNaN(); @Test public void testScalarAddInf(); @Test public void testConjugate(); @Test public void testConjugateNaN(); @Test public void testConjugateInfiinite(); @Test public void testDivide(); @Test public void testDivideReal(); @Test public void testDivideImaginary(); @Test public void testDivideInf(); @Test public void testDivideZero(); @Test public void testDivideZeroZero(); @Test public void testDivideNaN(); @Test public void testDivideNaNInf(); @Test public void testScalarDivide(); @Test public void testScalarDivideNaN(); @Test public void testScalarDivideInf(); @Test public void testScalarDivideZero(); @Test public void testReciprocal(); @Test public void testReciprocalReal(); @Test public void testReciprocalImaginary(); @Test public void testReciprocalInf(); @Test public void testReciprocalZero(); @Test public void testReciprocalNaN(); @Test public void testMultiply(); @Test public void testMultiplyNaN(); @Test public void testMultiplyInfInf(); @Test public void testMultiplyNaNInf(); @Test public void testScalarMultiply(); @Test public void testScalarMultiplyNaN(); @Test public void testScalarMultiplyInf(); @Test public void testNegate(); @Test public void testNegateNaN(); @Test public void testSubtract(); @Test public void testSubtractNaN(); @Test public void testSubtractInf(); @Test public void testScalarSubtract(); @Test public void testScalarSubtractNaN(); @Test public void testScalarSubtractInf(); @Test public void testEqualsNull(); @Test public void testEqualsClass(); @Test public void testEqualsSame(); @Test public void testEqualsTrue(); @Test public void testEqualsRealDifference(); @Test public void testEqualsImaginaryDifference(); @Test public void testEqualsNaN(); @Test public void testHashCode(); @Test public void testAcos(); @Test public void testAcosInf(); @Test public void testAcosNaN(); @Test public void testAsin(); @Test public void testAsinNaN(); @Test public void testAsinInf(); @Test public void testAtan(); @Test public void testAtanInf(); @Test public void testAtanI(); @Test public void testAtanNaN(); @Test public void testCos(); @Test public void testCosNaN(); @Test public void testCosInf(); @Test public void testCosh(); @Test public void testCoshNaN(); @Test public void testCoshInf(); @Test public void testExp(); @Test public void testExpNaN(); @Test public void testExpInf(); @Test public void testLog(); @Test public void testLogNaN(); @Test public void testLogInf(); @Test public void testLogZero(); @Test public void testPow(); @Test public void testPowNaNBase(); @Test public void testPowNaNExponent(); @Test public void testPowInf(); @Test public void testPowZero(); @Test public void testScalarPow(); @Test public void testScalarPowNaNBase(); @Test public void testScalarPowNaNExponent(); @Test public void testScalarPowInf(); @Test public void testScalarPowZero(); @Test(expected=NullArgumentException.class) public void testpowNull(); @Test public void testSin(); @Test public void testSinInf(); @Test public void testSinNaN(); @Test public void testSinh(); @Test public void testSinhNaN(); @Test public void testSinhInf(); @Test public void testSqrtRealPositive(); @Test public void testSqrtRealZero(); @Test public void testSqrtRealNegative(); @Test public void testSqrtImaginaryZero(); @Test public void testSqrtImaginaryNegative(); @Test public void testSqrtPolar(); @Test public void testSqrtNaN(); @Test public void testSqrtInf(); @Test public void testSqrt1z(); @Test public void testSqrt1zNaN(); @Test public void testTan(); @Test public void testTanNaN(); @Test public void testTanInf(); @Test public void testTanCritical(); @Test public void testTanh(); @Test public void testTanhNaN(); @Test public void testTanhInf(); @Test public void testTanhCritical(); @Test public void testMath221(); @Test public void testNthRoot_normal_thirdRoot(); @Test public void testNthRoot_normal_fourthRoot(); @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty(); @Test public void testNthRoot_cornercase_thirdRoot_realPartZero(); @Test public void testNthRoot_cornercase_NAN_Inf(); @Test public void testGetArgument(); @Test public void testGetArgumentInf(); @Test public void testGetArgumentNaN(); @Test public void testSerial(); public TestComplex(double real, double imaginary); public TestComplex(Complex other); @Override protected TestComplex createComplex(double real, double imaginary); } ``` You are a professional Java test case writer, please create a test case named `testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty() { ```
public class Complex implements FieldElement<Complex>, Serializable
package org.apache.commons.math3.complex; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; import java.util.List;
@Test public void testConstructor(); @Test public void testConstructorNaN(); @Test public void testAbs(); @Test public void testAbsNaN(); @Test public void testAbsInfinite(); @Test public void testAdd(); @Test public void testAddNaN(); @Test public void testAddInf(); @Test public void testScalarAdd(); @Test public void testScalarAddNaN(); @Test public void testScalarAddInf(); @Test public void testConjugate(); @Test public void testConjugateNaN(); @Test public void testConjugateInfiinite(); @Test public void testDivide(); @Test public void testDivideReal(); @Test public void testDivideImaginary(); @Test public void testDivideInf(); @Test public void testDivideZero(); @Test public void testDivideZeroZero(); @Test public void testDivideNaN(); @Test public void testDivideNaNInf(); @Test public void testScalarDivide(); @Test public void testScalarDivideNaN(); @Test public void testScalarDivideInf(); @Test public void testScalarDivideZero(); @Test public void testReciprocal(); @Test public void testReciprocalReal(); @Test public void testReciprocalImaginary(); @Test public void testReciprocalInf(); @Test public void testReciprocalZero(); @Test public void testReciprocalNaN(); @Test public void testMultiply(); @Test public void testMultiplyNaN(); @Test public void testMultiplyInfInf(); @Test public void testMultiplyNaNInf(); @Test public void testScalarMultiply(); @Test public void testScalarMultiplyNaN(); @Test public void testScalarMultiplyInf(); @Test public void testNegate(); @Test public void testNegateNaN(); @Test public void testSubtract(); @Test public void testSubtractNaN(); @Test public void testSubtractInf(); @Test public void testScalarSubtract(); @Test public void testScalarSubtractNaN(); @Test public void testScalarSubtractInf(); @Test public void testEqualsNull(); @Test public void testEqualsClass(); @Test public void testEqualsSame(); @Test public void testEqualsTrue(); @Test public void testEqualsRealDifference(); @Test public void testEqualsImaginaryDifference(); @Test public void testEqualsNaN(); @Test public void testHashCode(); @Test public void testAcos(); @Test public void testAcosInf(); @Test public void testAcosNaN(); @Test public void testAsin(); @Test public void testAsinNaN(); @Test public void testAsinInf(); @Test public void testAtan(); @Test public void testAtanInf(); @Test public void testAtanI(); @Test public void testAtanNaN(); @Test public void testCos(); @Test public void testCosNaN(); @Test public void testCosInf(); @Test public void testCosh(); @Test public void testCoshNaN(); @Test public void testCoshInf(); @Test public void testExp(); @Test public void testExpNaN(); @Test public void testExpInf(); @Test public void testLog(); @Test public void testLogNaN(); @Test public void testLogInf(); @Test public void testLogZero(); @Test public void testPow(); @Test public void testPowNaNBase(); @Test public void testPowNaNExponent(); @Test public void testPowInf(); @Test public void testPowZero(); @Test public void testScalarPow(); @Test public void testScalarPowNaNBase(); @Test public void testScalarPowNaNExponent(); @Test public void testScalarPowInf(); @Test public void testScalarPowZero(); @Test(expected=NullArgumentException.class) public void testpowNull(); @Test public void testSin(); @Test public void testSinInf(); @Test public void testSinNaN(); @Test public void testSinh(); @Test public void testSinhNaN(); @Test public void testSinhInf(); @Test public void testSqrtRealPositive(); @Test public void testSqrtRealZero(); @Test public void testSqrtRealNegative(); @Test public void testSqrtImaginaryZero(); @Test public void testSqrtImaginaryNegative(); @Test public void testSqrtPolar(); @Test public void testSqrtNaN(); @Test public void testSqrtInf(); @Test public void testSqrt1z(); @Test public void testSqrt1zNaN(); @Test public void testTan(); @Test public void testTanNaN(); @Test public void testTanInf(); @Test public void testTanCritical(); @Test public void testTanh(); @Test public void testTanhNaN(); @Test public void testTanhInf(); @Test public void testTanhCritical(); @Test public void testMath221(); @Test public void testNthRoot_normal_thirdRoot(); @Test public void testNthRoot_normal_fourthRoot(); @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty(); @Test public void testNthRoot_cornercase_thirdRoot_realPartZero(); @Test public void testNthRoot_cornercase_NAN_Inf(); @Test public void testGetArgument(); @Test public void testGetArgumentInf(); @Test public void testGetArgumentNaN(); @Test public void testSerial(); public TestComplex(double real, double imaginary); public TestComplex(Complex other); @Override protected TestComplex createComplex(double real, double imaginary);
f6860ee8198322da690ef2ef99268e293940ae22c6b04db71f3fa299ba8a8dd5
[ "org.apache.commons.math3.complex.ComplexTest::testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty" ]
public static final Complex I = new Complex(0.0, 1.0); public static final Complex NaN = new Complex(Double.NaN, Double.NaN); public static final Complex INF = new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); public static final Complex ONE = new Complex(1.0, 0.0); public static final Complex ZERO = new Complex(0.0, 0.0); private static final long serialVersionUID = -6195664516687396620L; private final double imaginary; private final double real; private final transient boolean isNaN; private final transient boolean isInfinite;
@Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty()
private double inf = Double.POSITIVE_INFINITY; private double neginf = Double.NEGATIVE_INFINITY; private double nan = Double.NaN; private double pi = FastMath.PI; private Complex oneInf = new Complex(1, inf); private Complex oneNegInf = new Complex(1, neginf); private Complex infOne = new Complex(inf, 1); private Complex infZero = new Complex(inf, 0); private Complex infNaN = new Complex(inf, nan); private Complex infNegInf = new Complex(inf, neginf); private Complex infInf = new Complex(inf, inf); private Complex negInfInf = new Complex(neginf, inf); private Complex negInfZero = new Complex(neginf, 0); private Complex negInfOne = new Complex(neginf, 1); private Complex negInfNaN = new Complex(neginf, nan); private Complex negInfNegInf = new Complex(neginf, neginf); private Complex oneNaN = new Complex(1, nan); private Complex zeroInf = new Complex(0, inf); private Complex zeroNaN = new Complex(0, nan); private Complex nanInf = new Complex(nan, inf); private Complex nanNegInf = new Complex(nan, neginf); private Complex nanZero = new Complex(nan, 0);
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.complex; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * @version $Id$ */ public class ComplexTest { private double inf = Double.POSITIVE_INFINITY; private double neginf = Double.NEGATIVE_INFINITY; private double nan = Double.NaN; private double pi = FastMath.PI; private Complex oneInf = new Complex(1, inf); private Complex oneNegInf = new Complex(1, neginf); private Complex infOne = new Complex(inf, 1); private Complex infZero = new Complex(inf, 0); private Complex infNaN = new Complex(inf, nan); private Complex infNegInf = new Complex(inf, neginf); private Complex infInf = new Complex(inf, inf); private Complex negInfInf = new Complex(neginf, inf); private Complex negInfZero = new Complex(neginf, 0); private Complex negInfOne = new Complex(neginf, 1); private Complex negInfNaN = new Complex(neginf, nan); private Complex negInfNegInf = new Complex(neginf, neginf); private Complex oneNaN = new Complex(1, nan); private Complex zeroInf = new Complex(0, inf); private Complex zeroNaN = new Complex(0, nan); private Complex nanInf = new Complex(nan, inf); private Complex nanNegInf = new Complex(nan, neginf); private Complex nanZero = new Complex(nan, 0); @Test public void testConstructor() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(3.0, z.getReal(), 1.0e-5); Assert.assertEquals(4.0, z.getImaginary(), 1.0e-5); } @Test public void testConstructorNaN() { Complex z = new Complex(3.0, Double.NaN); Assert.assertTrue(z.isNaN()); z = new Complex(nan, 4.0); Assert.assertTrue(z.isNaN()); z = new Complex(3.0, 4.0); Assert.assertFalse(z.isNaN()); } @Test public void testAbs() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(5.0, z.abs(), 1.0e-5); } @Test public void testAbsNaN() { Assert.assertTrue(Double.isNaN(Complex.NaN.abs())); Complex z = new Complex(inf, nan); Assert.assertTrue(Double.isNaN(z.abs())); } @Test public void testAbsInfinite() { Complex z = new Complex(inf, 0); Assert.assertEquals(inf, z.abs(), 0); z = new Complex(0, neginf); Assert.assertEquals(inf, z.abs(), 0); z = new Complex(inf, neginf); Assert.assertEquals(inf, z.abs(), 0); } @Test public void testAdd() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.add(y); Assert.assertEquals(8.0, z.getReal(), 1.0e-5); Assert.assertEquals(10.0, z.getImaginary(), 1.0e-5); } @Test public void testAddNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.add(Complex.NaN); Assert.assertSame(Complex.NaN, z); z = new Complex(1, nan); Complex w = x.add(z); Assert.assertSame(Complex.NaN, w); } @Test public void testAddInf() { Complex x = new Complex(1, 1); Complex z = new Complex(inf, 0); Complex w = x.add(z); Assert.assertEquals(w.getImaginary(), 1, 0); Assert.assertEquals(inf, w.getReal(), 0); x = new Complex(neginf, 0); Assert.assertTrue(Double.isNaN(x.add(z).getReal())); } @Test public void testScalarAdd() { Complex x = new Complex(3.0, 4.0); double yDouble = 2.0; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.add(yComplex), x.add(yDouble)); } @Test public void testScalarAddNaN() { Complex x = new Complex(3.0, 4.0); double yDouble = Double.NaN; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.add(yComplex), x.add(yDouble)); } @Test public void testScalarAddInf() { Complex x = new Complex(1, 1); double yDouble = Double.POSITIVE_INFINITY; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.add(yComplex), x.add(yDouble)); x = new Complex(neginf, 0); Assert.assertEquals(x.add(yComplex), x.add(yDouble)); } @Test public void testConjugate() { Complex x = new Complex(3.0, 4.0); Complex z = x.conjugate(); Assert.assertEquals(3.0, z.getReal(), 1.0e-5); Assert.assertEquals(-4.0, z.getImaginary(), 1.0e-5); } @Test public void testConjugateNaN() { Complex z = Complex.NaN.conjugate(); Assert.assertTrue(z.isNaN()); } @Test public void testConjugateInfiinite() { Complex z = new Complex(0, inf); Assert.assertEquals(neginf, z.conjugate().getImaginary(), 0); z = new Complex(0, neginf); Assert.assertEquals(inf, z.conjugate().getImaginary(), 0); } @Test public void testDivide() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.divide(y); Assert.assertEquals(39.0 / 61.0, z.getReal(), 1.0e-5); Assert.assertEquals(2.0 / 61.0, z.getImaginary(), 1.0e-5); } @Test public void testDivideReal() { Complex x = new Complex(2d, 3d); Complex y = new Complex(2d, 0d); Assert.assertEquals(new Complex(1d, 1.5), x.divide(y)); } @Test public void testDivideImaginary() { Complex x = new Complex(2d, 3d); Complex y = new Complex(0d, 2d); Assert.assertEquals(new Complex(1.5d, -1d), x.divide(y)); } @Test public void testDivideInf() { Complex x = new Complex(3, 4); Complex w = new Complex(neginf, inf); Assert.assertTrue(x.divide(w).equals(Complex.ZERO)); Complex z = w.divide(x); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertEquals(inf, z.getImaginary(), 0); w = new Complex(inf, inf); z = w.divide(x); Assert.assertTrue(Double.isNaN(z.getImaginary())); Assert.assertEquals(inf, z.getReal(), 0); w = new Complex(1, inf); z = w.divide(w); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); } @Test public void testDivideZero() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.ZERO); // Assert.assertEquals(z, Complex.INF); // See MATH-657 Assert.assertEquals(z, Complex.NaN); } @Test public void testDivideZeroZero() { Complex x = new Complex(0.0, 0.0); Complex z = x.divide(Complex.ZERO); Assert.assertEquals(z, Complex.NaN); } @Test public void testDivideNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testDivideNaNInf() { Complex z = oneInf.divide(Complex.ONE); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertEquals(inf, z.getImaginary(), 0); z = negInfNegInf.divide(oneNaN); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); z = negInfInf.divide(Complex.ONE); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); } @Test public void testScalarDivide() { Complex x = new Complex(3.0, 4.0); double yDouble = 2.0; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.divide(yComplex), x.divide(yDouble)); } @Test public void testScalarDivideNaN() { Complex x = new Complex(3.0, 4.0); double yDouble = Double.NaN; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.divide(yComplex), x.divide(yDouble)); } @Test public void testScalarDivideInf() { Complex x = new Complex(1,1); double yDouble = Double.POSITIVE_INFINITY; Complex yComplex = new Complex(yDouble); TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0); yDouble = Double.NEGATIVE_INFINITY; yComplex = new Complex(yDouble); TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0); x = new Complex(1, Double.NEGATIVE_INFINITY); TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0); } @Test public void testScalarDivideZero() { Complex x = new Complex(1,1); TestUtils.assertEquals(x.divide(Complex.ZERO), x.divide(0), 0); } @Test public void testReciprocal() { Complex z = new Complex(5.0, 6.0); Complex act = z.reciprocal(); double expRe = 5.0 / 61.0; double expIm = -6.0 / 61.0; Assert.assertEquals(expRe, act.getReal(), FastMath.ulp(expRe)); Assert.assertEquals(expIm, act.getImaginary(), FastMath.ulp(expIm)); } @Test public void testReciprocalReal() { Complex z = new Complex(-2.0, 0.0); Assert.assertEquals(new Complex(-0.5, 0.0), z.reciprocal()); } @Test public void testReciprocalImaginary() { Complex z = new Complex(0.0, -2.0); Assert.assertEquals(new Complex(0.0, 0.5), z.reciprocal()); } @Test public void testReciprocalInf() { Complex z = new Complex(neginf, inf); Assert.assertTrue(z.reciprocal().equals(Complex.ZERO)); z = new Complex(1, inf).reciprocal(); Assert.assertEquals(z, Complex.ZERO); } @Test public void testReciprocalZero() { Assert.assertEquals(Complex.ZERO.reciprocal(), Complex.INF); } @Test public void testReciprocalNaN() { Assert.assertTrue(Complex.NaN.reciprocal().isNaN()); } @Test public void testMultiply() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.multiply(y); Assert.assertEquals(-9.0, z.getReal(), 1.0e-5); Assert.assertEquals(38.0, z.getImaginary(), 1.0e-5); } @Test public void testMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Complex.NaN); Assert.assertSame(Complex.NaN, z); z = Complex.NaN.multiply(5); Assert.assertSame(Complex.NaN, z); } @Test public void testMultiplyInfInf() { // Assert.assertTrue(infInf.multiply(infInf).isNaN()); // MATH-620 Assert.assertTrue(infInf.multiply(infInf).isInfinite()); } @Test public void testMultiplyNaNInf() { Complex z = new Complex(1,1); Complex w = z.multiply(infOne); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); // [MATH-164] Assert.assertTrue(new Complex( 1,0).multiply(infInf).equals(Complex.INF)); Assert.assertTrue(new Complex(-1,0).multiply(infInf).equals(Complex.INF)); Assert.assertTrue(new Complex( 1,0).multiply(negInfZero).equals(Complex.INF)); w = oneInf.multiply(oneNegInf); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); w = negInfNegInf.multiply(oneNaN); Assert.assertTrue(Double.isNaN(w.getReal())); Assert.assertTrue(Double.isNaN(w.getImaginary())); z = new Complex(1, neginf); Assert.assertSame(Complex.INF, z.multiply(z)); } @Test public void testScalarMultiply() { Complex x = new Complex(3.0, 4.0); double yDouble = 2.0; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble)); int zInt = -5; Complex zComplex = new Complex(zInt); Assert.assertEquals(x.multiply(zComplex), x.multiply(zInt)); } @Test public void testScalarMultiplyNaN() { Complex x = new Complex(3.0, 4.0); double yDouble = Double.NaN; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble)); } @Test public void testScalarMultiplyInf() { Complex x = new Complex(1, 1); double yDouble = Double.POSITIVE_INFINITY; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble)); yDouble = Double.NEGATIVE_INFINITY; yComplex = new Complex(yDouble); Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble)); } @Test public void testNegate() { Complex x = new Complex(3.0, 4.0); Complex z = x.negate(); Assert.assertEquals(-3.0, z.getReal(), 1.0e-5); Assert.assertEquals(-4.0, z.getImaginary(), 1.0e-5); } @Test public void testNegateNaN() { Complex z = Complex.NaN.negate(); Assert.assertTrue(z.isNaN()); } @Test public void testSubtract() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.subtract(y); Assert.assertEquals(-2.0, z.getReal(), 1.0e-5); Assert.assertEquals(-2.0, z.getImaginary(), 1.0e-5); } @Test public void testSubtractNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.subtract(Complex.NaN); Assert.assertSame(Complex.NaN, z); z = new Complex(1, nan); Complex w = x.subtract(z); Assert.assertSame(Complex.NaN, w); } @Test public void testSubtractInf() { Complex x = new Complex(1, 1); Complex z = new Complex(neginf, 0); Complex w = x.subtract(z); Assert.assertEquals(w.getImaginary(), 1, 0); Assert.assertEquals(inf, w.getReal(), 0); x = new Complex(neginf, 0); Assert.assertTrue(Double.isNaN(x.subtract(z).getReal())); } @Test public void testScalarSubtract() { Complex x = new Complex(3.0, 4.0); double yDouble = 2.0; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble)); } @Test public void testScalarSubtractNaN() { Complex x = new Complex(3.0, 4.0); double yDouble = Double.NaN; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble)); } @Test public void testScalarSubtractInf() { Complex x = new Complex(1, 1); double yDouble = Double.POSITIVE_INFINITY; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble)); x = new Complex(neginf, 0); Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble)); } @Test public void testEqualsNull() { Complex x = new Complex(3.0, 4.0); Assert.assertFalse(x.equals(null)); } @Test public void testEqualsClass() { Complex x = new Complex(3.0, 4.0); Assert.assertFalse(x.equals(this)); } @Test public void testEqualsSame() { Complex x = new Complex(3.0, 4.0); Assert.assertTrue(x.equals(x)); } @Test public void testEqualsTrue() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(3.0, 4.0); Assert.assertTrue(x.equals(y)); } @Test public void testEqualsRealDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0 + Double.MIN_VALUE, 0.0); Assert.assertFalse(x.equals(y)); } @Test public void testEqualsImaginaryDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); Assert.assertFalse(x.equals(y)); } @Test public void testEqualsNaN() { Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Complex complexNaN = Complex.NaN; Assert.assertTrue(realNaN.equals(imaginaryNaN)); Assert.assertTrue(imaginaryNaN.equals(complexNaN)); Assert.assertTrue(realNaN.equals(complexNaN)); } @Test public void testHashCode() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); Assert.assertFalse(x.hashCode()==y.hashCode()); y = new Complex(0.0 + Double.MIN_VALUE, 0.0); Assert.assertFalse(x.hashCode()==y.hashCode()); Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Assert.assertEquals(realNaN.hashCode(), imaginaryNaN.hashCode()); Assert.assertEquals(imaginaryNaN.hashCode(), Complex.NaN.hashCode()); } @Test public void testAcos() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.936812, -2.30551); TestUtils.assertEquals(expected, z.acos(), 1.0e-5); TestUtils.assertEquals(new Complex(FastMath.acos(0), 0), Complex.ZERO.acos(), 1.0e-12); } @Test public void testAcosInf() { TestUtils.assertSame(Complex.NaN, oneInf.acos()); TestUtils.assertSame(Complex.NaN, oneNegInf.acos()); TestUtils.assertSame(Complex.NaN, infOne.acos()); TestUtils.assertSame(Complex.NaN, negInfOne.acos()); TestUtils.assertSame(Complex.NaN, infInf.acos()); TestUtils.assertSame(Complex.NaN, infNegInf.acos()); TestUtils.assertSame(Complex.NaN, negInfInf.acos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.acos()); } @Test public void testAcosNaN() { Assert.assertTrue(Complex.NaN.acos().isNaN()); } @Test public void testAsin() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.633984, 2.30551); TestUtils.assertEquals(expected, z.asin(), 1.0e-5); } @Test public void testAsinNaN() { Assert.assertTrue(Complex.NaN.asin().isNaN()); } @Test public void testAsinInf() { TestUtils.assertSame(Complex.NaN, oneInf.asin()); TestUtils.assertSame(Complex.NaN, oneNegInf.asin()); TestUtils.assertSame(Complex.NaN, infOne.asin()); TestUtils.assertSame(Complex.NaN, negInfOne.asin()); TestUtils.assertSame(Complex.NaN, infInf.asin()); TestUtils.assertSame(Complex.NaN, infNegInf.asin()); TestUtils.assertSame(Complex.NaN, negInfInf.asin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.asin()); } @Test public void testAtan() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.44831, 0.158997); TestUtils.assertEquals(expected, z.atan(), 1.0e-5); } @Test public void testAtanInf() { TestUtils.assertSame(Complex.NaN, oneInf.atan()); TestUtils.assertSame(Complex.NaN, oneNegInf.atan()); TestUtils.assertSame(Complex.NaN, infOne.atan()); TestUtils.assertSame(Complex.NaN, negInfOne.atan()); TestUtils.assertSame(Complex.NaN, infInf.atan()); TestUtils.assertSame(Complex.NaN, infNegInf.atan()); TestUtils.assertSame(Complex.NaN, negInfInf.atan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.atan()); } @Test public void testAtanI() { Assert.assertTrue(Complex.I.atan().isNaN()); } @Test public void testAtanNaN() { Assert.assertTrue(Complex.NaN.atan().isNaN()); } @Test public void testCos() { Complex z = new Complex(3, 4); Complex expected = new Complex(-27.03495, -3.851153); TestUtils.assertEquals(expected, z.cos(), 1.0e-5); } @Test public void testCosNaN() { Assert.assertTrue(Complex.NaN.cos().isNaN()); } @Test public void testCosInf() { TestUtils.assertSame(infNegInf, oneInf.cos()); TestUtils.assertSame(infInf, oneNegInf.cos()); TestUtils.assertSame(Complex.NaN, infOne.cos()); TestUtils.assertSame(Complex.NaN, negInfOne.cos()); TestUtils.assertSame(Complex.NaN, infInf.cos()); TestUtils.assertSame(Complex.NaN, infNegInf.cos()); TestUtils.assertSame(Complex.NaN, negInfInf.cos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cos()); } @Test public void testCosh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.58066, -7.58155); TestUtils.assertEquals(expected, z.cosh(), 1.0e-5); } @Test public void testCoshNaN() { Assert.assertTrue(Complex.NaN.cosh().isNaN()); } @Test public void testCoshInf() { TestUtils.assertSame(Complex.NaN, oneInf.cosh()); TestUtils.assertSame(Complex.NaN, oneNegInf.cosh()); TestUtils.assertSame(infInf, infOne.cosh()); TestUtils.assertSame(infNegInf, negInfOne.cosh()); TestUtils.assertSame(Complex.NaN, infInf.cosh()); TestUtils.assertSame(Complex.NaN, infNegInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cosh()); } @Test public void testExp() { Complex z = new Complex(3, 4); Complex expected = new Complex(-13.12878, -15.20078); TestUtils.assertEquals(expected, z.exp(), 1.0e-5); TestUtils.assertEquals(Complex.ONE, Complex.ZERO.exp(), 10e-12); Complex iPi = Complex.I.multiply(new Complex(pi,0)); TestUtils.assertEquals(Complex.ONE.negate(), iPi.exp(), 10e-12); } @Test public void testExpNaN() { Assert.assertTrue(Complex.NaN.exp().isNaN()); } @Test public void testExpInf() { TestUtils.assertSame(Complex.NaN, oneInf.exp()); TestUtils.assertSame(Complex.NaN, oneNegInf.exp()); TestUtils.assertSame(infInf, infOne.exp()); TestUtils.assertSame(Complex.ZERO, negInfOne.exp()); TestUtils.assertSame(Complex.NaN, infInf.exp()); TestUtils.assertSame(Complex.NaN, infNegInf.exp()); TestUtils.assertSame(Complex.NaN, negInfInf.exp()); TestUtils.assertSame(Complex.NaN, negInfNegInf.exp()); } @Test public void testLog() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.60944, 0.927295); TestUtils.assertEquals(expected, z.log(), 1.0e-5); } @Test public void testLogNaN() { Assert.assertTrue(Complex.NaN.log().isNaN()); } @Test public void testLogInf() { TestUtils.assertEquals(new Complex(inf, pi / 2), oneInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 2), oneNegInf.log(), 10e-12); TestUtils.assertEquals(infZero, infOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi), negInfOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi / 4), infInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 4), infNegInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, 3d * pi / 4), negInfInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, - 3d * pi / 4), negInfNegInf.log(), 10e-12); } @Test public void testLogZero() { TestUtils.assertSame(negInfZero, Complex.ZERO.log()); } @Test public void testPow() { Complex x = new Complex(3, 4); Complex y = new Complex(5, 6); Complex expected = new Complex(-1.860893, 11.83677); TestUtils.assertEquals(expected, x.pow(y), 1.0e-5); } @Test public void testPowNaNBase() { Complex x = new Complex(3, 4); Assert.assertTrue(Complex.NaN.pow(x).isNaN()); } @Test public void testPowNaNExponent() { Complex x = new Complex(3, 4); Assert.assertTrue(x.pow(Complex.NaN).isNaN()); } @Test public void testPowInf() { TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infOne)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infInf)); } @Test public void testPowZero() { TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ZERO)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.I)); TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, Complex.I.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(Complex.ZERO), 10e-12); } @Test public void testScalarPow() { Complex x = new Complex(3, 4); double yDouble = 5.0; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.pow(yComplex), x.pow(yDouble)); } @Test public void testScalarPowNaNBase() { Complex x = Complex.NaN; double yDouble = 5.0; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.pow(yComplex), x.pow(yDouble)); } @Test public void testScalarPowNaNExponent() { Complex x = new Complex(3, 4); double yDouble = Double.NaN; Complex yComplex = new Complex(yDouble); Assert.assertEquals(x.pow(yComplex), x.pow(yDouble)); } @Test public void testScalarPowInf() { TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(Double.POSITIVE_INFINITY)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(Double.NEGATIVE_INFINITY)); TestUtils.assertSame(Complex.NaN,infOne.pow(1.0)); TestUtils.assertSame(Complex.NaN,negInfOne.pow(1.0)); TestUtils.assertSame(Complex.NaN,infInf.pow(1.0)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(1.0)); TestUtils.assertSame(Complex.NaN,negInfInf.pow(10)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(1.0)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Double.POSITIVE_INFINITY)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Double.POSITIVE_INFINITY)); TestUtils.assertSame(Complex.NaN,infInf.pow(Double.POSITIVE_INFINITY)); TestUtils.assertSame(Complex.NaN,infInf.pow(Double.NEGATIVE_INFINITY)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(Double.NEGATIVE_INFINITY)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(Double.POSITIVE_INFINITY)); } @Test public void testScalarPowZero() { TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(1.0)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(0.0)); TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(0.0), 10e-12); TestUtils.assertEquals(Complex.ONE, Complex.I.pow(0.0), 10e-12); TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(0.0), 10e-12); } @Test(expected=NullArgumentException.class) public void testpowNull() { Complex.ONE.pow(null); } @Test public void testSin() { Complex z = new Complex(3, 4); Complex expected = new Complex(3.853738, -27.01681); TestUtils.assertEquals(expected, z.sin(), 1.0e-5); } @Test public void testSinInf() { TestUtils.assertSame(infInf, oneInf.sin()); TestUtils.assertSame(infNegInf, oneNegInf.sin()); TestUtils.assertSame(Complex.NaN, infOne.sin()); TestUtils.assertSame(Complex.NaN, negInfOne.sin()); TestUtils.assertSame(Complex.NaN, infInf.sin()); TestUtils.assertSame(Complex.NaN, infNegInf.sin()); TestUtils.assertSame(Complex.NaN, negInfInf.sin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sin()); } @Test public void testSinNaN() { Assert.assertTrue(Complex.NaN.sin().isNaN()); } @Test public void testSinh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.54812, -7.61923); TestUtils.assertEquals(expected, z.sinh(), 1.0e-5); } @Test public void testSinhNaN() { Assert.assertTrue(Complex.NaN.sinh().isNaN()); } @Test public void testSinhInf() { TestUtils.assertSame(Complex.NaN, oneInf.sinh()); TestUtils.assertSame(Complex.NaN, oneNegInf.sinh()); TestUtils.assertSame(infInf, infOne.sinh()); TestUtils.assertSame(negInfInf, negInfOne.sinh()); TestUtils.assertSame(Complex.NaN, infInf.sinh()); TestUtils.assertSame(Complex.NaN, infNegInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sinh()); } @Test public void testSqrtRealPositive() { Complex z = new Complex(3, 4); Complex expected = new Complex(2, 1); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtRealZero() { Complex z = new Complex(0.0, 4); Complex expected = new Complex(1.41421, 1.41421); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtRealNegative() { Complex z = new Complex(-3.0, 4); Complex expected = new Complex(1, 2); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtImaginaryZero() { Complex z = new Complex(-3.0, 0.0); Complex expected = new Complex(0.0, 1.73205); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtImaginaryNegative() { Complex z = new Complex(-3.0, -4.0); Complex expected = new Complex(1.0, -2.0); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtPolar() { double r = 1; for (int i = 0; i < 5; i++) { r += i; double theta = 0; for (int j =0; j < 11; j++) { theta += pi /12; Complex z = ComplexUtils.polar2Complex(r, theta); Complex sqrtz = ComplexUtils.polar2Complex(FastMath.sqrt(r), theta / 2); TestUtils.assertEquals(sqrtz, z.sqrt(), 10e-12); } } } @Test public void testSqrtNaN() { Assert.assertTrue(Complex.NaN.sqrt().isNaN()); } @Test public void testSqrtInf() { TestUtils.assertSame(infNaN, oneInf.sqrt()); TestUtils.assertSame(infNaN, oneNegInf.sqrt()); TestUtils.assertSame(infZero, infOne.sqrt()); TestUtils.assertSame(zeroInf, negInfOne.sqrt()); TestUtils.assertSame(infNaN, infInf.sqrt()); TestUtils.assertSame(infNaN, infNegInf.sqrt()); TestUtils.assertSame(nanInf, negInfInf.sqrt()); TestUtils.assertSame(nanNegInf, negInfNegInf.sqrt()); } @Test public void testSqrt1z() { Complex z = new Complex(3, 4); Complex expected = new Complex(4.08033, -2.94094); TestUtils.assertEquals(expected, z.sqrt1z(), 1.0e-5); } @Test public void testSqrt1zNaN() { Assert.assertTrue(Complex.NaN.sqrt1z().isNaN()); } @Test public void testTan() { Complex z = new Complex(3, 4); Complex expected = new Complex(-0.000187346, 0.999356); TestUtils.assertEquals(expected, z.tan(), 1.0e-5); /* Check that no overflow occurs (MATH-722) */ Complex actual = new Complex(3.0, 1E10).tan(); expected = new Complex(0, 1); TestUtils.assertEquals(expected, actual, 1.0e-5); actual = new Complex(3.0, -1E10).tan(); expected = new Complex(0, -1); TestUtils.assertEquals(expected, actual, 1.0e-5); } @Test public void testTanNaN() { Assert.assertTrue(Complex.NaN.tan().isNaN()); } @Test public void testTanInf() { TestUtils.assertSame(Complex.valueOf(0.0, 1.0), oneInf.tan()); TestUtils.assertSame(Complex.valueOf(0.0, -1.0), oneNegInf.tan()); TestUtils.assertSame(Complex.NaN, infOne.tan()); TestUtils.assertSame(Complex.NaN, negInfOne.tan()); TestUtils.assertSame(Complex.NaN, infInf.tan()); TestUtils.assertSame(Complex.NaN, infNegInf.tan()); TestUtils.assertSame(Complex.NaN, negInfInf.tan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tan()); } @Test public void testTanCritical() { TestUtils.assertSame(infNaN, new Complex(pi/2, 0).tan()); TestUtils.assertSame(negInfNaN, new Complex(-pi/2, 0).tan()); } @Test public void testTanh() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.00071, 0.00490826); TestUtils.assertEquals(expected, z.tanh(), 1.0e-5); /* Check that no overflow occurs (MATH-722) */ Complex actual = new Complex(1E10, 3.0).tanh(); expected = new Complex(1, 0); TestUtils.assertEquals(expected, actual, 1.0e-5); actual = new Complex(-1E10, 3.0).tanh(); expected = new Complex(-1, 0); TestUtils.assertEquals(expected, actual, 1.0e-5); } @Test public void testTanhNaN() { Assert.assertTrue(Complex.NaN.tanh().isNaN()); } @Test public void testTanhInf() { TestUtils.assertSame(Complex.NaN, oneInf.tanh()); TestUtils.assertSame(Complex.NaN, oneNegInf.tanh()); TestUtils.assertSame(Complex.valueOf(1.0, 0.0), infOne.tanh()); TestUtils.assertSame(Complex.valueOf(-1.0, 0.0), negInfOne.tanh()); TestUtils.assertSame(Complex.NaN, infInf.tanh()); TestUtils.assertSame(Complex.NaN, infNegInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tanh()); } @Test public void testTanhCritical() { TestUtils.assertSame(nanInf, new Complex(0, pi/2).tanh()); } /** test issue MATH-221 */ @Test public void testMath221() { Assert.assertEquals(new Complex(0,-1), new Complex(0,1).multiply(new Complex(-1,0))); } /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = -2 + 2 * i</b> * => z_0 = 1 + i * => z_1 = -1.3660 + 0.3660 * i * => z_2 = 0.3660 - 1.3660 * i * </code> * </pre> */ @Test public void testNthRoot_normal_thirdRoot() { // The complex number we want to compute all third-roots for. Complex z = new Complex(-2,2); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(1.0, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(1.0, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.3660254037844386, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(0.36602540378443843, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(0.366025403784439, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.3660254037844384, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test: computing <b>fourth roots</b> of z. * <pre> * <code> * <b>z = 5 - 2 * i</b> * => z_0 = 1.5164 - 0.1446 * i * => z_1 = 0.1446 + 1.5164 * i * => z_2 = -1.5164 + 0.1446 * i * => z_3 = -1.5164 - 0.1446 * i * </code> * </pre> */ @Test public void testNthRoot_normal_fourthRoot() { // The complex number we want to compute all third-roots for. Complex z = new Complex(5,-2); // The List holding all fourth roots Complex[] fourthRootsOfZ = z.nthRoot(4).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(4, fourthRootsOfZ.length); // test z_0 Assert.assertEquals(1.5164629308487783, fourthRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(-0.14469266210702247, fourthRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(0.14469266210702256, fourthRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(1.5164629308487783, fourthRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-1.5164629308487783, fourthRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(0.14469266210702267, fourthRootsOfZ[2].getImaginary(), 1.0e-5); // test z_3 Assert.assertEquals(-0.14469266210702275, fourthRootsOfZ[3].getReal(), 1.0e-5); Assert.assertEquals(-1.5164629308487783, fourthRootsOfZ[3].getImaginary(), 1.0e-5); } /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty() { // The number 8 has three third roots. One we all already know is the number 2. // But there are two more complex roots. Complex z = new Complex(8,0); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(2.0, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(0.0, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.0, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(1.7320508075688774, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-1.0, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.732050807568877, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test: computing <b>third roots</b> of z with real part 0. * <pre> * <code> * <b>z = 2 * i</b> * => z_0 = 1.0911 + 0.6299 * i * => z_1 = -1.0911 + 0.6299 * i * => z_2 = -2.3144 - 1.2599 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_realPartZero() { // complex number with only imaginary part Complex z = new Complex(0,2); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(1.0911236359717216, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(0.6299605249474365, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.0911236359717216, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(0.6299605249474365, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-2.3144374213981936E-16, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.2599210498948732, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test cornercases with NaN and Infinity. */ @Test public void testNthRoot_cornercase_NAN_Inf() { // NaN + finite -> NaN List<Complex> roots = oneNaN.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); roots = nanZero.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); // NaN + infinite -> NaN roots = nanInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); // finite + infinite -> Inf roots = oneInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.INF, roots.get(0)); // infinite + infinite -> Inf roots = negInfInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.INF, roots.get(0)); } /** * Test standard values */ @Test public void testGetArgument() { Complex z = new Complex(1, 0); Assert.assertEquals(0.0, z.getArgument(), 1.0e-12); z = new Complex(1, 1); Assert.assertEquals(FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(0, 1); Assert.assertEquals(FastMath.PI/2, z.getArgument(), 1.0e-12); z = new Complex(-1, 1); Assert.assertEquals(3 * FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(-1, 0); Assert.assertEquals(FastMath.PI, z.getArgument(), 1.0e-12); z = new Complex(-1, -1); Assert.assertEquals(-3 * FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(0, -1); Assert.assertEquals(-FastMath.PI/2, z.getArgument(), 1.0e-12); z = new Complex(1, -1); Assert.assertEquals(-FastMath.PI/4, z.getArgument(), 1.0e-12); } /** * Verify atan2-style handling of infinite parts */ @Test public void testGetArgumentInf() { Assert.assertEquals(FastMath.PI/4, infInf.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI/2, oneInf.getArgument(), 1.0e-12); Assert.assertEquals(0.0, infOne.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI/2, zeroInf.getArgument(), 1.0e-12); Assert.assertEquals(0.0, infZero.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI, negInfOne.getArgument(), 1.0e-12); Assert.assertEquals(-3.0*FastMath.PI/4, negInfNegInf.getArgument(), 1.0e-12); Assert.assertEquals(-FastMath.PI/2, oneNegInf.getArgument(), 1.0e-12); } /** * Verify that either part NaN results in NaN */ @Test public void testGetArgumentNaN() { Assert.assertTrue(Double.isNaN(nanZero.getArgument())); Assert.assertTrue(Double.isNaN(zeroNaN.getArgument())); Assert.assertTrue(Double.isNaN(Complex.NaN.getArgument())); } @Test public void testSerial() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(z, TestUtils.serializeAndRecover(z)); Complex ncmplx = (Complex)TestUtils.serializeAndRecover(oneNaN); Assert.assertEquals(nanZero, ncmplx); Assert.assertTrue(ncmplx.isNaN()); Complex infcmplx = (Complex)TestUtils.serializeAndRecover(infInf); Assert.assertEquals(infInf, infcmplx); Assert.assertTrue(infcmplx.isInfinite()); TestComplex tz = new TestComplex(3.0, 4.0); Assert.assertEquals(tz, TestUtils.serializeAndRecover(tz)); TestComplex ntcmplx = (TestComplex)TestUtils.serializeAndRecover(new TestComplex(oneNaN)); Assert.assertEquals(nanZero, ntcmplx); Assert.assertTrue(ntcmplx.isNaN()); TestComplex inftcmplx = (TestComplex)TestUtils.serializeAndRecover(new TestComplex(infInf)); Assert.assertEquals(infInf, inftcmplx); Assert.assertTrue(inftcmplx.isInfinite()); } /** * Class to test extending Complex */ public static class TestComplex extends Complex { /** * Serialization identifier. */ private static final long serialVersionUID = 3268726724160389237L; public TestComplex(double real, double imaginary) { super(real, imaginary); } public TestComplex(Complex other){ this(other.getReal(), other.getImaginary()); } @Override protected TestComplex createComplex(double real, double imaginary){ return new TestComplex(real, imaginary); } } }
[ { "be_test_class_file": "org/apache/commons/math3/complex/Complex.java", "be_test_class_name": "org.apache.commons.math3.complex.Complex", "be_test_function_name": "abs", "be_test_function_signature": "()D", "line_numbers": [ "116", "117", "119", "120", "122", "123", "124", "126", "127", "129", "130", "132", "133" ], "method_line_rate": 0.46153846153846156 }, { "be_test_class_file": "org/apache/commons/math3/complex/Complex.java", "be_test_class_name": "org.apache.commons.math3.complex.Complex", "be_test_function_name": "createComplex", "be_test_function_signature": "(DD)Lorg/apache/commons/math3/complex/Complex;", "line_numbers": [ "1176" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/complex/Complex.java", "be_test_class_name": "org.apache.commons.math3.complex.Complex", "be_test_function_name": "getArgument", "be_test_function_signature": "()D", "line_numbers": [ "1104" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/complex/Complex.java", "be_test_class_name": "org.apache.commons.math3.complex.Complex", "be_test_function_name": "getImaginary", "be_test_function_signature": "()D", "line_numbers": [ "376" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/complex/Complex.java", "be_test_class_name": "org.apache.commons.math3.complex.Complex", "be_test_function_name": "getReal", "be_test_function_signature": "()D", "line_numbers": [ "385" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/complex/Complex.java", "be_test_class_name": "org.apache.commons.math3.complex.Complex", "be_test_function_name": "isInfinite", "be_test_function_signature": "()Z", "line_numbers": [ "409" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/complex/Complex.java", "be_test_class_name": "org.apache.commons.math3.complex.Complex", "be_test_function_name": "nthRoot", "be_test_function_signature": "(I)Ljava/util/List;", "line_numbers": [ "1131", "1132", "1136", "1138", "1139", "1140", "1142", "1143", "1144", "1148", "1151", "1152", "1153", "1154", "1156", "1157", "1158", "1159", "1162" ], "method_line_rate": 0.7368421052631579 } ]
public class ZipArchiveInputStreamTest
@Test public void testMessageWithCorruptFileName() throws Exception { try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-351.zip")))) { ZipArchiveEntry ze = in.getNextZipEntry(); while (ze != null) { ze = in.getNextZipEntry(); } fail("expected EOFException"); } catch (final EOFException ex) { final String m = ex.getMessage(); assertTrue(m.startsWith("Truncated ZIP entry: ?2016")); // the first character is not printable } }
// private static final int LFH_LEN = 30; // private static final int CFH_LEN = 46; // private static final long TWO_EXP_32 = ZIP64_MAGIC + 1; // private final byte[] lfhBuf = new byte[LFH_LEN]; // private final byte[] skipBuf = new byte[1024]; // private final byte[] shortBuf = new byte[SHORT]; // private final byte[] wordBuf = new byte[WORD]; // private final byte[] twoDwordBuf = new byte[2 * DWORD]; // private int entriesRead = 0; // private static final byte[] LFH = ZipLong.LFH_SIG.getBytes(); // private static final byte[] CFH = ZipLong.CFH_SIG.getBytes(); // private static final byte[] DD = ZipLong.DD_SIG.getBytes(); // // public ZipArchiveInputStream(final InputStream inputStream); // public ZipArchiveInputStream(final InputStream inputStream, final String encoding); // public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields); // public ZipArchiveInputStream(final InputStream inputStream, // final String encoding, // final boolean useUnicodeExtraFields, // final boolean allowStoredEntriesWithDataDescriptor); // public ZipArchiveEntry getNextZipEntry() throws IOException; // private void readFirstLocalFileHeader(final byte[] lfh) throws IOException; // private void processZip64Extra(final ZipLong size, final ZipLong cSize); // @Override // public ArchiveEntry getNextEntry() throws IOException; // @Override // public boolean canReadEntryData(final ArchiveEntry ae); // @Override // public int read(final byte[] buffer, final int offset, final int length) throws IOException; // private int readStored(final byte[] buffer, final int offset, final int length) throws IOException; // private int readDeflated(final byte[] buffer, final int offset, final int length) throws IOException; // private int readFromInflater(final byte[] buffer, final int offset, final int length) throws IOException; // @Override // public void close() throws IOException; // @Override // public long skip(final long value) throws IOException; // public static boolean matches(final byte[] signature, final int length); // private static boolean checksig(final byte[] signature, final byte[] expected); // private void closeEntry() throws IOException; // private boolean currentEntryHasOutstandingBytes(); // private void drainCurrentEntryData() throws IOException; // private long getBytesInflated(); // private int fill() throws IOException; // private void readFully(final byte[] b) throws IOException; // private void readDataDescriptor() throws IOException; // private boolean supportsDataDescriptorFor(final ZipArchiveEntry entry); // private boolean supportsCompressedSizeFor(final ZipArchiveEntry entry); // private void readStoredEntry() throws IOException; // private boolean bufferContainsSignature(final ByteArrayOutputStream bos, final int offset, final int lastRead, final int expectedDDLen) // throws IOException; // private int cacheBytesRead(final ByteArrayOutputStream bos, int offset, final int lastRead, final int expecteDDLen); // private void pushback(final byte[] buf, final int offset, final int length) throws IOException; // private void skipRemainderOfArchive() throws IOException; // private void findEocdRecord() throws IOException; // private void realSkip(final long value) throws IOException; // private int readOneByte() throws IOException; // private boolean isFirstByteOfEocdSig(final int b); // public BoundedInputStream(final InputStream in, final long size); // @Override // public int read() throws IOException; // @Override // public int read(final byte[] b) throws IOException; // @Override // public int read(final byte[] b, final int off, final int len) throws IOException; // @Override // public long skip(final long n) throws IOException; // @Override // public int available() throws IOException; // } // // // Abstract Java Test Class // package org.apache.commons.compress.archivers.zip; // // import static org.apache.commons.compress.AbstractTestCase.getFile; // import static org.junit.Assert.assertArrayEquals; // 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.BufferedInputStream; // import java.io.ByteArrayInputStream; // import java.io.EOFException; // import java.io.File; // import java.io.FileInputStream; // import java.io.IOException; // import java.io.InputStream; // import java.util.Arrays; // import java.util.zip.ZipException; // import org.apache.commons.compress.archivers.ArchiveEntry; // import org.apache.commons.compress.utils.IOUtils; // import org.junit.Assert; // import org.junit.Test; // // // // public class ZipArchiveInputStreamTest { // // // @Test // public void winzipBackSlashWorkaround() throws Exception; // @Test // public void properUseOfInflater() throws Exception; // @Test // public void shouldConsumeArchiveCompletely() throws Exception; // @Test // public void shouldReadNestedZip() throws IOException; // private void extractZipInputStream(final ZipArchiveInputStream in) // throws IOException; // @Test // public void testUnshrinkEntry() throws Exception; // @Test // public void testReadingOfFirstStoredEntry() throws Exception; // @Test // public void testMessageWithCorruptFileName() throws Exception; // @Test // public void testUnzipBZip2CompressedEntry() throws Exception; // @Test // public void readDeflate64CompressedStream() throws Exception; // @Test // public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception; // @Test // public void testWithBytesAfterData() throws Exception; // @Test // public void testThrowOnInvalidEntry() throws Exception; // @Test // public void testOffsets() throws Exception; // @Test // public void nameSourceDefaultsToName() throws Exception; // @Test // public void nameSourceIsSetToUnicodeExtraField() throws Exception; // @Test // public void nameSourceIsSetToEFS() throws Exception; // @Test // public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception; // private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException; // private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; // private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected) // throws Exception; // } // You are a professional Java test case writer, please create a test case named `testMessageWithCorruptFileName` for the `ZipArchiveInputStream` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-351" * >COMPRESS-351</a>. */
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
package org.apache.commons.compress.archivers.zip; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.nio.ByteBuffer; import java.util.zip.CRC32; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.deflate64.Deflate64CompressorInputStream; import org.apache.commons.compress.utils.ArchiveUtils; import org.apache.commons.compress.utils.IOUtils; import static org.apache.commons.compress.archivers.zip.ZipConstants.DWORD; import static org.apache.commons.compress.archivers.zip.ZipConstants.SHORT; import static org.apache.commons.compress.archivers.zip.ZipConstants.WORD; import static org.apache.commons.compress.archivers.zip.ZipConstants.ZIP64_MAGIC;
public ZipArchiveInputStream(final InputStream inputStream); public ZipArchiveInputStream(final InputStream inputStream, final String encoding); public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields); public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields, final boolean allowStoredEntriesWithDataDescriptor); public ZipArchiveEntry getNextZipEntry() throws IOException; private void readFirstLocalFileHeader(final byte[] lfh) throws IOException; private void processZip64Extra(final ZipLong size, final ZipLong cSize); @Override public ArchiveEntry getNextEntry() throws IOException; @Override public boolean canReadEntryData(final ArchiveEntry ae); @Override public int read(final byte[] buffer, final int offset, final int length) throws IOException; private int readStored(final byte[] buffer, final int offset, final int length) throws IOException; private int readDeflated(final byte[] buffer, final int offset, final int length) throws IOException; private int readFromInflater(final byte[] buffer, final int offset, final int length) throws IOException; @Override public void close() throws IOException; @Override public long skip(final long value) throws IOException; public static boolean matches(final byte[] signature, final int length); private static boolean checksig(final byte[] signature, final byte[] expected); private void closeEntry() throws IOException; private boolean currentEntryHasOutstandingBytes(); private void drainCurrentEntryData() throws IOException; private long getBytesInflated(); private int fill() throws IOException; private void readFully(final byte[] b) throws IOException; private void readDataDescriptor() throws IOException; private boolean supportsDataDescriptorFor(final ZipArchiveEntry entry); private boolean supportsCompressedSizeFor(final ZipArchiveEntry entry); private void readStoredEntry() throws IOException; private boolean bufferContainsSignature(final ByteArrayOutputStream bos, final int offset, final int lastRead, final int expectedDDLen) throws IOException; private int cacheBytesRead(final ByteArrayOutputStream bos, int offset, final int lastRead, final int expecteDDLen); private void pushback(final byte[] buf, final int offset, final int length) throws IOException; private void skipRemainderOfArchive() throws IOException; private void findEocdRecord() throws IOException; private void realSkip(final long value) throws IOException; private int readOneByte() throws IOException; private boolean isFirstByteOfEocdSig(final int b); public BoundedInputStream(final InputStream in, final long size); @Override public int read() throws IOException; @Override public int read(final byte[] b) throws IOException; @Override public int read(final byte[] b, final int off, final int len) throws IOException; @Override public long skip(final long n) throws IOException; @Override public int available() throws IOException;
195
testMessageWithCorruptFileName
```java private static final int LFH_LEN = 30; private static final int CFH_LEN = 46; private static final long TWO_EXP_32 = ZIP64_MAGIC + 1; private final byte[] lfhBuf = new byte[LFH_LEN]; private final byte[] skipBuf = new byte[1024]; private final byte[] shortBuf = new byte[SHORT]; private final byte[] wordBuf = new byte[WORD]; private final byte[] twoDwordBuf = new byte[2 * DWORD]; private int entriesRead = 0; private static final byte[] LFH = ZipLong.LFH_SIG.getBytes(); private static final byte[] CFH = ZipLong.CFH_SIG.getBytes(); private static final byte[] DD = ZipLong.DD_SIG.getBytes(); public ZipArchiveInputStream(final InputStream inputStream); public ZipArchiveInputStream(final InputStream inputStream, final String encoding); public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields); public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields, final boolean allowStoredEntriesWithDataDescriptor); public ZipArchiveEntry getNextZipEntry() throws IOException; private void readFirstLocalFileHeader(final byte[] lfh) throws IOException; private void processZip64Extra(final ZipLong size, final ZipLong cSize); @Override public ArchiveEntry getNextEntry() throws IOException; @Override public boolean canReadEntryData(final ArchiveEntry ae); @Override public int read(final byte[] buffer, final int offset, final int length) throws IOException; private int readStored(final byte[] buffer, final int offset, final int length) throws IOException; private int readDeflated(final byte[] buffer, final int offset, final int length) throws IOException; private int readFromInflater(final byte[] buffer, final int offset, final int length) throws IOException; @Override public void close() throws IOException; @Override public long skip(final long value) throws IOException; public static boolean matches(final byte[] signature, final int length); private static boolean checksig(final byte[] signature, final byte[] expected); private void closeEntry() throws IOException; private boolean currentEntryHasOutstandingBytes(); private void drainCurrentEntryData() throws IOException; private long getBytesInflated(); private int fill() throws IOException; private void readFully(final byte[] b) throws IOException; private void readDataDescriptor() throws IOException; private boolean supportsDataDescriptorFor(final ZipArchiveEntry entry); private boolean supportsCompressedSizeFor(final ZipArchiveEntry entry); private void readStoredEntry() throws IOException; private boolean bufferContainsSignature(final ByteArrayOutputStream bos, final int offset, final int lastRead, final int expectedDDLen) throws IOException; private int cacheBytesRead(final ByteArrayOutputStream bos, int offset, final int lastRead, final int expecteDDLen); private void pushback(final byte[] buf, final int offset, final int length) throws IOException; private void skipRemainderOfArchive() throws IOException; private void findEocdRecord() throws IOException; private void realSkip(final long value) throws IOException; private int readOneByte() throws IOException; private boolean isFirstByteOfEocdSig(final int b); public BoundedInputStream(final InputStream in, final long size); @Override public int read() throws IOException; @Override public int read(final byte[] b) throws IOException; @Override public int read(final byte[] b, final int off, final int len) throws IOException; @Override public long skip(final long n) throws IOException; @Override public int available() throws IOException; } // Abstract Java Test Class package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.assertArrayEquals; 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.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.utils.IOUtils; import org.junit.Assert; import org.junit.Test; public class ZipArchiveInputStreamTest { @Test public void winzipBackSlashWorkaround() throws Exception; @Test public void properUseOfInflater() throws Exception; @Test public void shouldConsumeArchiveCompletely() throws Exception; @Test public void shouldReadNestedZip() throws IOException; private void extractZipInputStream(final ZipArchiveInputStream in) throws IOException; @Test public void testUnshrinkEntry() throws Exception; @Test public void testReadingOfFirstStoredEntry() throws Exception; @Test public void testMessageWithCorruptFileName() throws Exception; @Test public void testUnzipBZip2CompressedEntry() throws Exception; @Test public void readDeflate64CompressedStream() throws Exception; @Test public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception; @Test public void testWithBytesAfterData() throws Exception; @Test public void testThrowOnInvalidEntry() throws Exception; @Test public void testOffsets() throws Exception; @Test public void nameSourceDefaultsToName() throws Exception; @Test public void nameSourceIsSetToUnicodeExtraField() throws Exception; @Test public void nameSourceIsSetToEFS() throws Exception; @Test public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception; private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException; private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected) throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testMessageWithCorruptFileName` for the `ZipArchiveInputStream` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-351" * >COMPRESS-351</a>. */
183
// private static final int LFH_LEN = 30; // private static final int CFH_LEN = 46; // private static final long TWO_EXP_32 = ZIP64_MAGIC + 1; // private final byte[] lfhBuf = new byte[LFH_LEN]; // private final byte[] skipBuf = new byte[1024]; // private final byte[] shortBuf = new byte[SHORT]; // private final byte[] wordBuf = new byte[WORD]; // private final byte[] twoDwordBuf = new byte[2 * DWORD]; // private int entriesRead = 0; // private static final byte[] LFH = ZipLong.LFH_SIG.getBytes(); // private static final byte[] CFH = ZipLong.CFH_SIG.getBytes(); // private static final byte[] DD = ZipLong.DD_SIG.getBytes(); // // public ZipArchiveInputStream(final InputStream inputStream); // public ZipArchiveInputStream(final InputStream inputStream, final String encoding); // public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields); // public ZipArchiveInputStream(final InputStream inputStream, // final String encoding, // final boolean useUnicodeExtraFields, // final boolean allowStoredEntriesWithDataDescriptor); // public ZipArchiveEntry getNextZipEntry() throws IOException; // private void readFirstLocalFileHeader(final byte[] lfh) throws IOException; // private void processZip64Extra(final ZipLong size, final ZipLong cSize); // @Override // public ArchiveEntry getNextEntry() throws IOException; // @Override // public boolean canReadEntryData(final ArchiveEntry ae); // @Override // public int read(final byte[] buffer, final int offset, final int length) throws IOException; // private int readStored(final byte[] buffer, final int offset, final int length) throws IOException; // private int readDeflated(final byte[] buffer, final int offset, final int length) throws IOException; // private int readFromInflater(final byte[] buffer, final int offset, final int length) throws IOException; // @Override // public void close() throws IOException; // @Override // public long skip(final long value) throws IOException; // public static boolean matches(final byte[] signature, final int length); // private static boolean checksig(final byte[] signature, final byte[] expected); // private void closeEntry() throws IOException; // private boolean currentEntryHasOutstandingBytes(); // private void drainCurrentEntryData() throws IOException; // private long getBytesInflated(); // private int fill() throws IOException; // private void readFully(final byte[] b) throws IOException; // private void readDataDescriptor() throws IOException; // private boolean supportsDataDescriptorFor(final ZipArchiveEntry entry); // private boolean supportsCompressedSizeFor(final ZipArchiveEntry entry); // private void readStoredEntry() throws IOException; // private boolean bufferContainsSignature(final ByteArrayOutputStream bos, final int offset, final int lastRead, final int expectedDDLen) // throws IOException; // private int cacheBytesRead(final ByteArrayOutputStream bos, int offset, final int lastRead, final int expecteDDLen); // private void pushback(final byte[] buf, final int offset, final int length) throws IOException; // private void skipRemainderOfArchive() throws IOException; // private void findEocdRecord() throws IOException; // private void realSkip(final long value) throws IOException; // private int readOneByte() throws IOException; // private boolean isFirstByteOfEocdSig(final int b); // public BoundedInputStream(final InputStream in, final long size); // @Override // public int read() throws IOException; // @Override // public int read(final byte[] b) throws IOException; // @Override // public int read(final byte[] b, final int off, final int len) throws IOException; // @Override // public long skip(final long n) throws IOException; // @Override // public int available() throws IOException; // } // // // Abstract Java Test Class // package org.apache.commons.compress.archivers.zip; // // import static org.apache.commons.compress.AbstractTestCase.getFile; // import static org.junit.Assert.assertArrayEquals; // 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.BufferedInputStream; // import java.io.ByteArrayInputStream; // import java.io.EOFException; // import java.io.File; // import java.io.FileInputStream; // import java.io.IOException; // import java.io.InputStream; // import java.util.Arrays; // import java.util.zip.ZipException; // import org.apache.commons.compress.archivers.ArchiveEntry; // import org.apache.commons.compress.utils.IOUtils; // import org.junit.Assert; // import org.junit.Test; // // // // public class ZipArchiveInputStreamTest { // // // @Test // public void winzipBackSlashWorkaround() throws Exception; // @Test // public void properUseOfInflater() throws Exception; // @Test // public void shouldConsumeArchiveCompletely() throws Exception; // @Test // public void shouldReadNestedZip() throws IOException; // private void extractZipInputStream(final ZipArchiveInputStream in) // throws IOException; // @Test // public void testUnshrinkEntry() throws Exception; // @Test // public void testReadingOfFirstStoredEntry() throws Exception; // @Test // public void testMessageWithCorruptFileName() throws Exception; // @Test // public void testUnzipBZip2CompressedEntry() throws Exception; // @Test // public void readDeflate64CompressedStream() throws Exception; // @Test // public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception; // @Test // public void testWithBytesAfterData() throws Exception; // @Test // public void testThrowOnInvalidEntry() throws Exception; // @Test // public void testOffsets() throws Exception; // @Test // public void nameSourceDefaultsToName() throws Exception; // @Test // public void nameSourceIsSetToUnicodeExtraField() throws Exception; // @Test // public void nameSourceIsSetToEFS() throws Exception; // @Test // public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception; // private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException; // private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; // private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected) // throws Exception; // } // You are a professional Java test case writer, please create a test case named `testMessageWithCorruptFileName` for the `ZipArchiveInputStream` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-351" * >COMPRESS-351</a>. */ @Test public void testMessageWithCorruptFileName() throws Exception {
/** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-351" * >COMPRESS-351</a>. */
47
org.apache.commons.compress.archivers.zip.ZipArchiveInputStream
src/test/java
```java private static final int LFH_LEN = 30; private static final int CFH_LEN = 46; private static final long TWO_EXP_32 = ZIP64_MAGIC + 1; private final byte[] lfhBuf = new byte[LFH_LEN]; private final byte[] skipBuf = new byte[1024]; private final byte[] shortBuf = new byte[SHORT]; private final byte[] wordBuf = new byte[WORD]; private final byte[] twoDwordBuf = new byte[2 * DWORD]; private int entriesRead = 0; private static final byte[] LFH = ZipLong.LFH_SIG.getBytes(); private static final byte[] CFH = ZipLong.CFH_SIG.getBytes(); private static final byte[] DD = ZipLong.DD_SIG.getBytes(); public ZipArchiveInputStream(final InputStream inputStream); public ZipArchiveInputStream(final InputStream inputStream, final String encoding); public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields); public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields, final boolean allowStoredEntriesWithDataDescriptor); public ZipArchiveEntry getNextZipEntry() throws IOException; private void readFirstLocalFileHeader(final byte[] lfh) throws IOException; private void processZip64Extra(final ZipLong size, final ZipLong cSize); @Override public ArchiveEntry getNextEntry() throws IOException; @Override public boolean canReadEntryData(final ArchiveEntry ae); @Override public int read(final byte[] buffer, final int offset, final int length) throws IOException; private int readStored(final byte[] buffer, final int offset, final int length) throws IOException; private int readDeflated(final byte[] buffer, final int offset, final int length) throws IOException; private int readFromInflater(final byte[] buffer, final int offset, final int length) throws IOException; @Override public void close() throws IOException; @Override public long skip(final long value) throws IOException; public static boolean matches(final byte[] signature, final int length); private static boolean checksig(final byte[] signature, final byte[] expected); private void closeEntry() throws IOException; private boolean currentEntryHasOutstandingBytes(); private void drainCurrentEntryData() throws IOException; private long getBytesInflated(); private int fill() throws IOException; private void readFully(final byte[] b) throws IOException; private void readDataDescriptor() throws IOException; private boolean supportsDataDescriptorFor(final ZipArchiveEntry entry); private boolean supportsCompressedSizeFor(final ZipArchiveEntry entry); private void readStoredEntry() throws IOException; private boolean bufferContainsSignature(final ByteArrayOutputStream bos, final int offset, final int lastRead, final int expectedDDLen) throws IOException; private int cacheBytesRead(final ByteArrayOutputStream bos, int offset, final int lastRead, final int expecteDDLen); private void pushback(final byte[] buf, final int offset, final int length) throws IOException; private void skipRemainderOfArchive() throws IOException; private void findEocdRecord() throws IOException; private void realSkip(final long value) throws IOException; private int readOneByte() throws IOException; private boolean isFirstByteOfEocdSig(final int b); public BoundedInputStream(final InputStream in, final long size); @Override public int read() throws IOException; @Override public int read(final byte[] b) throws IOException; @Override public int read(final byte[] b, final int off, final int len) throws IOException; @Override public long skip(final long n) throws IOException; @Override public int available() throws IOException; } // Abstract Java Test Class package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.assertArrayEquals; 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.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.utils.IOUtils; import org.junit.Assert; import org.junit.Test; public class ZipArchiveInputStreamTest { @Test public void winzipBackSlashWorkaround() throws Exception; @Test public void properUseOfInflater() throws Exception; @Test public void shouldConsumeArchiveCompletely() throws Exception; @Test public void shouldReadNestedZip() throws IOException; private void extractZipInputStream(final ZipArchiveInputStream in) throws IOException; @Test public void testUnshrinkEntry() throws Exception; @Test public void testReadingOfFirstStoredEntry() throws Exception; @Test public void testMessageWithCorruptFileName() throws Exception; @Test public void testUnzipBZip2CompressedEntry() throws Exception; @Test public void readDeflate64CompressedStream() throws Exception; @Test public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception; @Test public void testWithBytesAfterData() throws Exception; @Test public void testThrowOnInvalidEntry() throws Exception; @Test public void testOffsets() throws Exception; @Test public void nameSourceDefaultsToName() throws Exception; @Test public void nameSourceIsSetToUnicodeExtraField() throws Exception; @Test public void nameSourceIsSetToEFS() throws Exception; @Test public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception; private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException; private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected) throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testMessageWithCorruptFileName` for the `ZipArchiveInputStream` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-351" * >COMPRESS-351</a>. */ @Test public void testMessageWithCorruptFileName() throws Exception { ```
public class ZipArchiveInputStream extends ArchiveInputStream
package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.assertArrayEquals; 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.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.utils.IOUtils; import org.junit.Assert; import org.junit.Test;
@Test public void winzipBackSlashWorkaround() throws Exception; @Test public void properUseOfInflater() throws Exception; @Test public void shouldConsumeArchiveCompletely() throws Exception; @Test public void shouldReadNestedZip() throws IOException; private void extractZipInputStream(final ZipArchiveInputStream in) throws IOException; @Test public void testUnshrinkEntry() throws Exception; @Test public void testReadingOfFirstStoredEntry() throws Exception; @Test public void testMessageWithCorruptFileName() throws Exception; @Test public void testUnzipBZip2CompressedEntry() throws Exception; @Test public void readDeflate64CompressedStream() throws Exception; @Test public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception; @Test public void testWithBytesAfterData() throws Exception; @Test public void testThrowOnInvalidEntry() throws Exception; @Test public void testOffsets() throws Exception; @Test public void nameSourceDefaultsToName() throws Exception; @Test public void nameSourceIsSetToUnicodeExtraField() throws Exception; @Test public void nameSourceIsSetToEFS() throws Exception; @Test public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception; private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException; private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected) throws Exception;
f84d4c5a8cbd6036074836fbb442033d2ebb57b3ab6fe8ce54ac17c9e1793095
[ "org.apache.commons.compress.archivers.zip.ZipArchiveInputStreamTest::testMessageWithCorruptFileName" ]
private final ZipEncoding zipEncoding; final String encoding; private final boolean useUnicodeExtraFields; private final InputStream in; private final Inflater inf = new Inflater(true); private final ByteBuffer buf = ByteBuffer.allocate(ZipArchiveOutputStream.BUFFER_SIZE); private CurrentEntry current = null; private boolean closed = false; private boolean hitCentralDirectory = false; private ByteArrayInputStream lastStoredEntry = null; private boolean allowStoredEntriesWithDataDescriptor = false; private static final int LFH_LEN = 30; private static final int CFH_LEN = 46; private static final long TWO_EXP_32 = ZIP64_MAGIC + 1; private final byte[] lfhBuf = new byte[LFH_LEN]; private final byte[] skipBuf = new byte[1024]; private final byte[] shortBuf = new byte[SHORT]; private final byte[] wordBuf = new byte[WORD]; private final byte[] twoDwordBuf = new byte[2 * DWORD]; private int entriesRead = 0; private static final byte[] LFH = ZipLong.LFH_SIG.getBytes(); private static final byte[] CFH = ZipLong.CFH_SIG.getBytes(); private static final byte[] DD = ZipLong.DD_SIG.getBytes();
@Test public void testMessageWithCorruptFileName() throws Exception
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.assertArrayEquals; 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.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.utils.IOUtils; import org.junit.Assert; import org.junit.Test; public class ZipArchiveInputStreamTest { /** * @see "https://issues.apache.org/jira/browse/COMPRESS-176" */ @Test public void winzipBackSlashWorkaround() throws Exception { ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(getFile("test-winzip.zip"))); ZipArchiveEntry zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); assertEquals("\u00e4/", zae.getName()); } finally { if (in != null) { in.close(); } } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-189" */ @Test public void properUseOfInflater() throws Exception { ZipFile zf = null; ZipArchiveInputStream in = null; try { zf = new ZipFile(getFile("COMPRESS-189.zip")); final ZipArchiveEntry zae = zf.getEntry("USD0558682-20080101.ZIP"); in = new ZipArchiveInputStream(new BufferedInputStream(zf.getInputStream(zae))); ZipArchiveEntry innerEntry; while ((innerEntry = in.getNextZipEntry()) != null) { if (innerEntry.getName().endsWith("XML")) { assertTrue(0 < in.read()); } } } finally { if (zf != null) { zf.close(); } if (in != null) { in.close(); } } } @Test public void shouldConsumeArchiveCompletely() throws Exception { final InputStream is = ZipArchiveInputStreamTest.class .getResourceAsStream("/archive_with_trailer.zip"); final ZipArchiveInputStream zip = new ZipArchiveInputStream(is); while (zip.getNextZipEntry() != null) { // just consume the archive } final byte[] expected = new byte[] { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n' }; final byte[] actual = new byte[expected.length]; is.read(actual); assertArrayEquals(expected, actual); zip.close(); } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-219" */ @Test public void shouldReadNestedZip() throws IOException { ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-219.zip"))); extractZipInputStream(in); } finally { if (in != null) { in.close(); } } } private void extractZipInputStream(final ZipArchiveInputStream in) throws IOException { ZipArchiveEntry zae = in.getNextZipEntry(); while (zae != null) { if (zae.getName().endsWith(".zip")) { extractZipInputStream(new ZipArchiveInputStream(in)); } zae = in.getNextZipEntry(); } } @Test public void testUnshrinkEntry() throws Exception { final ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("SHRUNK.ZIP"))); ZipArchiveEntry entry = in.getNextZipEntry(); assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod()); assertTrue(in.canReadEntryData(entry)); FileInputStream original = new FileInputStream(getFile("test1.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in)); } finally { original.close(); } entry = in.getNextZipEntry(); assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod()); assertTrue(in.canReadEntryData(entry)); original = new FileInputStream(getFile("test2.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in)); } finally { original.close(); } } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-264" * >COMPRESS-264</a>. */ @Test public void testReadingOfFirstStoredEntry() throws Exception { try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-264.zip")))) { final ZipArchiveEntry ze = in.getNextZipEntry(); assertEquals(5, ze.getSize()); assertArrayEquals(new byte[] { 'd', 'a', 't', 'a', '\n' }, IOUtils.toByteArray(in)); } } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-351" * >COMPRESS-351</a>. */ @Test public void testMessageWithCorruptFileName() throws Exception { try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-351.zip")))) { ZipArchiveEntry ze = in.getNextZipEntry(); while (ze != null) { ze = in.getNextZipEntry(); } fail("expected EOFException"); } catch (final EOFException ex) { final String m = ex.getMessage(); assertTrue(m.startsWith("Truncated ZIP entry: ?2016")); // the first character is not printable } } @Test public void testUnzipBZip2CompressedEntry() throws Exception { try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("bzip2-zip.zip")))) { final ZipArchiveEntry ze = in.getNextZipEntry(); assertEquals(42, ze.getSize()); final byte[] expected = new byte[42]; Arrays.fill(expected, (byte) 'a'); assertArrayEquals(expected, IOUtils.toByteArray(in)); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-380" */ @Test public void readDeflate64CompressedStream() throws Exception { final File input = getFile("COMPRESS-380/COMPRESS-380-input"); final File archive = getFile("COMPRESS-380/COMPRESS-380.zip"); try (FileInputStream in = new FileInputStream(input); ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(archive))) { byte[] orig = IOUtils.toByteArray(in); ZipArchiveEntry e = zin.getNextZipEntry(); byte[] fromZip = IOUtils.toByteArray(zin); assertArrayEquals(orig, fromZip); } } @Test public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception { // this is a copy of bla.jar with META-INF/MANIFEST.MF's method manually changed to ENHANCED_DEFLATED final File archive = getFile("COMPRESS-380/COMPRESS-380-dd.zip"); try (ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(archive))) { ZipArchiveEntry e = zin.getNextZipEntry(); assertEquals(-1, e.getSize()); assertEquals(ZipMethod.ENHANCED_DEFLATED.getCode(), e.getMethod()); byte[] fromZip = IOUtils.toByteArray(zin); byte[] expected = new byte[] { 'M', 'a', 'n', 'i', 'f', 'e', 's', 't', '-', 'V', 'e', 'r', 's', 'i', 'o', 'n', ':', ' ', '1', '.', '0', '\r', '\n', '\r', '\n' }; assertArrayEquals(expected, fromZip); zin.getNextZipEntry(); assertEquals(25, e.getSize()); } } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-364" * >COMPRESS-364</a>. */ @Test public void testWithBytesAfterData() throws Exception { final int expectedNumEntries = 2; final InputStream is = ZipArchiveInputStreamTest.class .getResourceAsStream("/archive_with_bytes_after_data.zip"); final ZipArchiveInputStream zip = new ZipArchiveInputStream(is); try { int actualNumEntries = 0; ZipArchiveEntry zae = zip.getNextZipEntry(); while (zae != null) { actualNumEntries++; readEntry(zip, zae); zae = zip.getNextZipEntry(); } assertEquals(expectedNumEntries, actualNumEntries); } finally { zip.close(); } } /** * <code>getNextZipEntry()</code> should throw a <code>ZipException</code> rather than return * <code>null</code> when an unexpected structure is encountered. */ @Test public void testThrowOnInvalidEntry() throws Exception { final InputStream is = ZipArchiveInputStreamTest.class .getResourceAsStream("/invalid-zip.zip"); final ZipArchiveInputStream zip = new ZipArchiveInputStream(is); try { zip.getNextZipEntry(); fail("IOException expected"); } catch (ZipException expected) { assertTrue(expected.getMessage().contains("Unexpected record signature")); } finally { zip.close(); } } /** * Test correct population of header and data offsets. */ @Test public void testOffsets() throws Exception { // mixed.zip contains both inflated and stored files try (InputStream archiveStream = ZipArchiveInputStream.class.getResourceAsStream("/mixed.zip"); ZipArchiveInputStream zipStream = new ZipArchiveInputStream((archiveStream)) ) { ZipArchiveEntry inflatedEntry = zipStream.getNextZipEntry(); Assert.assertEquals("inflated.txt", inflatedEntry.getName()); Assert.assertEquals(0x0000, inflatedEntry.getLocalHeaderOffset()); Assert.assertEquals(0x0046, inflatedEntry.getDataOffset()); ZipArchiveEntry storedEntry = zipStream.getNextZipEntry(); Assert.assertEquals("stored.txt", storedEntry.getName()); Assert.assertEquals(0x5892, storedEntry.getLocalHeaderOffset()); Assert.assertEquals(0x58d6, storedEntry.getDataOffset()); Assert.assertNull(zipStream.getNextZipEntry()); } } @Test public void nameSourceDefaultsToName() throws Exception { nameSource("bla.zip", "test1.xml", ZipArchiveEntry.NameSource.NAME); } @Test public void nameSourceIsSetToUnicodeExtraField() throws Exception { nameSource("utf8-winzip-test.zip", "\u20AC_for_Dollar.txt", ZipArchiveEntry.NameSource.UNICODE_EXTRA_FIELD); } @Test public void nameSourceIsSetToEFS() throws Exception { nameSource("utf8-7zip-test.zip", "\u20AC_for_Dollar.txt", 3, ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG); } @Test public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception { // we never read any data try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new ByteArrayInputStream(new byte[0]))) { ZipArchiveEntry e = new ZipArchiveEntry("test"); e.setMethod(ZipMethod.DEFLATED.getCode()); assertTrue(zis.canReadEntryData(e)); e.setMethod(ZipMethod.ENHANCED_DEFLATED.getCode()); assertTrue(zis.canReadEntryData(e)); e.setMethod(ZipMethod.BZIP2.getCode()); assertFalse(zis.canReadEntryData(e)); } } private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException { final int len = (int)zae.getSize(); final byte[] buff = new byte[len]; zip.read(buff, 0, len); return buff; } private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception { nameSource(archive, entry, 1, expected); } private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected) throws Exception { try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(getFile(archive)))) { ZipArchiveEntry ze; do { ze = zis.getNextZipEntry(); } while (--entryNo > 0); assertEquals(entry, ze.getName()); assertEquals(expected, ze.getNameSource()); } } }
[ { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "close", "be_test_function_signature": "()V", "line_numbers": [ "554", "555", "557", "559", "560", "562" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "closeEntry", "be_test_function_signature": "()V", "line_numbers": [ "644", "645", "647", "648", "652", "653", "656", "658", "663", "666", "667", "668", "672", "673", "677", "678", "681", "682", "683", "684", "685" ], "method_line_rate": 0.19047619047619047 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "currentEntryHasOutstandingBytes", "be_test_function_signature": "()Z", "line_numbers": [ "695" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "drainCurrentEntryData", "be_test_function_signature": "()V", "line_numbers": [ "704", "705", "706", "707", "708", "711", "712", "713", "714" ], "method_line_rate": 0.8888888888888888 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "getNextZipEntry", "be_test_function_signature": "()Lorg/apache/commons/compress/archivers/zip/ZipArchiveEntry;", "line_numbers": [ "221", "222", "223", "225", "226", "227", "230", "232", "237", "239", "241", "242", "243", "245", "246", "247", "248", "249", "251", "252", "255", "256", "258", "259", "260", "262", "263", "264", "265", "266", "268", "270", "271", "273", "274", "275", "277", "278", "279", "280", "282", "283", "285", "286", "288", "291", "293", "295", "296", "298", "299", "300", "301", "302", "305", "306", "307", "309", "310", "313", "315", "316", "317", "319", "320", "321", "322", "323", "325", "326", "328", "332", "334", "335", "337", "338", "345", "346", "347", "350", "351" ], "method_line_rate": 0.7037037037037037 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "processZip64Extra", "be_test_function_signature": "(Lorg/apache/commons/compress/archivers/zip/ZipLong;Lorg/apache/commons/compress/archivers/zip/ZipLong;)V", "line_numbers": [ "382", "385", "386", "387", "389", "390", "392", "393", "396" ], "method_line_rate": 0.7777777777777778 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "readFirstLocalFileHeader", "be_test_function_signature": "([B)V", "line_numbers": [ "360", "361", "362", "363", "366", "369", "370", "371", "372", "374" ], "method_line_rate": 0.5 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream", "be_test_function_name": "readFully", "be_test_function_signature": "([B)V", "line_numbers": [ "755", "756", "757", "758", "760" ], "method_line_rate": 0.8 } ]
public class TestDateTimeComparator extends TestCase
public void testSecond() { aDateTime = getADate( "1969-12-31T23:59:58" ); bDateTime = getADate( "1969-12-31T23:50:59" ); assertEquals( "SecondM1a", -1, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "SecondP1a", 1, cSecond.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1970-01-01T00:00:00" ); bDateTime = getADate( "1970-01-01T00:00:01" ); assertEquals( "SecondM1b", -1, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "SecondP1b", 1, cSecond.compare( bDateTime, aDateTime ) ); } // end of testSecond
// // Abstract Java Tested Class // package org.joda.time; // // import java.io.Serializable; // import java.util.Comparator; // import org.joda.time.convert.ConverterManager; // import org.joda.time.convert.InstantConverter; // // // // public class DateTimeComparator implements Comparator<Object>, Serializable { // private static final long serialVersionUID = -6097339773320178364L; // private static final DateTimeComparator ALL_INSTANCE = new DateTimeComparator(null, null); // private static final DateTimeComparator DATE_INSTANCE = new DateTimeComparator(DateTimeFieldType.dayOfYear(), null); // private static final DateTimeComparator TIME_INSTANCE = new DateTimeComparator(null, DateTimeFieldType.dayOfYear()); // private final DateTimeFieldType iLowerLimit; // private final DateTimeFieldType iUpperLimit; // // public static DateTimeComparator getInstance(); // public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit); // public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); // public static DateTimeComparator getDateOnlyInstance(); // public static DateTimeComparator getTimeOnlyInstance(); // protected DateTimeComparator(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); // public DateTimeFieldType getLowerLimit(); // public DateTimeFieldType getUpperLimit(); // public int compare(Object lhsObj, Object rhsObj); // private Object readResolve(); // public boolean equals(Object object); // public int hashCode(); // public String toString(); // } // // // Abstract Java Test Class // package org.joda.time; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.lang.reflect.Modifier; // import java.util.ArrayList; // import java.util.Calendar; // import java.util.Collections; // import java.util.Comparator; // import java.util.Date; // import java.util.List; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.joda.time.chrono.ISOChronology; // // // // public class TestDateTimeComparator extends TestCase { // private static final Chronology ISO = ISOChronology.getInstance(); // DateTime aDateTime = null; // DateTime bDateTime = null; // Comparator cMillis = null; // Comparator cSecond = null; // Comparator cMinute = null; // Comparator cHour = null; // Comparator cDayOfWeek = null; // Comparator cDayOfMonth = null; // Comparator cDayOfYear = null; // Comparator cWeekOfWeekyear = null; // Comparator cWeekyear = null; // Comparator cMonth = null; // Comparator cYear = null; // Comparator cDate = null; // Comparator cTime = null; // // public static void main(String[] args); // public static TestSuite suite(); // public TestDateTimeComparator(String name); // public void setUp() /* throws Exception */; // protected void tearDown() /* throws Exception */; // public void testClass(); // public void testStaticGetInstance(); // public void testStaticGetDateOnlyInstance(); // public void testStaticGetTimeOnlyInstance(); // public void testStaticGetInstanceLower(); // public void testStaticGetInstanceLowerUpper(); // public void testEqualsHashCode(); // public void testSerialization1() throws Exception; // public void testSerialization2() throws Exception; // public void testBasicComps1(); // public void testBasicComps2(); // public void testBasicComps3(); // public void testBasicComps4(); // public void testBasicComps5(); // public void testMillis(); // public void testSecond(); // public void testMinute(); // public void testHour(); // public void testDOW(); // public void testDOM(); // public void testDOY(); // public void testWOW(); // public void testWOYY(); // public void testMonth(); // public void testYear(); // public void testListBasic(); // public void testListMillis(); // public void testListSecond(); // public void testListMinute(); // public void testListHour(); // public void testListDOW(); // public void testListDOM(); // public void testListDOY(); // public void testListWOW(); // public void testListYOYY(); // public void testListMonth(); // public void testListYear(); // public void testListDate(); // public void testListTime(); // public void testNullDT(); // public void testInvalidObj(); // private DateTime getADate(String s); // private List loadAList(String[] someStrs); // private boolean isListSorted(List tl); // } // You are a professional Java test case writer, please create a test case named `testSecond` for the `DateTimeComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test unequal comparisons with second comparators. */
src/test/java/org/joda/time/TestDateTimeComparator.java
package org.joda.time; import java.io.Serializable; import java.util.Comparator; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.InstantConverter;
public static DateTimeComparator getInstance(); public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit); public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); public static DateTimeComparator getDateOnlyInstance(); public static DateTimeComparator getTimeOnlyInstance(); protected DateTimeComparator(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); public DateTimeFieldType getLowerLimit(); public DateTimeFieldType getUpperLimit(); public int compare(Object lhsObj, Object rhsObj); private Object readResolve(); public boolean equals(Object object); public int hashCode(); public String toString();
443
testSecond
```java // Abstract Java Tested Class package org.joda.time; import java.io.Serializable; import java.util.Comparator; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.InstantConverter; public class DateTimeComparator implements Comparator<Object>, Serializable { private static final long serialVersionUID = -6097339773320178364L; private static final DateTimeComparator ALL_INSTANCE = new DateTimeComparator(null, null); private static final DateTimeComparator DATE_INSTANCE = new DateTimeComparator(DateTimeFieldType.dayOfYear(), null); private static final DateTimeComparator TIME_INSTANCE = new DateTimeComparator(null, DateTimeFieldType.dayOfYear()); private final DateTimeFieldType iLowerLimit; private final DateTimeFieldType iUpperLimit; public static DateTimeComparator getInstance(); public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit); public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); public static DateTimeComparator getDateOnlyInstance(); public static DateTimeComparator getTimeOnlyInstance(); protected DateTimeComparator(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); public DateTimeFieldType getLowerLimit(); public DateTimeFieldType getUpperLimit(); public int compare(Object lhsObj, Object rhsObj); private Object readResolve(); public boolean equals(Object object); public int hashCode(); public String toString(); } // Abstract Java Test Class package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.ISOChronology; public class TestDateTimeComparator extends TestCase { private static final Chronology ISO = ISOChronology.getInstance(); DateTime aDateTime = null; DateTime bDateTime = null; Comparator cMillis = null; Comparator cSecond = null; Comparator cMinute = null; Comparator cHour = null; Comparator cDayOfWeek = null; Comparator cDayOfMonth = null; Comparator cDayOfYear = null; Comparator cWeekOfWeekyear = null; Comparator cWeekyear = null; Comparator cMonth = null; Comparator cYear = null; Comparator cDate = null; Comparator cTime = null; public static void main(String[] args); public static TestSuite suite(); public TestDateTimeComparator(String name); public void setUp() /* throws Exception */; protected void tearDown() /* throws Exception */; public void testClass(); public void testStaticGetInstance(); public void testStaticGetDateOnlyInstance(); public void testStaticGetTimeOnlyInstance(); public void testStaticGetInstanceLower(); public void testStaticGetInstanceLowerUpper(); public void testEqualsHashCode(); public void testSerialization1() throws Exception; public void testSerialization2() throws Exception; public void testBasicComps1(); public void testBasicComps2(); public void testBasicComps3(); public void testBasicComps4(); public void testBasicComps5(); public void testMillis(); public void testSecond(); public void testMinute(); public void testHour(); public void testDOW(); public void testDOM(); public void testDOY(); public void testWOW(); public void testWOYY(); public void testMonth(); public void testYear(); public void testListBasic(); public void testListMillis(); public void testListSecond(); public void testListMinute(); public void testListHour(); public void testListDOW(); public void testListDOM(); public void testListDOY(); public void testListWOW(); public void testListYOYY(); public void testListMonth(); public void testListYear(); public void testListDate(); public void testListTime(); public void testNullDT(); public void testInvalidObj(); private DateTime getADate(String s); private List loadAList(String[] someStrs); private boolean isListSorted(List tl); } ``` You are a professional Java test case writer, please create a test case named `testSecond` for the `DateTimeComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test unequal comparisons with second comparators. */
434
// // Abstract Java Tested Class // package org.joda.time; // // import java.io.Serializable; // import java.util.Comparator; // import org.joda.time.convert.ConverterManager; // import org.joda.time.convert.InstantConverter; // // // // public class DateTimeComparator implements Comparator<Object>, Serializable { // private static final long serialVersionUID = -6097339773320178364L; // private static final DateTimeComparator ALL_INSTANCE = new DateTimeComparator(null, null); // private static final DateTimeComparator DATE_INSTANCE = new DateTimeComparator(DateTimeFieldType.dayOfYear(), null); // private static final DateTimeComparator TIME_INSTANCE = new DateTimeComparator(null, DateTimeFieldType.dayOfYear()); // private final DateTimeFieldType iLowerLimit; // private final DateTimeFieldType iUpperLimit; // // public static DateTimeComparator getInstance(); // public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit); // public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); // public static DateTimeComparator getDateOnlyInstance(); // public static DateTimeComparator getTimeOnlyInstance(); // protected DateTimeComparator(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); // public DateTimeFieldType getLowerLimit(); // public DateTimeFieldType getUpperLimit(); // public int compare(Object lhsObj, Object rhsObj); // private Object readResolve(); // public boolean equals(Object object); // public int hashCode(); // public String toString(); // } // // // Abstract Java Test Class // package org.joda.time; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.lang.reflect.Modifier; // import java.util.ArrayList; // import java.util.Calendar; // import java.util.Collections; // import java.util.Comparator; // import java.util.Date; // import java.util.List; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.joda.time.chrono.ISOChronology; // // // // public class TestDateTimeComparator extends TestCase { // private static final Chronology ISO = ISOChronology.getInstance(); // DateTime aDateTime = null; // DateTime bDateTime = null; // Comparator cMillis = null; // Comparator cSecond = null; // Comparator cMinute = null; // Comparator cHour = null; // Comparator cDayOfWeek = null; // Comparator cDayOfMonth = null; // Comparator cDayOfYear = null; // Comparator cWeekOfWeekyear = null; // Comparator cWeekyear = null; // Comparator cMonth = null; // Comparator cYear = null; // Comparator cDate = null; // Comparator cTime = null; // // public static void main(String[] args); // public static TestSuite suite(); // public TestDateTimeComparator(String name); // public void setUp() /* throws Exception */; // protected void tearDown() /* throws Exception */; // public void testClass(); // public void testStaticGetInstance(); // public void testStaticGetDateOnlyInstance(); // public void testStaticGetTimeOnlyInstance(); // public void testStaticGetInstanceLower(); // public void testStaticGetInstanceLowerUpper(); // public void testEqualsHashCode(); // public void testSerialization1() throws Exception; // public void testSerialization2() throws Exception; // public void testBasicComps1(); // public void testBasicComps2(); // public void testBasicComps3(); // public void testBasicComps4(); // public void testBasicComps5(); // public void testMillis(); // public void testSecond(); // public void testMinute(); // public void testHour(); // public void testDOW(); // public void testDOM(); // public void testDOY(); // public void testWOW(); // public void testWOYY(); // public void testMonth(); // public void testYear(); // public void testListBasic(); // public void testListMillis(); // public void testListSecond(); // public void testListMinute(); // public void testListHour(); // public void testListDOW(); // public void testListDOM(); // public void testListDOY(); // public void testListWOW(); // public void testListYOYY(); // public void testListMonth(); // public void testListYear(); // public void testListDate(); // public void testListTime(); // public void testNullDT(); // public void testInvalidObj(); // private DateTime getADate(String s); // private List loadAList(String[] someStrs); // private boolean isListSorted(List tl); // } // You are a professional Java test case writer, please create a test case named `testSecond` for the `DateTimeComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test unequal comparisons with second comparators. */ // } // end of testMillis // assertEquals( "MillisP1", 1, cMillis.compare( bDateTime, aDateTime ) ); // assertEquals( "MillisM1", -1, cMillis.compare( aDateTime, bDateTime ) ); // bDateTime = new DateTime( aDateTime.getMillis() + 1, DateTimeZone.UTC ); // aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); // public void testMillis() { // Defects4J: flaky method public void testSecond() {
/** * Test unequal comparisons with second comparators. */ // } // end of testMillis // assertEquals( "MillisP1", 1, cMillis.compare( bDateTime, aDateTime ) ); // assertEquals( "MillisM1", -1, cMillis.compare( aDateTime, bDateTime ) ); // bDateTime = new DateTime( aDateTime.getMillis() + 1, DateTimeZone.UTC ); // aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); // public void testMillis() { // Defects4J: flaky method
1
org.joda.time.DateTimeComparator
src/test/java
```java // Abstract Java Tested Class package org.joda.time; import java.io.Serializable; import java.util.Comparator; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.InstantConverter; public class DateTimeComparator implements Comparator<Object>, Serializable { private static final long serialVersionUID = -6097339773320178364L; private static final DateTimeComparator ALL_INSTANCE = new DateTimeComparator(null, null); private static final DateTimeComparator DATE_INSTANCE = new DateTimeComparator(DateTimeFieldType.dayOfYear(), null); private static final DateTimeComparator TIME_INSTANCE = new DateTimeComparator(null, DateTimeFieldType.dayOfYear()); private final DateTimeFieldType iLowerLimit; private final DateTimeFieldType iUpperLimit; public static DateTimeComparator getInstance(); public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit); public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); public static DateTimeComparator getDateOnlyInstance(); public static DateTimeComparator getTimeOnlyInstance(); protected DateTimeComparator(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit); public DateTimeFieldType getLowerLimit(); public DateTimeFieldType getUpperLimit(); public int compare(Object lhsObj, Object rhsObj); private Object readResolve(); public boolean equals(Object object); public int hashCode(); public String toString(); } // Abstract Java Test Class package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.ISOChronology; public class TestDateTimeComparator extends TestCase { private static final Chronology ISO = ISOChronology.getInstance(); DateTime aDateTime = null; DateTime bDateTime = null; Comparator cMillis = null; Comparator cSecond = null; Comparator cMinute = null; Comparator cHour = null; Comparator cDayOfWeek = null; Comparator cDayOfMonth = null; Comparator cDayOfYear = null; Comparator cWeekOfWeekyear = null; Comparator cWeekyear = null; Comparator cMonth = null; Comparator cYear = null; Comparator cDate = null; Comparator cTime = null; public static void main(String[] args); public static TestSuite suite(); public TestDateTimeComparator(String name); public void setUp() /* throws Exception */; protected void tearDown() /* throws Exception */; public void testClass(); public void testStaticGetInstance(); public void testStaticGetDateOnlyInstance(); public void testStaticGetTimeOnlyInstance(); public void testStaticGetInstanceLower(); public void testStaticGetInstanceLowerUpper(); public void testEqualsHashCode(); public void testSerialization1() throws Exception; public void testSerialization2() throws Exception; public void testBasicComps1(); public void testBasicComps2(); public void testBasicComps3(); public void testBasicComps4(); public void testBasicComps5(); public void testMillis(); public void testSecond(); public void testMinute(); public void testHour(); public void testDOW(); public void testDOM(); public void testDOY(); public void testWOW(); public void testWOYY(); public void testMonth(); public void testYear(); public void testListBasic(); public void testListMillis(); public void testListSecond(); public void testListMinute(); public void testListHour(); public void testListDOW(); public void testListDOM(); public void testListDOY(); public void testListWOW(); public void testListYOYY(); public void testListMonth(); public void testListYear(); public void testListDate(); public void testListTime(); public void testNullDT(); public void testInvalidObj(); private DateTime getADate(String s); private List loadAList(String[] someStrs); private boolean isListSorted(List tl); } ``` You are a professional Java test case writer, please create a test case named `testSecond` for the `DateTimeComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test unequal comparisons with second comparators. */ // } // end of testMillis // assertEquals( "MillisP1", 1, cMillis.compare( bDateTime, aDateTime ) ); // assertEquals( "MillisM1", -1, cMillis.compare( aDateTime, bDateTime ) ); // bDateTime = new DateTime( aDateTime.getMillis() + 1, DateTimeZone.UTC ); // aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); // public void testMillis() { // Defects4J: flaky method public void testSecond() { ```
public class DateTimeComparator implements Comparator<Object>, Serializable
package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.ISOChronology;
public static void main(String[] args); public static TestSuite suite(); public TestDateTimeComparator(String name); public void setUp() /* throws Exception */; protected void tearDown() /* throws Exception */; public void testClass(); public void testStaticGetInstance(); public void testStaticGetDateOnlyInstance(); public void testStaticGetTimeOnlyInstance(); public void testStaticGetInstanceLower(); public void testStaticGetInstanceLowerUpper(); public void testEqualsHashCode(); public void testSerialization1() throws Exception; public void testSerialization2() throws Exception; public void testBasicComps1(); public void testBasicComps2(); public void testBasicComps3(); public void testBasicComps4(); public void testBasicComps5(); public void testMillis(); public void testSecond(); public void testMinute(); public void testHour(); public void testDOW(); public void testDOM(); public void testDOY(); public void testWOW(); public void testWOYY(); public void testMonth(); public void testYear(); public void testListBasic(); public void testListMillis(); public void testListSecond(); public void testListMinute(); public void testListHour(); public void testListDOW(); public void testListDOM(); public void testListDOY(); public void testListWOW(); public void testListYOYY(); public void testListMonth(); public void testListYear(); public void testListDate(); public void testListTime(); public void testNullDT(); public void testInvalidObj(); private DateTime getADate(String s); private List loadAList(String[] someStrs); private boolean isListSorted(List tl);
f86148a6dc4a9dea418d8a9bd088c59afb8d8adca2248d41c2f407cc45a30c36
[ "org.joda.time.TestDateTimeComparator::testSecond" ]
private static final long serialVersionUID = -6097339773320178364L; private static final DateTimeComparator ALL_INSTANCE = new DateTimeComparator(null, null); private static final DateTimeComparator DATE_INSTANCE = new DateTimeComparator(DateTimeFieldType.dayOfYear(), null); private static final DateTimeComparator TIME_INSTANCE = new DateTimeComparator(null, DateTimeFieldType.dayOfYear()); private final DateTimeFieldType iLowerLimit; private final DateTimeFieldType iUpperLimit;
public void testSecond()
private static final Chronology ISO = ISOChronology.getInstance(); DateTime aDateTime = null; DateTime bDateTime = null; Comparator cMillis = null; Comparator cSecond = null; Comparator cMinute = null; Comparator cHour = null; Comparator cDayOfWeek = null; Comparator cDayOfMonth = null; Comparator cDayOfYear = null; Comparator cWeekOfWeekyear = null; Comparator cWeekyear = null; Comparator cMonth = null; Comparator cYear = null; Comparator cDate = null; Comparator cTime = null;
Time
/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for the * org.joda.time.DateTimeComparator class. * * @author Guy Allard */ public class TestDateTimeComparator extends TestCase { private static final Chronology ISO = ISOChronology.getInstance(); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeComparator.class); } public TestDateTimeComparator(String name) { super(name); } /** * A reference to a DateTime object. */ DateTime aDateTime = null; /** * A reference to a DateTime object. */ DateTime bDateTime = null; /** * A reference to a DateTimeComparator object * (a Comparator) for millis of seconds. */ Comparator cMillis = null; /** * A reference to a DateTimeComparator object * (a Comparator) for seconds. */ Comparator cSecond = null; /** * A reference to a DateTimeComparator object * (a Comparator) for minutes. */ Comparator cMinute = null; /** * A reference to a DateTimeComparator object * (a Comparator) for hours. */ Comparator cHour = null; /** * A reference to a DateTimeComparator object * (a Comparator) for day of the week. */ Comparator cDayOfWeek = null; /** * A reference to a DateTimeComparator object * (a Comparator) for day of the month. */ Comparator cDayOfMonth = null; /** * A reference to a DateTimeComparator object * (a Comparator) for day of the year. */ Comparator cDayOfYear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for week of the weekyear. */ Comparator cWeekOfWeekyear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for year given a week of the year. */ Comparator cWeekyear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for months. */ Comparator cMonth = null; /** * A reference to a DateTimeComparator object * (a Comparator) for year. */ Comparator cYear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for the date portion of an * object. */ Comparator cDate = null; /** * A reference to a DateTimeComparator object * (a Comparator) for the time portion of an * object. */ Comparator cTime = null; /** * Junit <code>setUp()</code> method. */ public void setUp() /* throws Exception */ { Chronology chrono = ISOChronology.getInstanceUTC(); // super.setUp(); // Obtain comparator's cMillis = DateTimeComparator.getInstance(null, DateTimeFieldType.secondOfMinute()); cSecond = DateTimeComparator.getInstance(DateTimeFieldType.secondOfMinute(), DateTimeFieldType.minuteOfHour()); cMinute = DateTimeComparator.getInstance(DateTimeFieldType.minuteOfHour(), DateTimeFieldType.hourOfDay()); cHour = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.dayOfYear()); cDayOfWeek = DateTimeComparator.getInstance(DateTimeFieldType.dayOfWeek(), DateTimeFieldType.weekOfWeekyear()); cDayOfMonth = DateTimeComparator.getInstance(DateTimeFieldType.dayOfMonth(), DateTimeFieldType.monthOfYear()); cDayOfYear = DateTimeComparator.getInstance(DateTimeFieldType.dayOfYear(), DateTimeFieldType.year()); cWeekOfWeekyear = DateTimeComparator.getInstance(DateTimeFieldType.weekOfWeekyear(), DateTimeFieldType.weekyear()); cWeekyear = DateTimeComparator.getInstance(DateTimeFieldType.weekyear()); cMonth = DateTimeComparator.getInstance(DateTimeFieldType.monthOfYear(), DateTimeFieldType.year()); cYear = DateTimeComparator.getInstance(DateTimeFieldType.year()); cDate = DateTimeComparator.getDateOnlyInstance(); cTime = DateTimeComparator.getTimeOnlyInstance(); } /** * Junit <code>tearDown()</code> method. */ protected void tearDown() /* throws Exception */ { // super.tearDown(); aDateTime = null; bDateTime = null; // cMillis = null; cSecond = null; cMinute = null; cHour = null; cDayOfWeek = null; cDayOfMonth = null; cDayOfYear = null; cWeekOfWeekyear = null; cWeekyear = null; cMonth = null; cYear = null; cDate = null; cTime = null; } //----------------------------------------------------------------------- public void testClass() { assertEquals(true, Modifier.isPublic(DateTimeComparator.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateTimeComparator.class.getModifiers())); assertEquals(1, DateTimeComparator.class.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(DateTimeComparator.class.getDeclaredConstructors()[0].getModifiers())); } //----------------------------------------------------------------------- public void testStaticGetInstance() { DateTimeComparator c = DateTimeComparator.getInstance(); assertEquals(null, c.getLowerLimit()); assertEquals(null, c.getUpperLimit()); assertEquals("DateTimeComparator[]", c.toString()); } public void testStaticGetDateOnlyInstance() { DateTimeComparator c = DateTimeComparator.getDateOnlyInstance(); assertEquals(DateTimeFieldType.dayOfYear(), c.getLowerLimit()); assertEquals(null, c.getUpperLimit()); assertEquals("DateTimeComparator[dayOfYear-]", c.toString()); assertSame(DateTimeComparator.getDateOnlyInstance(), DateTimeComparator.getDateOnlyInstance()); } public void testStaticGetTimeOnlyInstance() { DateTimeComparator c = DateTimeComparator.getTimeOnlyInstance(); assertEquals(null, c.getLowerLimit()); assertEquals(DateTimeFieldType.dayOfYear(), c.getUpperLimit()); assertEquals("DateTimeComparator[-dayOfYear]", c.toString()); assertSame(DateTimeComparator.getTimeOnlyInstance(), DateTimeComparator.getTimeOnlyInstance()); } public void testStaticGetInstanceLower() { DateTimeComparator c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay()); assertEquals(DateTimeFieldType.hourOfDay(), c.getLowerLimit()); assertEquals(null, c.getUpperLimit()); assertEquals("DateTimeComparator[hourOfDay-]", c.toString()); c = DateTimeComparator.getInstance(null); assertSame(DateTimeComparator.getInstance(), c); } public void testStaticGetInstanceLowerUpper() { DateTimeComparator c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.dayOfYear()); assertEquals(DateTimeFieldType.hourOfDay(), c.getLowerLimit()); assertEquals(DateTimeFieldType.dayOfYear(), c.getUpperLimit()); assertEquals("DateTimeComparator[hourOfDay-dayOfYear]", c.toString()); c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.hourOfDay()); assertEquals(DateTimeFieldType.hourOfDay(), c.getLowerLimit()); assertEquals(DateTimeFieldType.hourOfDay(), c.getUpperLimit()); assertEquals("DateTimeComparator[hourOfDay]", c.toString()); c = DateTimeComparator.getInstance(null, null); assertSame(DateTimeComparator.getInstance(), c); c = DateTimeComparator.getInstance(DateTimeFieldType.dayOfYear(), null); assertSame(DateTimeComparator.getDateOnlyInstance(), c); c = DateTimeComparator.getInstance(null, DateTimeFieldType.dayOfYear()); assertSame(DateTimeComparator.getTimeOnlyInstance(), c); } //----------------------------------------------------------------------- public void testEqualsHashCode() { DateTimeComparator c1 = DateTimeComparator.getInstance(); assertEquals(true, c1.equals(c1)); assertEquals(false, c1.equals(null)); assertEquals(true, c1.hashCode() == c1.hashCode()); DateTimeComparator c2 = DateTimeComparator.getTimeOnlyInstance(); assertEquals(true, c2.equals(c2)); assertEquals(false, c2.equals(c1)); assertEquals(false, c1.equals(c2)); assertEquals(false, c2.equals(null)); assertEquals(false, c1.hashCode() == c2.hashCode()); DateTimeComparator c3 = DateTimeComparator.getTimeOnlyInstance(); assertEquals(true, c3.equals(c3)); assertEquals(false, c3.equals(c1)); assertEquals(true, c3.equals(c2)); assertEquals(false, c1.equals(c3)); assertEquals(true, c2.equals(c3)); assertEquals(false, c1.hashCode() == c3.hashCode()); assertEquals(true, c2.hashCode() == c3.hashCode()); DateTimeComparator c4 = DateTimeComparator.getDateOnlyInstance(); assertEquals(false, c4.hashCode() == c3.hashCode()); } //----------------------------------------------------------------------- public void testSerialization1() throws Exception { DateTimeField f = ISO.dayOfYear(); f.toString(); DateTimeComparator c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.dayOfYear()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(c); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeComparator result = (DateTimeComparator) ois.readObject(); ois.close(); assertEquals(c, result); } //----------------------------------------------------------------------- public void testSerialization2() throws Exception { DateTimeComparator c = DateTimeComparator.getInstance(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(c); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeComparator result = (DateTimeComparator) ois.readObject(); ois.close(); assertSame(c, result); } //----------------------------------------------------------------------- /** * Test all basic comparator operation with DateTime objects. */ public void testBasicComps1() { aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); bDateTime = new DateTime( aDateTime.getMillis(), DateTimeZone.UTC ); assertEquals( "getMillis", aDateTime.getMillis(), bDateTime.getMillis() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with ReadableInstant objects. */ public void testBasicComps2() { ReadableInstant aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); ReadableInstant bDateTime = new DateTime( aDateTime.getMillis(), DateTimeZone.UTC ); assertEquals( "getMillis", aDateTime.getMillis(), bDateTime.getMillis() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with java Date objects. */ public void testBasicComps3() { Date aDateTime = new Date( System.currentTimeMillis() ); Date bDateTime = new Date( aDateTime.getTime() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with Long objects. */ public void testBasicComps4() { Long aDateTime = new Long( System.currentTimeMillis() ); Long bDateTime = new Long( aDateTime.longValue() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with Calendar objects. */ public void testBasicComps5() { Calendar aDateTime = Calendar.getInstance(); // right now Calendar bDateTime = aDateTime; assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test unequal comparisons with millis of second comparators. */ public void testMillis() {} // Defects4J: flaky method // public void testMillis() { // aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); // bDateTime = new DateTime( aDateTime.getMillis() + 1, DateTimeZone.UTC ); // assertEquals( "MillisM1", -1, cMillis.compare( aDateTime, bDateTime ) ); // assertEquals( "MillisP1", 1, cMillis.compare( bDateTime, aDateTime ) ); // } // end of testMillis /** * Test unequal comparisons with second comparators. */ public void testSecond() { aDateTime = getADate( "1969-12-31T23:59:58" ); bDateTime = getADate( "1969-12-31T23:50:59" ); assertEquals( "SecondM1a", -1, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "SecondP1a", 1, cSecond.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1970-01-01T00:00:00" ); bDateTime = getADate( "1970-01-01T00:00:01" ); assertEquals( "SecondM1b", -1, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "SecondP1b", 1, cSecond.compare( bDateTime, aDateTime ) ); } // end of testSecond /** * Test unequal comparisons with minute comparators. */ public void testMinute() { aDateTime = getADate( "1969-12-31T23:58:00" ); bDateTime = getADate( "1969-12-31T23:59:00" ); assertEquals( "MinuteM1a", -1, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "MinuteP1a", 1, cMinute.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1970-01-01T00:00:00" ); bDateTime = getADate( "1970-01-01T00:01:00" ); assertEquals( "MinuteM1b", -1, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "MinuteP1b", 1, cMinute.compare( bDateTime, aDateTime ) ); } // end of testMinute /** * Test unequal comparisons with hour comparators. */ public void testHour() { aDateTime = getADate( "1969-12-31T22:00:00" ); bDateTime = getADate( "1969-12-31T23:00:00" ); assertEquals( "HourM1a", -1, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "HourP1a", 1, cHour.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1970-01-01T00:00:00" ); bDateTime = getADate( "1970-01-01T01:00:00" ); assertEquals( "HourM1b", -1, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "HourP1b", 1, cHour.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1969-12-31T23:59:59" ); bDateTime = getADate( "1970-01-01T00:00:00" ); assertEquals( "HourP1c", 1, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "HourM1c", -1, cHour.compare( bDateTime, aDateTime ) ); } // end of testHour /** * Test unequal comparisons with day of week comparators. */ public void testDOW() { /* * Dates chosen when I wrote the code, so I know what day of * the week it is. */ aDateTime = getADate( "2002-04-12T00:00:00" ); bDateTime = getADate( "2002-04-13T00:00:00" ); assertEquals( "DOWM1a", -1, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOWP1a", 1, cDayOfWeek.compare( bDateTime, aDateTime ) ); } // end of testDOW /** * Test unequal comparisons with day of month comparators. */ public void testDOM() { aDateTime = getADate( "2002-04-12T00:00:00" ); bDateTime = getADate( "2002-04-13T00:00:00" ); assertEquals( "DOMM1a", -1, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOMP1a", 1, cDayOfMonth.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "2000-12-01T00:00:00" ); bDateTime = getADate( "1814-04-30T00:00:00" ); assertEquals( "DOMM1b", -1, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOMP1b", 1, cDayOfMonth.compare( bDateTime, aDateTime ) ); } // end of testDOM /** * Test unequal comparisons with day of year comparators. */ public void testDOY() { aDateTime = getADate( "2002-04-12T00:00:00" ); bDateTime = getADate( "2002-04-13T00:00:00" ); assertEquals( "DOYM1a", -1, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "DOYP1a", 1, cDayOfYear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "2000-02-29T00:00:00" ); bDateTime = getADate( "1814-11-30T00:00:00" ); assertEquals( "DOYM1b", -1, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "DOYP1b", 1, cDayOfYear.compare( bDateTime, aDateTime ) ); } // end of testDOY /** * Test unequal comparisons with week of weekyear comparators. */ public void testWOW() { // 1st week of year contains Jan 04. aDateTime = getADate( "2000-01-04T00:00:00" ); bDateTime = getADate( "2000-01-11T00:00:00" ); assertEquals( "WOWM1a", -1, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WOWP1a", 1, cWeekOfWeekyear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "2000-01-04T00:00:00" ); bDateTime = getADate( "1999-12-31T00:00:00" ); assertEquals( "WOWM1b", -1, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WOWP1b", 1, cWeekOfWeekyear.compare( bDateTime, aDateTime ) ); } // end of testMillis /** * Test unequal comparisons with year given the week comparators. */ public void testWOYY() { // How do I test the end conditions of this? // Don't understand ...... aDateTime = getADate( "1998-12-31T23:59:59" ); bDateTime = getADate( "1999-01-01T00:00:00" ); assertEquals( "YOYYZ", 0, cWeekyear.compare( aDateTime, bDateTime ) ); bDateTime = getADate( "1999-01-04T00:00:00" ); assertEquals( "YOYYM1", -1, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "YOYYP1", 1, cWeekyear.compare( bDateTime, aDateTime ) ); } // end of testWOYY /** * Test unequal comparisons with month comparators. */ public void testMonth() { aDateTime = getADate( "2002-04-30T00:00:00" ); bDateTime = getADate( "2002-05-01T00:00:00" ); assertEquals( "MONTHM1a", -1, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "MONTHP1a", 1, cMonth.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1900-01-01T00:00:00" ); bDateTime = getADate( "1899-12-31T00:00:00" ); assertEquals( "MONTHM1b", -1, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "MONTHP1b", 1, cMonth.compare( bDateTime, aDateTime ) ); } // end of testMonth /** * Test unequal comparisons with year comparators. */ public void testYear() { aDateTime = getADate( "2000-01-01T00:00:00" ); bDateTime = getADate( "2001-01-01T00:00:00" ); assertEquals( "YEARM1a", -1, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "YEARP1a", 1, cYear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1968-12-31T23:59:59" ); bDateTime = getADate( "1970-01-01T00:00:00" ); assertEquals( "YEARM1b", -1, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "YEARP1b", 1, cYear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1969-12-31T23:59:59" ); bDateTime = getADate( "1970-01-01T00:00:00" ); assertEquals( "YEARM1c", -1, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "YEARP1c", 1, cYear.compare( bDateTime, aDateTime ) ); } // end of testYear /* * 'List' processing tests follow. */ /** * Test sorting with full default comparator. */ public void testListBasic() { String[] dtStrs = { "1999-02-01T00:00:00", "1998-01-20T00:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListBasic", !isSorted1, isSorted2); } // end of testListBasic /** * Test sorting with millis of second comparator. */ public void testListMillis() { // List sl = new ArrayList(); long base = 12345L * 1000L; sl.add( new DateTime( base + 999L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 222L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 456L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 888L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 123L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 000L, DateTimeZone.UTC ) ); // boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cMillis ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListLillis", !isSorted1, isSorted2); } // end of testListSecond /** * Test sorting with second comparator. */ public void testListSecond() { String[] dtStrs = { "1999-02-01T00:00:10", "1999-02-01T00:00:30", "1999-02-01T00:00:25", "1999-02-01T00:00:18", "1999-02-01T00:00:01", "1999-02-01T00:00:59", "1999-02-01T00:00:22" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cSecond ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListSecond", !isSorted1, isSorted2); } // end of testListSecond /** * Test sorting with minute comparator. */ public void testListMinute() { String[] dtStrs = { "1999-02-01T00:10:00", "1999-02-01T00:30:00", "1999-02-01T00:25:00", "1999-02-01T00:18:00", "1999-02-01T00:01:00", "1999-02-01T00:59:00", "1999-02-01T00:22:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cMinute ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListMinute", !isSorted1, isSorted2); } // end of testListMinute /** * Test sorting with hour comparator. */ public void testListHour() { String[] dtStrs = { "1999-02-01T10:00:00", "1999-02-01T23:00:00", "1999-02-01T01:00:00", "1999-02-01T15:00:00", "1999-02-01T05:00:00", "1999-02-01T20:00:00", "1999-02-01T17:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cHour ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListHour", !isSorted1, isSorted2); } // end of testListHour /** * Test sorting with day of week comparator. */ public void testListDOW() { String[] dtStrs = { /* 2002-04-15 = Monday */ "2002-04-21T10:00:00", "2002-04-16T10:00:00", "2002-04-15T10:00:00", "2002-04-17T10:00:00", "2002-04-19T10:00:00", "2002-04-18T10:00:00", "2002-04-20T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDayOfWeek ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDOW", !isSorted1, isSorted2); } // end of testListDOW /** * Test sorting with day of month comparator. */ public void testListDOM() { String[] dtStrs = { /* 2002-04-14 = Sunday */ "2002-04-20T10:00:00", "2002-04-16T10:00:00", "2002-04-15T10:00:00", "2002-04-17T10:00:00", "2002-04-19T10:00:00", "2002-04-18T10:00:00", "2002-04-14T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDayOfMonth ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDOM", !isSorted1, isSorted2); } // end of testListDOM /** * Test sorting with day of year comparator. */ public void testListDOY() { String[] dtStrs = { "2002-04-20T10:00:00", "2002-01-16T10:00:00", "2002-12-31T10:00:00", "2002-09-14T10:00:00", "2002-09-19T10:00:00", "2002-02-14T10:00:00", "2002-10-30T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDayOfYear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDOY", !isSorted1, isSorted2); } // end of testListDOY /** * Test sorting with week of weekyear comparator. */ public void testListWOW() { String[] dtStrs = { "2002-04-01T10:00:00", "2002-01-01T10:00:00", "2002-12-01T10:00:00", "2002-09-01T10:00:00", "2002-09-01T10:00:00", "2002-02-01T10:00:00", "2002-10-01T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cWeekOfWeekyear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListWOW", !isSorted1, isSorted2); } // end of testListWOW /** * Test sorting with year (given week) comparator. */ public void testListYOYY() { // ?? How to catch end conditions ?? String[] dtStrs = { "2010-04-01T10:00:00", "2002-01-01T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cWeekyear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListYOYY", !isSorted1, isSorted2); } // end of testListYOYY /** * Test sorting with month comparator. */ public void testListMonth() { String[] dtStrs = { "2002-04-01T10:00:00", "2002-01-01T10:00:00", "2002-12-01T10:00:00", "2002-09-01T10:00:00", "2002-09-01T10:00:00", "2002-02-01T10:00:00", "2002-10-01T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cMonth ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListMonth", !isSorted1, isSorted2); } // end of testListMonth /** * Test sorting with year comparator. */ public void testListYear() { String[] dtStrs = { "1999-02-01T00:00:00", "1998-02-01T00:00:00", "2525-02-01T00:00:00", "1776-02-01T00:00:00", "1863-02-01T00:00:00", "1066-02-01T00:00:00", "2100-02-01T00:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cYear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListYear", !isSorted1, isSorted2); } // end of testListYear /** * Test sorting with date only comparator. */ public void testListDate() { String[] dtStrs = { "1999-02-01T00:00:00", "1998-10-03T00:00:00", "2525-05-20T00:00:00", "1776-12-25T00:00:00", "1863-01-31T00:00:00", "1066-09-22T00:00:00", "2100-07-04T00:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDate ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDate", !isSorted1, isSorted2); } // end of testListDate /** * Test sorting with time only comparator. */ public void testListTime() { String[] dtStrs = { "1999-02-01T01:02:05", "1999-02-01T22:22:22", "1999-02-01T05:30:45", "1999-02-01T09:17:59", "1999-02-01T09:17:58", "1999-02-01T15:30:00", "1999-02-01T17:00:44" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cTime ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListTime", !isSorted1, isSorted2); } // end of testListTime /** * Test comparator operation with null object(s). */ public void testNullDT() { // null means now aDateTime = getADate("2000-01-01T00:00:00"); assertTrue(cYear.compare(null, aDateTime) > 0); assertTrue(cYear.compare(aDateTime, null) < 0); } /** * Test comparator operation with an invalid object type. */ public void testInvalidObj() { aDateTime = getADate("2000-01-01T00:00:00"); try { cYear.compare("FreeBird", aDateTime); fail("Invalid object failed"); } catch (IllegalArgumentException cce) {} } // private convenience methods //----------------------------------------------------------------------- /** * Creates a date to test with. */ private DateTime getADate(String s) { DateTime retDT = null; try { retDT = new DateTime(s, DateTimeZone.UTC); } catch (IllegalArgumentException pe) { pe.printStackTrace(); } return retDT; } /** * Load a string array. */ private List loadAList(String[] someStrs) { List newList = new ArrayList(); try { for (int i = 0; i < someStrs.length; ++i) { newList.add(new DateTime(someStrs[i], DateTimeZone.UTC)); } // end of the for } catch (IllegalArgumentException pe) { pe.printStackTrace(); } return newList; } /** * Check if the list is sorted. */ private boolean isListSorted(List tl) { // tl must be populated with DateTime objects. DateTime lhDT = (DateTime)tl.get(0); DateTime rhDT = null; Long lhVal = new Long( lhDT.getMillis() ); Long rhVal = null; for (int i = 1; i < tl.size(); ++i) { rhDT = (DateTime)tl.get(i); rhVal = new Long( rhDT.getMillis() ); if ( lhVal.compareTo( rhVal) > 0 ) return false; // lhVal = rhVal; // swap for next iteration lhDT = rhDT; // swap for next iteration } return true; } }
[ { "be_test_class_file": "org/joda/time/DateTimeComparator.java", "be_test_class_name": "org.joda.time.DateTimeComparator", "be_test_function_name": "compare", "be_test_function_signature": "(Ljava/lang/Object;Ljava/lang/Object;)I", "line_numbers": [ "192", "193", "194", "196", "197", "198", "200", "201", "202", "205", "206", "207", "210", "211", "212", "213", "215" ], "method_line_rate": 0.9411764705882353 }, { "be_test_class_file": "org/joda/time/DateTimeComparator.java", "be_test_class_name": "org.joda.time.DateTimeComparator", "be_test_function_name": "getDateOnlyInstance", "be_test_function_signature": "()Lorg/joda/time/DateTimeComparator;", "line_numbers": [ "130" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/DateTimeComparator.java", "be_test_class_name": "org.joda.time.DateTimeComparator", "be_test_function_name": "getInstance", "be_test_function_signature": "(Lorg/joda/time/DateTimeFieldType;)Lorg/joda/time/DateTimeComparator;", "line_numbers": [ "87" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/DateTimeComparator.java", "be_test_class_name": "org.joda.time.DateTimeComparator", "be_test_function_name": "getInstance", "be_test_function_signature": "(Lorg/joda/time/DateTimeFieldType;Lorg/joda/time/DateTimeFieldType;)Lorg/joda/time/DateTimeComparator;", "line_numbers": [ "106", "107", "109", "110", "112", "113", "115" ], "method_line_rate": 0.5714285714285714 }, { "be_test_class_file": "org/joda/time/DateTimeComparator.java", "be_test_class_name": "org.joda.time.DateTimeComparator", "be_test_function_name": "getTimeOnlyInstance", "be_test_function_signature": "()Lorg/joda/time/DateTimeComparator;", "line_numbers": [ "145" ], "method_line_rate": 1 } ]
public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest
@Test public void testGLSEfficiency() { RandomGenerator rg = new JDKRandomGenerator(); rg.setSeed(200); // Seed has been selected to generate non-trivial covariance // Assume model has 16 observations (will use Longley data). Start by generating // non-constant variances for the 16 error terms. final int nObs = 16; double[] sigma = new double[nObs]; for (int i = 0; i < nObs; i++) { sigma[i] = 10 * rg.nextDouble(); } // Now generate 1000 error vectors to use to estimate the covariance matrix // Columns are draws on N(0, sigma[col]) final int numSeeds = 1000; RealMatrix errorSeeds = MatrixUtils.createRealMatrix(numSeeds, nObs); for (int i = 0; i < numSeeds; i++) { for (int j = 0; j < nObs; j++) { errorSeeds.setEntry(i, j, rg.nextGaussian() * sigma[j]); } } // Get covariance matrix for columns RealMatrix cov = (new Covariance(errorSeeds)).getCovarianceMatrix(); // Create a CorrelatedRandomVectorGenerator to use to generate correlated errors GaussianRandomGenerator rawGenerator = new GaussianRandomGenerator(rg); double[] errorMeans = new double[nObs]; // Counting on init to 0 here CorrelatedRandomVectorGenerator gen = new CorrelatedRandomVectorGenerator(errorMeans, cov, 1.0e-12 * cov.getNorm(), rawGenerator); // Now start generating models. Use Longley X matrix on LHS // and Longley OLS beta vector as "true" beta. Generate // Y values by XB + u where u is a CorrelatedRandomVector generated // from cov. OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression(); ols.newSampleData(longley, nObs, 6); final RealVector b = ols.calculateBeta().copy(); final RealMatrix x = ols.getX().copy(); // Create a GLS model to reuse GLSMultipleLinearRegression gls = new GLSMultipleLinearRegression(); gls.newSampleData(longley, nObs, 6); gls.newCovarianceData(cov.getData()); // Create aggregators for stats measuring model performance DescriptiveStatistics olsBetaStats = new DescriptiveStatistics(); DescriptiveStatistics glsBetaStats = new DescriptiveStatistics(); // Generate Y vectors for 10000 models, estimate GLS and OLS and // Verify that OLS estimates are better final int nModels = 10000; for (int i = 0; i < nModels; i++) { // Generate y = xb + u with u cov RealVector u = MatrixUtils.createRealVector(gen.nextVector()); double[] y = u.add(x.operate(b)).toArray(); // Estimate OLS parameters ols.newYSampleData(y); RealVector olsBeta = ols.calculateBeta(); // Estimate GLS parameters gls.newYSampleData(y); RealVector glsBeta = gls.calculateBeta(); // Record deviations from "true" beta double dist = olsBeta.getDistance(b); olsBetaStats.addValue(dist * dist); dist = glsBeta.getDistance(b); glsBetaStats.addValue(dist * dist); } // Verify that GLS is on average more efficient, lower variance assert(olsBetaStats.getMean() > 1.5 * glsBetaStats.getMean()); assert(olsBetaStats.getStandardDeviation() > glsBetaStats.getStandardDeviation()); }
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.regression; // // import org.apache.commons.math3.linear.LUDecomposition; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.Array2DRowRealMatrix; // import org.apache.commons.math3.linear.RealVector; // // // // public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegression { // private RealMatrix Omega; // private RealMatrix OmegaInverse; // // public void newSampleData(double[] y, double[][] x, double[][] covariance); // protected void newCovarianceData(double[][] omega); // protected RealMatrix getOmegaInverse(); // @Override // protected RealVector calculateBeta(); // @Override // protected RealMatrix calculateBetaVariance(); // @Override // protected double calculateErrorVariance(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.regression; // // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.linear.MatrixUtils; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.RealVector; // import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator; // import org.apache.commons.math3.random.JDKRandomGenerator; // import org.apache.commons.math3.random.GaussianRandomGenerator; // import org.apache.commons.math3.random.RandomGenerator; // import org.apache.commons.math3.stat.correlation.Covariance; // import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; // // // // public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { // private double[] y; // private double[][] x; // private double[][] omega; // private double[] longley = new double[] { // 60323,83.0,234289,2356,1590,107608,1947, // 61122,88.5,259426,2325,1456,108632,1948, // 60171,88.2,258054,3682,1616,109773,1949, // 61187,89.5,284599,3351,1650,110929,1950, // 63221,96.2,328975,2099,3099,112075,1951, // 63639,98.1,346999,1932,3594,113270,1952, // 64989,99.0,365385,1870,3547,115094,1953, // 63761,100.0,363112,3578,3350,116219,1954, // 66019,101.2,397469,2904,3048,117388,1955, // 67857,104.6,419180,2822,2857,118734,1956, // 68169,108.4,442769,2936,2798,120445,1957, // 66513,110.8,444546,4681,2637,121950,1958, // 68655,112.6,482704,3813,2552,123366,1959, // 69564,114.2,502601,3931,2514,125368,1960, // 69331,115.7,518173,4806,2572,127852,1961, // 70551,116.9,554894,4007,2827,130081,1962 // }; // // @Before // @Override // public void setUp(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddXSampleData(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddNullYSampleData(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddSampleDataWithSizeMismatch(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddNullCovarianceData(); // @Test(expected=IllegalArgumentException.class) // public void notEnoughData(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddCovarianceDataWithSampleSizeMismatch(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddCovarianceDataThatIsNotSquare(); // @Override // protected GLSMultipleLinearRegression createRegression(); // @Override // protected int getNumberOfRegressors(); // @Override // protected int getSampleSize(); // @Test // public void testYVariance(); // @Test // public void testNewSample2(); // @Test // public void testGLSOLSConsistency(); // @Test // public void testGLSEfficiency(); // } // You are a professional Java test case writer, please create a test case named `testGLSEfficiency` for the `GLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Generate an error covariance matrix and sample data representing models * with this error structure. Then verify that GLS estimated coefficients, * on average, perform better than OLS. */
src/test/java/org/apache/commons/math3/stat/regression/GLSMultipleLinearRegressionTest.java
package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealVector;
public void newSampleData(double[] y, double[][] x, double[][] covariance); protected void newCovarianceData(double[][] omega); protected RealMatrix getOmegaInverse(); @Override protected RealVector calculateBeta(); @Override protected RealMatrix calculateBetaVariance(); @Override protected double calculateErrorVariance();
294
testGLSEfficiency
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealVector; public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegression { private RealMatrix Omega; private RealMatrix OmegaInverse; public void newSampleData(double[] y, double[][] x, double[][] covariance); protected void newCovarianceData(double[][] omega); protected RealMatrix getOmegaInverse(); @Override protected RealVector calculateBeta(); @Override protected RealMatrix calculateBetaVariance(); @Override protected double calculateErrorVariance(); } // Abstract Java Test Class package org.apache.commons.math3.stat.regression; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.GaussianRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { private double[] y; private double[][] x; private double[][] omega; private double[] longley = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; @Before @Override public void setUp(); @Test(expected=IllegalArgumentException.class) public void cannotAddXSampleData(); @Test(expected=IllegalArgumentException.class) public void cannotAddNullYSampleData(); @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch(); @Test(expected=IllegalArgumentException.class) public void cannotAddNullCovarianceData(); @Test(expected=IllegalArgumentException.class) public void notEnoughData(); @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataWithSampleSizeMismatch(); @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataThatIsNotSquare(); @Override protected GLSMultipleLinearRegression createRegression(); @Override protected int getNumberOfRegressors(); @Override protected int getSampleSize(); @Test public void testYVariance(); @Test public void testNewSample2(); @Test public void testGLSOLSConsistency(); @Test public void testGLSEfficiency(); } ``` You are a professional Java test case writer, please create a test case named `testGLSEfficiency` for the `GLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Generate an error covariance matrix and sample data representing models * with this error structure. Then verify that GLS estimated coefficients, * on average, perform better than OLS. */
216
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.regression; // // import org.apache.commons.math3.linear.LUDecomposition; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.Array2DRowRealMatrix; // import org.apache.commons.math3.linear.RealVector; // // // // public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegression { // private RealMatrix Omega; // private RealMatrix OmegaInverse; // // public void newSampleData(double[] y, double[][] x, double[][] covariance); // protected void newCovarianceData(double[][] omega); // protected RealMatrix getOmegaInverse(); // @Override // protected RealVector calculateBeta(); // @Override // protected RealMatrix calculateBetaVariance(); // @Override // protected double calculateErrorVariance(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.regression; // // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.linear.MatrixUtils; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.RealVector; // import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator; // import org.apache.commons.math3.random.JDKRandomGenerator; // import org.apache.commons.math3.random.GaussianRandomGenerator; // import org.apache.commons.math3.random.RandomGenerator; // import org.apache.commons.math3.stat.correlation.Covariance; // import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; // // // // public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { // private double[] y; // private double[][] x; // private double[][] omega; // private double[] longley = new double[] { // 60323,83.0,234289,2356,1590,107608,1947, // 61122,88.5,259426,2325,1456,108632,1948, // 60171,88.2,258054,3682,1616,109773,1949, // 61187,89.5,284599,3351,1650,110929,1950, // 63221,96.2,328975,2099,3099,112075,1951, // 63639,98.1,346999,1932,3594,113270,1952, // 64989,99.0,365385,1870,3547,115094,1953, // 63761,100.0,363112,3578,3350,116219,1954, // 66019,101.2,397469,2904,3048,117388,1955, // 67857,104.6,419180,2822,2857,118734,1956, // 68169,108.4,442769,2936,2798,120445,1957, // 66513,110.8,444546,4681,2637,121950,1958, // 68655,112.6,482704,3813,2552,123366,1959, // 69564,114.2,502601,3931,2514,125368,1960, // 69331,115.7,518173,4806,2572,127852,1961, // 70551,116.9,554894,4007,2827,130081,1962 // }; // // @Before // @Override // public void setUp(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddXSampleData(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddNullYSampleData(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddSampleDataWithSizeMismatch(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddNullCovarianceData(); // @Test(expected=IllegalArgumentException.class) // public void notEnoughData(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddCovarianceDataWithSampleSizeMismatch(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddCovarianceDataThatIsNotSquare(); // @Override // protected GLSMultipleLinearRegression createRegression(); // @Override // protected int getNumberOfRegressors(); // @Override // protected int getSampleSize(); // @Test // public void testYVariance(); // @Test // public void testNewSample2(); // @Test // public void testGLSOLSConsistency(); // @Test // public void testGLSEfficiency(); // } // You are a professional Java test case writer, please create a test case named `testGLSEfficiency` for the `GLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Generate an error covariance matrix and sample data representing models * with this error structure. Then verify that GLS estimated coefficients, * on average, perform better than OLS. */ @Test public void testGLSEfficiency() {
/** * Generate an error covariance matrix and sample data representing models * with this error structure. Then verify that GLS estimated coefficients, * on average, perform better than OLS. */
1
org.apache.commons.math3.stat.regression.GLSMultipleLinearRegression
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealVector; public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegression { private RealMatrix Omega; private RealMatrix OmegaInverse; public void newSampleData(double[] y, double[][] x, double[][] covariance); protected void newCovarianceData(double[][] omega); protected RealMatrix getOmegaInverse(); @Override protected RealVector calculateBeta(); @Override protected RealMatrix calculateBetaVariance(); @Override protected double calculateErrorVariance(); } // Abstract Java Test Class package org.apache.commons.math3.stat.regression; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.GaussianRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { private double[] y; private double[][] x; private double[][] omega; private double[] longley = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; @Before @Override public void setUp(); @Test(expected=IllegalArgumentException.class) public void cannotAddXSampleData(); @Test(expected=IllegalArgumentException.class) public void cannotAddNullYSampleData(); @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch(); @Test(expected=IllegalArgumentException.class) public void cannotAddNullCovarianceData(); @Test(expected=IllegalArgumentException.class) public void notEnoughData(); @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataWithSampleSizeMismatch(); @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataThatIsNotSquare(); @Override protected GLSMultipleLinearRegression createRegression(); @Override protected int getNumberOfRegressors(); @Override protected int getSampleSize(); @Test public void testYVariance(); @Test public void testNewSample2(); @Test public void testGLSOLSConsistency(); @Test public void testGLSEfficiency(); } ``` You are a professional Java test case writer, please create a test case named `testGLSEfficiency` for the `GLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Generate an error covariance matrix and sample data representing models * with this error structure. Then verify that GLS estimated coefficients, * on average, perform better than OLS. */ @Test public void testGLSEfficiency() { ```
public class GLSMultipleLinearRegression extends AbstractMultipleLinearRegression
package org.apache.commons.math3.stat.regression; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.GaussianRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
@Before @Override public void setUp(); @Test(expected=IllegalArgumentException.class) public void cannotAddXSampleData(); @Test(expected=IllegalArgumentException.class) public void cannotAddNullYSampleData(); @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch(); @Test(expected=IllegalArgumentException.class) public void cannotAddNullCovarianceData(); @Test(expected=IllegalArgumentException.class) public void notEnoughData(); @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataWithSampleSizeMismatch(); @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataThatIsNotSquare(); @Override protected GLSMultipleLinearRegression createRegression(); @Override protected int getNumberOfRegressors(); @Override protected int getSampleSize(); @Test public void testYVariance(); @Test public void testNewSample2(); @Test public void testGLSOLSConsistency(); @Test public void testGLSEfficiency();
f90f772e59fbd325fb582f2355e6ee8bb9dbc9ec9b4e2e4795f3d6418f6f1d81
[ "org.apache.commons.math3.stat.regression.GLSMultipleLinearRegressionTest::testGLSEfficiency" ]
private RealMatrix Omega; private RealMatrix OmegaInverse;
@Test public void testGLSEfficiency()
private double[] y; private double[][] x; private double[][] omega; private double[] longley = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 };
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.stat.regression; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.GaussianRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class GLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { private double[] y; private double[][] x; private double[][] omega; private double[] longley = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; @Before @Override public void setUp(){ y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0}; x = new double[6][]; x[0] = new double[]{0, 0, 0, 0, 0}; x[1] = new double[]{2.0, 0, 0, 0, 0}; x[2] = new double[]{0, 3.0, 0, 0, 0}; x[3] = new double[]{0, 0, 4.0, 0, 0}; x[4] = new double[]{0, 0, 0, 5.0, 0}; x[5] = new double[]{0, 0, 0, 0, 6.0}; omega = new double[6][]; omega[0] = new double[]{1.0, 0, 0, 0, 0, 0}; omega[1] = new double[]{0, 2.0, 0, 0, 0, 0}; omega[2] = new double[]{0, 0, 3.0, 0, 0, 0}; omega[3] = new double[]{0, 0, 0, 4.0, 0, 0}; omega[4] = new double[]{0, 0, 0, 0, 5.0, 0}; omega[5] = new double[]{0, 0, 0, 0, 0, 6.0}; super.setUp(); } @Test(expected=IllegalArgumentException.class) public void cannotAddXSampleData() { createRegression().newSampleData(new double[]{}, null, null); } @Test(expected=IllegalArgumentException.class) public void cannotAddNullYSampleData() { createRegression().newSampleData(null, new double[][]{}, null); } @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch() { double[] y = new double[]{1.0, 2.0}; double[][] x = new double[1][]; x[0] = new double[]{1.0, 0}; createRegression().newSampleData(y, x, null); } @Test(expected=IllegalArgumentException.class) public void cannotAddNullCovarianceData() { createRegression().newSampleData(new double[]{}, new double[][]{}, null); } @Test(expected=IllegalArgumentException.class) public void notEnoughData() { double[] reducedY = new double[y.length - 1]; double[][] reducedX = new double[x.length - 1][]; double[][] reducedO = new double[omega.length - 1][]; System.arraycopy(y, 0, reducedY, 0, reducedY.length); System.arraycopy(x, 0, reducedX, 0, reducedX.length); System.arraycopy(omega, 0, reducedO, 0, reducedO.length); createRegression().newSampleData(reducedY, reducedX, reducedO); } @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataWithSampleSizeMismatch() { double[] y = new double[]{1.0, 2.0}; double[][] x = new double[2][]; x[0] = new double[]{1.0, 0}; x[1] = new double[]{0, 1.0}; double[][] omega = new double[1][]; omega[0] = new double[]{1.0, 0}; createRegression().newSampleData(y, x, omega); } @Test(expected=IllegalArgumentException.class) public void cannotAddCovarianceDataThatIsNotSquare() { double[] y = new double[]{1.0, 2.0}; double[][] x = new double[2][]; x[0] = new double[]{1.0, 0}; x[1] = new double[]{0, 1.0}; double[][] omega = new double[3][]; omega[0] = new double[]{1.0, 0}; omega[1] = new double[]{0, 1.0}; omega[2] = new double[]{0, 2.0}; createRegression().newSampleData(y, x, omega); } @Override protected GLSMultipleLinearRegression createRegression() { GLSMultipleLinearRegression regression = new GLSMultipleLinearRegression(); regression.newSampleData(y, x, omega); return regression; } @Override protected int getNumberOfRegressors() { return x[0].length + 1; } @Override protected int getSampleSize() { return y.length; } /** * test calculateYVariance */ @Test public void testYVariance() { // assumes: y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0}; GLSMultipleLinearRegression model = new GLSMultipleLinearRegression(); model.newSampleData(y, x, omega); TestUtils.assertEquals(model.calculateYVariance(), 3.5, 0); } /** * Verifies that setting X, Y and covariance separately has the same effect as newSample(X,Y,cov). */ @Test public void testNewSample2() { double[] y = new double[] {1, 2, 3, 4}; double[][] x = new double[][] { {19, 22, 33}, {20, 30, 40}, {25, 35, 45}, {27, 37, 47} }; double[][] covariance = MatrixUtils.createRealIdentityMatrix(4).scalarMultiply(2).getData(); GLSMultipleLinearRegression regression = new GLSMultipleLinearRegression(); regression.newSampleData(y, x, covariance); RealMatrix combinedX = regression.getX().copy(); RealVector combinedY = regression.getY().copy(); RealMatrix combinedCovInv = regression.getOmegaInverse(); regression.newXSampleData(x); regression.newYSampleData(y); Assert.assertEquals(combinedX, regression.getX()); Assert.assertEquals(combinedY, regression.getY()); Assert.assertEquals(combinedCovInv, regression.getOmegaInverse()); } /** * Verifies that GLS with identity covariance matrix gives the same results * as OLS. */ @Test public void testGLSOLSConsistency() { RealMatrix identityCov = MatrixUtils.createRealIdentityMatrix(16); GLSMultipleLinearRegression glsModel = new GLSMultipleLinearRegression(); OLSMultipleLinearRegression olsModel = new OLSMultipleLinearRegression(); glsModel.newSampleData(longley, 16, 6); olsModel.newSampleData(longley, 16, 6); glsModel.newCovarianceData(identityCov.getData()); double[] olsBeta = olsModel.calculateBeta().toArray(); double[] glsBeta = glsModel.calculateBeta().toArray(); // TODO: Should have assertRelativelyEquals(double[], double[], eps) in TestUtils // Should also add RealVector and RealMatrix versions for (int i = 0; i < olsBeta.length; i++) { TestUtils.assertRelativelyEquals(olsBeta[i], glsBeta[i], 10E-7); } } /** * Generate an error covariance matrix and sample data representing models * with this error structure. Then verify that GLS estimated coefficients, * on average, perform better than OLS. */ @Test public void testGLSEfficiency() { RandomGenerator rg = new JDKRandomGenerator(); rg.setSeed(200); // Seed has been selected to generate non-trivial covariance // Assume model has 16 observations (will use Longley data). Start by generating // non-constant variances for the 16 error terms. final int nObs = 16; double[] sigma = new double[nObs]; for (int i = 0; i < nObs; i++) { sigma[i] = 10 * rg.nextDouble(); } // Now generate 1000 error vectors to use to estimate the covariance matrix // Columns are draws on N(0, sigma[col]) final int numSeeds = 1000; RealMatrix errorSeeds = MatrixUtils.createRealMatrix(numSeeds, nObs); for (int i = 0; i < numSeeds; i++) { for (int j = 0; j < nObs; j++) { errorSeeds.setEntry(i, j, rg.nextGaussian() * sigma[j]); } } // Get covariance matrix for columns RealMatrix cov = (new Covariance(errorSeeds)).getCovarianceMatrix(); // Create a CorrelatedRandomVectorGenerator to use to generate correlated errors GaussianRandomGenerator rawGenerator = new GaussianRandomGenerator(rg); double[] errorMeans = new double[nObs]; // Counting on init to 0 here CorrelatedRandomVectorGenerator gen = new CorrelatedRandomVectorGenerator(errorMeans, cov, 1.0e-12 * cov.getNorm(), rawGenerator); // Now start generating models. Use Longley X matrix on LHS // and Longley OLS beta vector as "true" beta. Generate // Y values by XB + u where u is a CorrelatedRandomVector generated // from cov. OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression(); ols.newSampleData(longley, nObs, 6); final RealVector b = ols.calculateBeta().copy(); final RealMatrix x = ols.getX().copy(); // Create a GLS model to reuse GLSMultipleLinearRegression gls = new GLSMultipleLinearRegression(); gls.newSampleData(longley, nObs, 6); gls.newCovarianceData(cov.getData()); // Create aggregators for stats measuring model performance DescriptiveStatistics olsBetaStats = new DescriptiveStatistics(); DescriptiveStatistics glsBetaStats = new DescriptiveStatistics(); // Generate Y vectors for 10000 models, estimate GLS and OLS and // Verify that OLS estimates are better final int nModels = 10000; for (int i = 0; i < nModels; i++) { // Generate y = xb + u with u cov RealVector u = MatrixUtils.createRealVector(gen.nextVector()); double[] y = u.add(x.operate(b)).toArray(); // Estimate OLS parameters ols.newYSampleData(y); RealVector olsBeta = ols.calculateBeta(); // Estimate GLS parameters gls.newYSampleData(y); RealVector glsBeta = gls.calculateBeta(); // Record deviations from "true" beta double dist = olsBeta.getDistance(b); olsBetaStats.addValue(dist * dist); dist = glsBeta.getDistance(b); glsBetaStats.addValue(dist * dist); } // Verify that GLS is on average more efficient, lower variance assert(olsBetaStats.getMean() > 1.5 * glsBetaStats.getMean()); assert(olsBetaStats.getStandardDeviation() > glsBetaStats.getStandardDeviation()); } }
[ { "be_test_class_file": "org/apache/commons/math3/stat/regression/GLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.GLSMultipleLinearRegression", "be_test_function_name": "calculateBeta", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealVector;", "line_numbers": [ "95", "96", "97", "98", "99" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/GLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.GLSMultipleLinearRegression", "be_test_function_name": "getOmegaInverse", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "80", "81", "83" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/GLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.GLSMultipleLinearRegression", "be_test_function_name": "newCovarianceData", "be_test_function_signature": "([[D)V", "line_numbers": [ "70", "71", "72" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/GLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.GLSMultipleLinearRegression", "be_test_function_name": "newSampleData", "be_test_function_signature": "([D[[D[[D)V", "line_numbers": [ "57", "58", "59", "60", "61", "62" ], "method_line_rate": 1 } ]
public class TestEthiopicChronology extends TestCase
public void testCalendar() { if (TestAll.FAST) { return; } System.out.println("\nTestEthiopicChronology.testCalendar"); DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, ETHIOPIC_UTC); long millis = epoch.getMillis(); long end = new DateTime(3000, 1, 1, 0, 0, 0, 0, ISO_UTC).getMillis(); DateTimeField dayOfWeek = ETHIOPIC_UTC.dayOfWeek(); DateTimeField dayOfYear = ETHIOPIC_UTC.dayOfYear(); DateTimeField dayOfMonth = ETHIOPIC_UTC.dayOfMonth(); DateTimeField monthOfYear = ETHIOPIC_UTC.monthOfYear(); DateTimeField year = ETHIOPIC_UTC.year(); DateTimeField yearOfEra = ETHIOPIC_UTC.yearOfEra(); DateTimeField era = ETHIOPIC_UTC.era(); int expectedDOW = new DateTime(8, 8, 29, 0, 0, 0, 0, JULIAN_UTC).getDayOfWeek(); int expectedDOY = 1; int expectedDay = 1; int expectedMonth = 1; int expectedYear = 1; while (millis < end) { int dowValue = dayOfWeek.get(millis); int doyValue = dayOfYear.get(millis); int dayValue = dayOfMonth.get(millis); int monthValue = monthOfYear.get(millis); int yearValue = year.get(millis); int yearOfEraValue = yearOfEra.get(millis); int monthLen = dayOfMonth.getMaximumValue(millis); if (monthValue < 1 || monthValue > 13) { fail("Bad month: " + millis); } // test era assertEquals(1, era.get(millis)); assertEquals("EE", era.getAsText(millis)); assertEquals("EE", era.getAsShortText(millis)); // test date assertEquals(expectedYear, yearValue); assertEquals(expectedYear, yearOfEraValue); assertEquals(expectedMonth, monthValue); assertEquals(expectedDay, dayValue); assertEquals(expectedDOW, dowValue); assertEquals(expectedDOY, doyValue); // test leap year assertEquals(yearValue % 4 == 3, year.isLeap(millis)); // test month length if (monthValue == 13) { assertEquals(yearValue % 4 == 3, monthOfYear.isLeap(millis)); if (yearValue % 4 == 3) { assertEquals(6, monthLen); } else { assertEquals(5, monthLen); } } else { assertEquals(30, monthLen); } // recalculate date expectedDOW = (((expectedDOW + 1) - 1) % 7) + 1; expectedDay++; expectedDOY++; if (expectedDay == 31 && expectedMonth < 13) { expectedDay = 1; expectedMonth++; } else if (expectedMonth == 13) { if (expectedYear % 4 == 3 && expectedDay == 7) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } else if (expectedYear % 4 != 3 && expectedDay == 6) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } } millis += SKIP; } }
// // Abstract Java Tested Class // package org.joda.time.chrono; // // import java.util.HashMap; // import java.util.Map; // import org.joda.time.Chronology; // import org.joda.time.DateTime; // import org.joda.time.DateTimeConstants; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeZone; // import org.joda.time.field.SkipDateTimeField; // // // // public final class EthiopicChronology extends BasicFixedMonthChronology { // private static final long serialVersionUID = -5972804258688333942L; // public static final int EE = DateTimeConstants.CE; // private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("EE"); // private static final int MIN_YEAR = -292269337; // private static final int MAX_YEAR = 292272984; // private static final Map<DateTimeZone, EthiopicChronology[]> cCache = new HashMap<DateTimeZone, EthiopicChronology[]>(); // private static final EthiopicChronology INSTANCE_UTC; // // public static EthiopicChronology getInstanceUTC(); // public static EthiopicChronology getInstance(); // public static EthiopicChronology getInstance(DateTimeZone zone); // public static EthiopicChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek); // EthiopicChronology(Chronology base, Object param, int minDaysInFirstWeek); // private Object readResolve(); // public Chronology withUTC(); // public Chronology withZone(DateTimeZone zone); // long calculateFirstDayOfYearMillis(int year); // int getMinYear(); // int getMaxYear(); // long getApproxMillisAtEpochDividedByTwo(); // protected void assemble(Fields fields); // } // // // Abstract Java Test Class // package org.joda.time.chrono; // // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.joda.time.Chronology; // import org.joda.time.DateTime; // import org.joda.time.DateTimeConstants; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeUtils; // import org.joda.time.DateTimeZone; // import org.joda.time.DurationField; // import org.joda.time.DurationFieldType; // import org.joda.time.DateTime.Property; // // // // public class TestEthiopicChronology extends TestCase { // private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; // private static long SKIP = 1 * MILLIS_PER_DAY; // private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); // private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); // private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); // private static final Chronology ETHIOPIC_UTC = EthiopicChronology.getInstanceUTC(); // private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); // private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); // long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + // 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + // 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + // 366 + 365; // private long TEST_TIME_NOW = // (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; // private DateTimeZone originalDateTimeZone = null; // private TimeZone originalTimeZone = null; // private Locale originalLocale = null; // // public static void main(String[] args); // public static TestSuite suite(); // public TestEthiopicChronology(String name); // protected void setUp() throws Exception; // protected void tearDown() throws Exception; // public void testFactoryUTC(); // public void testFactory(); // public void testFactory_Zone(); // public void testEquality(); // public void testWithUTC(); // public void testWithZone(); // public void testToString(); // public void testDurationFields(); // public void testDateFields(); // public void testTimeFields(); // public void testEpoch(); // public void testEra(); // public void testCalendar(); // public void testSampleDate(); // public void testSampleDateWithZone(); // public void testDurationYear(); // public void testDurationMonth(); // } // You are a professional Java test case writer, please create a test case named `testCalendar` for the `EthiopicChronology` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */
src/test/java/org/joda/time/chrono/TestEthiopicChronology.java
package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.field.SkipDateTimeField;
public static EthiopicChronology getInstanceUTC(); public static EthiopicChronology getInstance(); public static EthiopicChronology getInstance(DateTimeZone zone); public static EthiopicChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek); EthiopicChronology(Chronology base, Object param, int minDaysInFirstWeek); private Object readResolve(); public Chronology withUTC(); public Chronology withZone(DateTimeZone zone); long calculateFirstDayOfYearMillis(int year); int getMinYear(); int getMaxYear(); long getApproxMillisAtEpochDividedByTwo(); protected void assemble(Fields fields);
397
testCalendar
```java // Abstract Java Tested Class package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.field.SkipDateTimeField; public final class EthiopicChronology extends BasicFixedMonthChronology { private static final long serialVersionUID = -5972804258688333942L; public static final int EE = DateTimeConstants.CE; private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("EE"); private static final int MIN_YEAR = -292269337; private static final int MAX_YEAR = 292272984; private static final Map<DateTimeZone, EthiopicChronology[]> cCache = new HashMap<DateTimeZone, EthiopicChronology[]>(); private static final EthiopicChronology INSTANCE_UTC; public static EthiopicChronology getInstanceUTC(); public static EthiopicChronology getInstance(); public static EthiopicChronology getInstance(DateTimeZone zone); public static EthiopicChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek); EthiopicChronology(Chronology base, Object param, int minDaysInFirstWeek); private Object readResolve(); public Chronology withUTC(); public Chronology withZone(DateTimeZone zone); long calculateFirstDayOfYearMillis(int year); int getMinYear(); int getMaxYear(); long getApproxMillisAtEpochDividedByTwo(); protected void assemble(Fields fields); } // Abstract Java Test Class package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.DateTime.Property; public class TestEthiopicChronology extends TestCase { private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; private static long SKIP = 1 * MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology ETHIOPIC_UTC = EthiopicChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args); public static TestSuite suite(); public TestEthiopicChronology(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testFactoryUTC(); public void testFactory(); public void testFactory_Zone(); public void testEquality(); public void testWithUTC(); public void testWithZone(); public void testToString(); public void testDurationFields(); public void testDateFields(); public void testTimeFields(); public void testEpoch(); public void testEra(); public void testCalendar(); public void testSampleDate(); public void testSampleDateWithZone(); public void testDurationYear(); public void testDurationMonth(); } ``` You are a professional Java test case writer, please create a test case named `testCalendar` for the `EthiopicChronology` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */
315
// // Abstract Java Tested Class // package org.joda.time.chrono; // // import java.util.HashMap; // import java.util.Map; // import org.joda.time.Chronology; // import org.joda.time.DateTime; // import org.joda.time.DateTimeConstants; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeZone; // import org.joda.time.field.SkipDateTimeField; // // // // public final class EthiopicChronology extends BasicFixedMonthChronology { // private static final long serialVersionUID = -5972804258688333942L; // public static final int EE = DateTimeConstants.CE; // private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("EE"); // private static final int MIN_YEAR = -292269337; // private static final int MAX_YEAR = 292272984; // private static final Map<DateTimeZone, EthiopicChronology[]> cCache = new HashMap<DateTimeZone, EthiopicChronology[]>(); // private static final EthiopicChronology INSTANCE_UTC; // // public static EthiopicChronology getInstanceUTC(); // public static EthiopicChronology getInstance(); // public static EthiopicChronology getInstance(DateTimeZone zone); // public static EthiopicChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek); // EthiopicChronology(Chronology base, Object param, int minDaysInFirstWeek); // private Object readResolve(); // public Chronology withUTC(); // public Chronology withZone(DateTimeZone zone); // long calculateFirstDayOfYearMillis(int year); // int getMinYear(); // int getMaxYear(); // long getApproxMillisAtEpochDividedByTwo(); // protected void assemble(Fields fields); // } // // // Abstract Java Test Class // package org.joda.time.chrono; // // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.joda.time.Chronology; // import org.joda.time.DateTime; // import org.joda.time.DateTimeConstants; // import org.joda.time.DateTimeField; // import org.joda.time.DateTimeUtils; // import org.joda.time.DateTimeZone; // import org.joda.time.DurationField; // import org.joda.time.DurationFieldType; // import org.joda.time.DateTime.Property; // // // // public class TestEthiopicChronology extends TestCase { // private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; // private static long SKIP = 1 * MILLIS_PER_DAY; // private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); // private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); // private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); // private static final Chronology ETHIOPIC_UTC = EthiopicChronology.getInstanceUTC(); // private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); // private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); // long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + // 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + // 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + // 366 + 365; // private long TEST_TIME_NOW = // (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; // private DateTimeZone originalDateTimeZone = null; // private TimeZone originalTimeZone = null; // private Locale originalLocale = null; // // public static void main(String[] args); // public static TestSuite suite(); // public TestEthiopicChronology(String name); // protected void setUp() throws Exception; // protected void tearDown() throws Exception; // public void testFactoryUTC(); // public void testFactory(); // public void testFactory_Zone(); // public void testEquality(); // public void testWithUTC(); // public void testWithZone(); // public void testToString(); // public void testDurationFields(); // public void testDateFields(); // public void testTimeFields(); // public void testEpoch(); // public void testEra(); // public void testCalendar(); // public void testSampleDate(); // public void testSampleDateWithZone(); // public void testDurationYear(); // public void testDurationMonth(); // } // You are a professional Java test case writer, please create a test case named `testCalendar` for the `EthiopicChronology` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */ //----------------------------------------------------------------------- public void testCalendar() {
/** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */ //-----------------------------------------------------------------------
1
org.joda.time.chrono.EthiopicChronology
src/test/java
```java // Abstract Java Tested Class package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.field.SkipDateTimeField; public final class EthiopicChronology extends BasicFixedMonthChronology { private static final long serialVersionUID = -5972804258688333942L; public static final int EE = DateTimeConstants.CE; private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("EE"); private static final int MIN_YEAR = -292269337; private static final int MAX_YEAR = 292272984; private static final Map<DateTimeZone, EthiopicChronology[]> cCache = new HashMap<DateTimeZone, EthiopicChronology[]>(); private static final EthiopicChronology INSTANCE_UTC; public static EthiopicChronology getInstanceUTC(); public static EthiopicChronology getInstance(); public static EthiopicChronology getInstance(DateTimeZone zone); public static EthiopicChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek); EthiopicChronology(Chronology base, Object param, int minDaysInFirstWeek); private Object readResolve(); public Chronology withUTC(); public Chronology withZone(DateTimeZone zone); long calculateFirstDayOfYearMillis(int year); int getMinYear(); int getMaxYear(); long getApproxMillisAtEpochDividedByTwo(); protected void assemble(Fields fields); } // Abstract Java Test Class package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.DateTime.Property; public class TestEthiopicChronology extends TestCase { private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; private static long SKIP = 1 * MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology ETHIOPIC_UTC = EthiopicChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args); public static TestSuite suite(); public TestEthiopicChronology(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testFactoryUTC(); public void testFactory(); public void testFactory_Zone(); public void testEquality(); public void testWithUTC(); public void testWithZone(); public void testToString(); public void testDurationFields(); public void testDateFields(); public void testTimeFields(); public void testEpoch(); public void testEra(); public void testCalendar(); public void testSampleDate(); public void testSampleDateWithZone(); public void testDurationYear(); public void testDurationMonth(); } ``` You are a professional Java test case writer, please create a test case named `testCalendar` for the `EthiopicChronology` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */ //----------------------------------------------------------------------- public void testCalendar() { ```
public final class EthiopicChronology extends BasicFixedMonthChronology
package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.DateTime.Property;
public static void main(String[] args); public static TestSuite suite(); public TestEthiopicChronology(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testFactoryUTC(); public void testFactory(); public void testFactory_Zone(); public void testEquality(); public void testWithUTC(); public void testWithZone(); public void testToString(); public void testDurationFields(); public void testDateFields(); public void testTimeFields(); public void testEpoch(); public void testEra(); public void testCalendar(); public void testSampleDate(); public void testSampleDateWithZone(); public void testDurationYear(); public void testDurationMonth();
f9c90521c068b3169bd618d79f0a920f5821da28474f5dff744164c48bd10228
[ "org.joda.time.chrono.TestEthiopicChronology::testCalendar" ]
private static final long serialVersionUID = -5972804258688333942L; public static final int EE = DateTimeConstants.CE; private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("EE"); private static final int MIN_YEAR = -292269337; private static final int MAX_YEAR = 292272984; private static final Map<DateTimeZone, EthiopicChronology[]> cCache = new HashMap<DateTimeZone, EthiopicChronology[]>(); private static final EthiopicChronology INSTANCE_UTC;
public void testCalendar()
private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; private static long SKIP = 1 * MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology ETHIOPIC_UTC = EthiopicChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null;
Time
/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.DateTime.Property; /** * This class is a Junit unit test for EthiopicChronology. * * @author Stephen Colebourne */ public class TestEthiopicChronology extends TestCase { private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; private static long SKIP = 1 * MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology ETHIOPIC_UTC = EthiopicChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { SKIP = 1 * MILLIS_PER_DAY; return new TestSuite(TestEthiopicChronology.class); } public TestEthiopicChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, EthiopicChronology.getInstanceUTC().getZone()); assertSame(EthiopicChronology.class, EthiopicChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, EthiopicChronology.getInstance().getZone()); assertSame(EthiopicChronology.class, EthiopicChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, EthiopicChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, EthiopicChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, EthiopicChronology.getInstance(null).getZone()); assertSame(EthiopicChronology.class, EthiopicChronology.getInstance(TOKYO).getClass()); } //----------------------------------------------------------------------- public void testEquality() { assertSame(EthiopicChronology.getInstance(TOKYO), EthiopicChronology.getInstance(TOKYO)); assertSame(EthiopicChronology.getInstance(LONDON), EthiopicChronology.getInstance(LONDON)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstance(PARIS)); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstanceUTC()); assertSame(EthiopicChronology.getInstance(), EthiopicChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstance(LONDON).withUTC()); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstance(TOKYO).withUTC()); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstanceUTC().withUTC()); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(EthiopicChronology.getInstance(TOKYO), EthiopicChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(EthiopicChronology.getInstance(LONDON), EthiopicChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(EthiopicChronology.getInstance(LONDON), EthiopicChronology.getInstance(TOKYO).withZone(null)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstance().withZone(PARIS)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("EthiopicChronology[Europe/London]", EthiopicChronology.getInstance(LONDON).toString()); assertEquals("EthiopicChronology[Asia/Tokyo]", EthiopicChronology.getInstance(TOKYO).toString()); assertEquals("EthiopicChronology[Europe/London]", EthiopicChronology.getInstance().toString()); assertEquals("EthiopicChronology[UTC]", EthiopicChronology.getInstanceUTC().toString()); } //----------------------------------------------------------------------- public void testDurationFields() { final EthiopicChronology ethiopic = EthiopicChronology.getInstance(); assertEquals("eras", ethiopic.eras().getName()); assertEquals("centuries", ethiopic.centuries().getName()); assertEquals("years", ethiopic.years().getName()); assertEquals("weekyears", ethiopic.weekyears().getName()); assertEquals("months", ethiopic.months().getName()); assertEquals("weeks", ethiopic.weeks().getName()); assertEquals("days", ethiopic.days().getName()); assertEquals("halfdays", ethiopic.halfdays().getName()); assertEquals("hours", ethiopic.hours().getName()); assertEquals("minutes", ethiopic.minutes().getName()); assertEquals("seconds", ethiopic.seconds().getName()); assertEquals("millis", ethiopic.millis().getName()); assertEquals(false, ethiopic.eras().isSupported()); assertEquals(true, ethiopic.centuries().isSupported()); assertEquals(true, ethiopic.years().isSupported()); assertEquals(true, ethiopic.weekyears().isSupported()); assertEquals(true, ethiopic.months().isSupported()); assertEquals(true, ethiopic.weeks().isSupported()); assertEquals(true, ethiopic.days().isSupported()); assertEquals(true, ethiopic.halfdays().isSupported()); assertEquals(true, ethiopic.hours().isSupported()); assertEquals(true, ethiopic.minutes().isSupported()); assertEquals(true, ethiopic.seconds().isSupported()); assertEquals(true, ethiopic.millis().isSupported()); assertEquals(false, ethiopic.centuries().isPrecise()); assertEquals(false, ethiopic.years().isPrecise()); assertEquals(false, ethiopic.weekyears().isPrecise()); assertEquals(false, ethiopic.months().isPrecise()); assertEquals(false, ethiopic.weeks().isPrecise()); assertEquals(false, ethiopic.days().isPrecise()); assertEquals(false, ethiopic.halfdays().isPrecise()); assertEquals(true, ethiopic.hours().isPrecise()); assertEquals(true, ethiopic.minutes().isPrecise()); assertEquals(true, ethiopic.seconds().isPrecise()); assertEquals(true, ethiopic.millis().isPrecise()); final EthiopicChronology ethiopicUTC = EthiopicChronology.getInstanceUTC(); assertEquals(false, ethiopicUTC.centuries().isPrecise()); assertEquals(false, ethiopicUTC.years().isPrecise()); assertEquals(false, ethiopicUTC.weekyears().isPrecise()); assertEquals(false, ethiopicUTC.months().isPrecise()); assertEquals(true, ethiopicUTC.weeks().isPrecise()); assertEquals(true, ethiopicUTC.days().isPrecise()); assertEquals(true, ethiopicUTC.halfdays().isPrecise()); assertEquals(true, ethiopicUTC.hours().isPrecise()); assertEquals(true, ethiopicUTC.minutes().isPrecise()); assertEquals(true, ethiopicUTC.seconds().isPrecise()); assertEquals(true, ethiopicUTC.millis().isPrecise()); final DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); final EthiopicChronology ethiopicGMT = EthiopicChronology.getInstance(gmt); assertEquals(false, ethiopicGMT.centuries().isPrecise()); assertEquals(false, ethiopicGMT.years().isPrecise()); assertEquals(false, ethiopicGMT.weekyears().isPrecise()); assertEquals(false, ethiopicGMT.months().isPrecise()); assertEquals(true, ethiopicGMT.weeks().isPrecise()); assertEquals(true, ethiopicGMT.days().isPrecise()); assertEquals(true, ethiopicGMT.halfdays().isPrecise()); assertEquals(true, ethiopicGMT.hours().isPrecise()); assertEquals(true, ethiopicGMT.minutes().isPrecise()); assertEquals(true, ethiopicGMT.seconds().isPrecise()); assertEquals(true, ethiopicGMT.millis().isPrecise()); } public void testDateFields() { final EthiopicChronology ethiopic = EthiopicChronology.getInstance(); assertEquals("era", ethiopic.era().getName()); assertEquals("centuryOfEra", ethiopic.centuryOfEra().getName()); assertEquals("yearOfCentury", ethiopic.yearOfCentury().getName()); assertEquals("yearOfEra", ethiopic.yearOfEra().getName()); assertEquals("year", ethiopic.year().getName()); assertEquals("monthOfYear", ethiopic.monthOfYear().getName()); assertEquals("weekyearOfCentury", ethiopic.weekyearOfCentury().getName()); assertEquals("weekyear", ethiopic.weekyear().getName()); assertEquals("weekOfWeekyear", ethiopic.weekOfWeekyear().getName()); assertEquals("dayOfYear", ethiopic.dayOfYear().getName()); assertEquals("dayOfMonth", ethiopic.dayOfMonth().getName()); assertEquals("dayOfWeek", ethiopic.dayOfWeek().getName()); assertEquals(true, ethiopic.era().isSupported()); assertEquals(true, ethiopic.centuryOfEra().isSupported()); assertEquals(true, ethiopic.yearOfCentury().isSupported()); assertEquals(true, ethiopic.yearOfEra().isSupported()); assertEquals(true, ethiopic.year().isSupported()); assertEquals(true, ethiopic.monthOfYear().isSupported()); assertEquals(true, ethiopic.weekyearOfCentury().isSupported()); assertEquals(true, ethiopic.weekyear().isSupported()); assertEquals(true, ethiopic.weekOfWeekyear().isSupported()); assertEquals(true, ethiopic.dayOfYear().isSupported()); assertEquals(true, ethiopic.dayOfMonth().isSupported()); assertEquals(true, ethiopic.dayOfWeek().isSupported()); assertEquals(ethiopic.eras(), ethiopic.era().getDurationField()); assertEquals(ethiopic.centuries(), ethiopic.centuryOfEra().getDurationField()); assertEquals(ethiopic.years(), ethiopic.yearOfCentury().getDurationField()); assertEquals(ethiopic.years(), ethiopic.yearOfEra().getDurationField()); assertEquals(ethiopic.years(), ethiopic.year().getDurationField()); assertEquals(ethiopic.months(), ethiopic.monthOfYear().getDurationField()); assertEquals(ethiopic.weekyears(), ethiopic.weekyearOfCentury().getDurationField()); assertEquals(ethiopic.weekyears(), ethiopic.weekyear().getDurationField()); assertEquals(ethiopic.weeks(), ethiopic.weekOfWeekyear().getDurationField()); assertEquals(ethiopic.days(), ethiopic.dayOfYear().getDurationField()); assertEquals(ethiopic.days(), ethiopic.dayOfMonth().getDurationField()); assertEquals(ethiopic.days(), ethiopic.dayOfWeek().getDurationField()); assertEquals(null, ethiopic.era().getRangeDurationField()); assertEquals(ethiopic.eras(), ethiopic.centuryOfEra().getRangeDurationField()); assertEquals(ethiopic.centuries(), ethiopic.yearOfCentury().getRangeDurationField()); assertEquals(ethiopic.eras(), ethiopic.yearOfEra().getRangeDurationField()); assertEquals(null, ethiopic.year().getRangeDurationField()); assertEquals(ethiopic.years(), ethiopic.monthOfYear().getRangeDurationField()); assertEquals(ethiopic.centuries(), ethiopic.weekyearOfCentury().getRangeDurationField()); assertEquals(null, ethiopic.weekyear().getRangeDurationField()); assertEquals(ethiopic.weekyears(), ethiopic.weekOfWeekyear().getRangeDurationField()); assertEquals(ethiopic.years(), ethiopic.dayOfYear().getRangeDurationField()); assertEquals(ethiopic.months(), ethiopic.dayOfMonth().getRangeDurationField()); assertEquals(ethiopic.weeks(), ethiopic.dayOfWeek().getRangeDurationField()); } public void testTimeFields() { final EthiopicChronology ethiopic = EthiopicChronology.getInstance(); assertEquals("halfdayOfDay", ethiopic.halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", ethiopic.clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", ethiopic.hourOfHalfday().getName()); assertEquals("clockhourOfDay", ethiopic.clockhourOfDay().getName()); assertEquals("hourOfDay", ethiopic.hourOfDay().getName()); assertEquals("minuteOfDay", ethiopic.minuteOfDay().getName()); assertEquals("minuteOfHour", ethiopic.minuteOfHour().getName()); assertEquals("secondOfDay", ethiopic.secondOfDay().getName()); assertEquals("secondOfMinute", ethiopic.secondOfMinute().getName()); assertEquals("millisOfDay", ethiopic.millisOfDay().getName()); assertEquals("millisOfSecond", ethiopic.millisOfSecond().getName()); assertEquals(true, ethiopic.halfdayOfDay().isSupported()); assertEquals(true, ethiopic.clockhourOfHalfday().isSupported()); assertEquals(true, ethiopic.hourOfHalfday().isSupported()); assertEquals(true, ethiopic.clockhourOfDay().isSupported()); assertEquals(true, ethiopic.hourOfDay().isSupported()); assertEquals(true, ethiopic.minuteOfDay().isSupported()); assertEquals(true, ethiopic.minuteOfHour().isSupported()); assertEquals(true, ethiopic.secondOfDay().isSupported()); assertEquals(true, ethiopic.secondOfMinute().isSupported()); assertEquals(true, ethiopic.millisOfDay().isSupported()); assertEquals(true, ethiopic.millisOfSecond().isSupported()); } //----------------------------------------------------------------------- public void testEpoch() { DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, ETHIOPIC_UTC); assertEquals(new DateTime(8, 8, 29, 0, 0, 0, 0, JULIAN_UTC), epoch.withChronology(JULIAN_UTC)); } public void testEra() { assertEquals(1, EthiopicChronology.EE); try { new DateTime(-1, 13, 5, 0, 0, 0, 0, ETHIOPIC_UTC); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */ public void testCalendar() { if (TestAll.FAST) { return; } System.out.println("\nTestEthiopicChronology.testCalendar"); DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, ETHIOPIC_UTC); long millis = epoch.getMillis(); long end = new DateTime(3000, 1, 1, 0, 0, 0, 0, ISO_UTC).getMillis(); DateTimeField dayOfWeek = ETHIOPIC_UTC.dayOfWeek(); DateTimeField dayOfYear = ETHIOPIC_UTC.dayOfYear(); DateTimeField dayOfMonth = ETHIOPIC_UTC.dayOfMonth(); DateTimeField monthOfYear = ETHIOPIC_UTC.monthOfYear(); DateTimeField year = ETHIOPIC_UTC.year(); DateTimeField yearOfEra = ETHIOPIC_UTC.yearOfEra(); DateTimeField era = ETHIOPIC_UTC.era(); int expectedDOW = new DateTime(8, 8, 29, 0, 0, 0, 0, JULIAN_UTC).getDayOfWeek(); int expectedDOY = 1; int expectedDay = 1; int expectedMonth = 1; int expectedYear = 1; while (millis < end) { int dowValue = dayOfWeek.get(millis); int doyValue = dayOfYear.get(millis); int dayValue = dayOfMonth.get(millis); int monthValue = monthOfYear.get(millis); int yearValue = year.get(millis); int yearOfEraValue = yearOfEra.get(millis); int monthLen = dayOfMonth.getMaximumValue(millis); if (monthValue < 1 || monthValue > 13) { fail("Bad month: " + millis); } // test era assertEquals(1, era.get(millis)); assertEquals("EE", era.getAsText(millis)); assertEquals("EE", era.getAsShortText(millis)); // test date assertEquals(expectedYear, yearValue); assertEquals(expectedYear, yearOfEraValue); assertEquals(expectedMonth, monthValue); assertEquals(expectedDay, dayValue); assertEquals(expectedDOW, dowValue); assertEquals(expectedDOY, doyValue); // test leap year assertEquals(yearValue % 4 == 3, year.isLeap(millis)); // test month length if (monthValue == 13) { assertEquals(yearValue % 4 == 3, monthOfYear.isLeap(millis)); if (yearValue % 4 == 3) { assertEquals(6, monthLen); } else { assertEquals(5, monthLen); } } else { assertEquals(30, monthLen); } // recalculate date expectedDOW = (((expectedDOW + 1) - 1) % 7) + 1; expectedDay++; expectedDOY++; if (expectedDay == 31 && expectedMonth < 13) { expectedDay = 1; expectedMonth++; } else if (expectedMonth == 13) { if (expectedYear % 4 == 3 && expectedDay == 7) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } else if (expectedYear % 4 != 3 && expectedDay == 6) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } } millis += SKIP; } } public void testSampleDate() { DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, ISO_UTC).withChronology(ETHIOPIC_UTC); assertEquals(EthiopicChronology.EE, dt.getEra()); assertEquals(20, dt.getCenturyOfEra()); // TODO confirm assertEquals(96, dt.getYearOfCentury()); assertEquals(1996, dt.getYearOfEra()); assertEquals(1996, dt.getYear()); Property fld = dt.year(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(new DateTime(1997, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(10, dt.getMonthOfYear()); fld = dt.monthOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(13, fld.getMaximumValue()); assertEquals(13, fld.getMaximumValueOverall()); assertEquals(new DateTime(1997, 1, 2, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(4)); assertEquals(new DateTime(1996, 1, 2, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addWrapFieldToCopy(4)); assertEquals(2, dt.getDayOfMonth()); fld = dt.dayOfMonth(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(30, fld.getMaximumValue()); assertEquals(30, fld.getMaximumValueOverall()); assertEquals(new DateTime(1996, 10, 3, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(DateTimeConstants.WEDNESDAY, dt.getDayOfWeek()); fld = dt.dayOfWeek(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(7, fld.getMaximumValue()); assertEquals(7, fld.getMaximumValueOverall()); assertEquals(new DateTime(1996, 10, 3, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(9 * 30 + 2, dt.getDayOfYear()); fld = dt.dayOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(365, fld.getMaximumValue()); assertEquals(366, fld.getMaximumValueOverall()); assertEquals(new DateTime(1996, 10, 3, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(0, dt.getHourOfDay()); assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testSampleDateWithZone() { DateTime dt = new DateTime(2004, 6, 9, 12, 0, 0, 0, PARIS).withChronology(ETHIOPIC_UTC); assertEquals(EthiopicChronology.EE, dt.getEra()); assertEquals(1996, dt.getYear()); assertEquals(1996, dt.getYearOfEra()); assertEquals(10, dt.getMonthOfYear()); assertEquals(2, dt.getDayOfMonth()); assertEquals(10, dt.getHourOfDay()); // PARIS is UTC+2 in summer (12-2=10) assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testDurationYear() { // Leap 1999, NotLeap 1996,97,98 DateTime dt96 = new DateTime(1996, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt97 = new DateTime(1997, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt98 = new DateTime(1998, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt99 = new DateTime(1999, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt00 = new DateTime(2000, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DurationField fld = dt96.year().getDurationField(); assertEquals(ETHIOPIC_UTC.years(), fld); assertEquals(1L * 365L * MILLIS_PER_DAY, fld.getMillis(1, dt96.getMillis())); assertEquals(2L * 365L * MILLIS_PER_DAY, fld.getMillis(2, dt96.getMillis())); assertEquals(3L * 365L * MILLIS_PER_DAY, fld.getMillis(3, dt96.getMillis())); assertEquals((4L * 365L + 1L) * MILLIS_PER_DAY, fld.getMillis(4, dt96.getMillis())); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getMillis(1)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 2, fld.getMillis(2)); assertEquals(1L * 365L * MILLIS_PER_DAY, fld.getMillis(1L, dt96.getMillis())); assertEquals(2L * 365L * MILLIS_PER_DAY, fld.getMillis(2L, dt96.getMillis())); assertEquals(3L * 365L * MILLIS_PER_DAY, fld.getMillis(3L, dt96.getMillis())); assertEquals((4L * 365L + 1L) * MILLIS_PER_DAY, fld.getMillis(4L, dt96.getMillis())); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getMillis(1L)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 2, fld.getMillis(2L)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getUnitMillis()); assertEquals(0, fld.getValue(1L * 365L * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(1, fld.getValue(1L * 365L * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(1, fld.getValue(1L * 365L * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(1, fld.getValue(2L * 365L * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(2, fld.getValue(2L * 365L * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(2, fld.getValue(2L * 365L * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(2, fld.getValue(3L * 365L * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(3, fld.getValue(3L * 365L * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(3, fld.getValue(3L * 365L * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(3, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(4, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(4, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(dt97.getMillis(), fld.add(dt96.getMillis(), 1)); assertEquals(dt98.getMillis(), fld.add(dt96.getMillis(), 2)); assertEquals(dt99.getMillis(), fld.add(dt96.getMillis(), 3)); assertEquals(dt00.getMillis(), fld.add(dt96.getMillis(), 4)); assertEquals(dt97.getMillis(), fld.add(dt96.getMillis(), 1L)); assertEquals(dt98.getMillis(), fld.add(dt96.getMillis(), 2L)); assertEquals(dt99.getMillis(), fld.add(dt96.getMillis(), 3L)); assertEquals(dt00.getMillis(), fld.add(dt96.getMillis(), 4L)); } public void testDurationMonth() { // Leap 1999, NotLeap 1996,97,98 DateTime dt11 = new DateTime(1999, 11, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt12 = new DateTime(1999, 12, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt13 = new DateTime(1999, 13, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt01 = new DateTime(2000, 1, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DurationField fld = dt11.monthOfYear().getDurationField(); assertEquals(ETHIOPIC_UTC.months(), fld); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1, dt11.getMillis())); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2, dt11.getMillis())); assertEquals((2L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(3, dt11.getMillis())); assertEquals((3L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(4, dt11.getMillis())); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1)); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2)); assertEquals(13L * 30L * MILLIS_PER_DAY, fld.getMillis(13)); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1L, dt11.getMillis())); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2L, dt11.getMillis())); assertEquals((2L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(3L, dt11.getMillis())); assertEquals((3L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(4L, dt11.getMillis())); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1L)); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2L)); assertEquals(13L * 30L * MILLIS_PER_DAY, fld.getMillis(13L)); assertEquals(0, fld.getValue(1L * 30L * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(1, fld.getValue(1L * 30L * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(1, fld.getValue(1L * 30L * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(1, fld.getValue(2L * 30L * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(2, fld.getValue(2L * 30L * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(2, fld.getValue(2L * 30L * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(2, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(3, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(3, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(3, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(4, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(4, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(dt12.getMillis(), fld.add(dt11.getMillis(), 1)); assertEquals(dt13.getMillis(), fld.add(dt11.getMillis(), 2)); assertEquals(dt01.getMillis(), fld.add(dt11.getMillis(), 3)); assertEquals(dt12.getMillis(), fld.add(dt11.getMillis(), 1L)); assertEquals(dt13.getMillis(), fld.add(dt11.getMillis(), 2L)); assertEquals(dt01.getMillis(), fld.add(dt11.getMillis(), 3L)); } }
[ { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "assemble", "be_test_function_signature": "(Lorg/joda/time/chrono/AssembledChronology$Fields;)V", "line_numbers": [ "246", "247", "250", "251", "253", "254", "255", "257" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "calculateFirstDayOfYearMillis", "be_test_function_signature": "(I)J", "line_numbers": [ "207", "209", "212", "214", "216", "217", "221", "226" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "getApproxMillisAtEpochDividedByTwo", "be_test_function_signature": "()J", "line_numbers": [ "241" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "getInstance", "be_test_function_signature": "(Lorg/joda/time/DateTimeZone;)Lorg/joda/time/chrono/EthiopicChronology;", "line_numbers": [ "108" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "getInstance", "be_test_function_signature": "(Lorg/joda/time/DateTimeZone;I)Lorg/joda/time/chrono/EthiopicChronology;", "line_numbers": [ "119", "120", "123", "124", "125", "126", "127", "130", "131", "132", "134", "135", "136", "138", "140", "141", "144", "145", "146", "149", "151", "152" ], "method_line_rate": 0.7727272727272727 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "getInstanceUTC", "be_test_function_signature": "()Lorg/joda/time/chrono/EthiopicChronology;", "line_numbers": [ "89" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "getMaxYear", "be_test_function_signature": "()I", "line_numbers": [ "236" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "getMinYear", "be_test_function_signature": "()I", "line_numbers": [ "231" ], "method_line_rate": 1 }, { "be_test_class_file": "org/joda/time/chrono/EthiopicChronology.java", "be_test_class_name": "org.joda.time.chrono.EthiopicChronology", "be_test_function_name": "getZone", "be_test_function_signature": "()Lorg/joda/time/DateTimeZone;", "line_numbers": [ "51" ], "method_line_rate": 1 } ]
public class FunctionInjectorTest extends TestCase
public void testInlineReferenceInExpression11() { // Call under label helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {a:foo(1)?0:1 }", "function foo(a){return true;}; " + "function x() {" + " a:{" + " var JSCompiler_inline_result$$0; " + " {JSCompiler_inline_result$$0=true;}" + " JSCompiler_inline_result$$0?0:1 " + " }" + "}", "foo", INLINE_BLOCK, true); }
// CanInlineResult.YES; // // @Override // protected void setUp() throws Exception; // private FunctionInjector getInjector(); // public void testIsSimpleFunction1(); // public void testIsSimpleFunction2(); // public void testIsSimpleFunction3(); // public void testIsSimpleFunction4(); // public void testIsSimpleFunction5(); // public void testIsSimpleFunction6(); // public void testIsSimpleFunction7(); // public void testCanInlineReferenceToFunction1(); // public void testCanInlineReferenceToFunction2(); // public void testCanInlineReferenceToFunction3(); // public void testCanInlineReferenceToFunction4(); // public void testCanInlineReferenceToFunction5(); // public void testCanInlineReferenceToFunction6(); // public void testCanInlineReferenceToFunction7(); // public void testCanInlineReferenceToFunction8(); // public void testCanInlineReferenceToFunction9(); // public void testCanInlineReferenceToFunction10(); // public void testCanInlineReferenceToFunction11(); // public void testCanInlineReferenceToFunction12(); // public void testCanInlineReferenceToFunction12b(); // public void testCanInlineReferenceToFunction14(); // public void testCanInlineReferenceToFunction15(); // public void testCanInlineReferenceToFunction16(); // public void testCanInlineReferenceToFunction17(); // public void testCanInlineReferenceToFunction18(); // public void testCanInlineReferenceToFunction19(); // public void testCanInlineReferenceToFunction20(); // public void testCanInlineReferenceToFunction21(); // public void testCanInlineReferenceToFunction22(); // public void testCanInlineReferenceToFunction23(); // public void testCanInlineReferenceToFunction24(); // public void testCanInlineReferenceToFunction25(); // public void testCanInlineReferenceToFunction26(); // public void testCanInlineReferenceToFunction27(); // public void testCanInlineReferenceToFunction28(); // public void testCanInlineReferenceToFunction29(); // public void testCanInlineReferenceToFunction30(); // public void testCanInlineReferenceToFunction31(); // public void testCanInlineReferenceToFunction32(); // public void testCanInlineReferenceToFunction33(); // public void testCanInlineReferenceToFunction34(); // public void testCanInlineReferenceToFunction35(); // public void testCanInlineReferenceToFunction36(); // public void testCanInlineReferenceToFunction37(); // public void testCanInlineReferenceToFunction38(); // public void testCanInlineReferenceToFunction39(); // public void testCanInlineReferenceToFunction40(); // public void testCanInlineReferenceToFunction41(); // public void testCanInlineReferenceToFunction42(); // public void testCanInlineReferenceToFunction43(); // public void testCanInlineReferenceToFunction44(); // public void testCanInlineReferenceToFunction45(); // public void testCanInlineReferenceToFunction46(); // public void testCanInlineReferenceToFunction47(); // public void testCanInlineReferenceToFunction48(); // public void testCanInlineReferenceToFunction49(); // public void testCanInlineReferenceToFunction50(); // public void testCanInlineReferenceToFunction51(); // public void testCanInlineReferenceToFunctionInExpression1(); // public void testCanInlineReferenceToFunctionInExpression2(); // public void testCanInlineReferenceToFunctionInExpression3(); // public void testCanInlineReferenceToFunctionInExpression4(); // public void testCanInlineReferenceToFunctionInExpression5(); // public void testCanInlineReferenceToFunctionInExpression5a(); // public void testCanInlineReferenceToFunctionInExpression6(); // public void testCanInlineReferenceToFunctionInExpression7(); // public void testCanInlineReferenceToFunctionInExpression7a(); // public void testCanInlineReferenceToFunctionInExpression8(); // public void testCanInlineReferenceToFunctionInExpression9(); // public void testCanInlineReferenceToFunctionInExpression10(); // public void testCanInlineReferenceToFunctionInExpression10a(); // public void testCanInlineReferenceToFunctionInExpression12(); // public void testCanInlineReferenceToFunctionInExpression13(); // public void testCanInlineReferenceToFunctionInExpression14(); // public void testCanInlineReferenceToFunctionInExpression14a(); // public void testCanInlineReferenceToFunctionInExpression18(); // public void testCanInlineReferenceToFunctionInExpression19(); // public void testCanInlineReferenceToFunctionInExpression19a(); // public void testCanInlineReferenceToFunctionInExpression21(); // public void testCanInlineReferenceToFunctionInExpression21a(); // public void testCanInlineReferenceToFunctionInExpression22(); // public void testCanInlineReferenceToFunctionInExpression22a(); // public void testCanInlineReferenceToFunctionInExpression23(); // public void testCanInlineReferenceToFunctionInExpression23a(); // public void testCanInlineReferenceToFunctionInLoop1(); // public void testCanInlineReferenceToFunctionInLoop2(); // public void testInline1(); // public void testInline2(); // public void testInline3(); // public void testInline4(); // public void testInline5(); // public void testInline6(); // public void testInline7(); // public void testInline8(); // public void testInline9(); // public void testInline10(); // public void testInline11(); // public void testInline12(); // public void testInline13(); // public void testInline14(); // public void testInline15(); // public void testInline16(); // public void testInline17(); // public void testInline18(); // public void testInline19(); // public void testInline19b(); // public void testInlineIntoLoop(); // public void testInlineFunctionWithInnerFunction1(); // public void testInlineFunctionWithInnerFunction2(); // public void testInlineFunctionWithInnerFunction3(); // public void testInlineFunctionWithInnerFunction4(); // public void testInlineFunctionWithInnerFunction5(); // public void testInlineReferenceInExpression1(); // public void testInlineReferenceInExpression2(); // public void testInlineReferenceInExpression3(); // public void testInlineReferenceInExpression4(); // public void testInlineReferenceInExpression5(); // public void testInlineReferenceInExpression6(); // public void testInlineReferenceInExpression7(); // public void testInlineReferenceInExpression8(); // public void testInlineReferenceInExpression9(); // public void testInlineReferenceInExpression11(); // public void testInlineReferenceInExpression12(); // public void testInlineReferenceInExpression13(); // public void testInlineReferenceInExpression14(); // public void testInlineReferenceInExpression15(); // public void testInlineReferenceInExpression16(); // public void testInlineReferenceInExpression17(); // public void testInlineWithinCalls1(); // public void testInlineAssignmentToConstant(); // public void testBug1897706(); // public void testIssue1101a(); // public void testIssue1101b(); // public void helperCanInlineReferenceToFunction( // final CanInlineResult expectedResult, // final String code, // final String fnName, // final InliningMode mode); // public void helperCanInlineReferenceToFunction( // final CanInlineResult expectedResult, // final String code, // final String fnName, // final InliningMode mode, // boolean allowDecomposition); // public void helperInlineReferenceToFunction( // String code, final String expectedResult, // final String fnName, final InliningMode mode); // private void validateSourceInfo(Compiler compiler, Node subtree); // public void helperInlineReferenceToFunction( // String code, final String expectedResult, // final String fnName, final InliningMode mode, // final boolean decompose); // private static Node findFunction(Node n, String name); // private static Node prep(String js); // private static Node parse(Compiler compiler, String js); // private static Node parseExpected(Compiler compiler, String js); // private static String toSource(Node n); // TestCallback(String callname, Method method); // @Override // public boolean shouldTraverse( // NodeTraversal nodeTraversal, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public boolean call(NodeTraversal t, Node n, Node parent); // @Override // public boolean call(NodeTraversal t, Node n, Node parent); // } // You are a professional Java test case writer, please create a test case named `testInlineReferenceInExpression11` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. // } // "foo", INLINE_BLOCK); // "b += 1 + JSCompiler_inline_result$$0 }", // "JSCompiler_inline_result$$0=true;}" + // "{var JSCompiler_inline_result$$0; " + // "function x() {var b;" + // "function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "/** @nosideeffects */ function foo(a){return true;}; " +
test/com/google/javascript/jscomp/FunctionInjectorTest.java
package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.collect.Sets; import com.google.javascript.jscomp.ExpressionDecomposer.DecompositionType; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Collection; import java.util.Map; import java.util.Set;
public FunctionInjector( AbstractCompiler compiler, Supplier<String> safeNameIdSupplier, boolean allowDecomposition, boolean assumeStrictThis, boolean assumeMinimumCapture); boolean doesFunctionMeetMinimumRequirements( final String fnName, Node fnNode); CanInlineResult canInlineReferenceToFunction(NodeTraversal t, Node callNode, Node fnNode, Set<String> needAliases, InliningMode mode, boolean referencesThis, boolean containsFunctions); private boolean isSupportedCallType(Node callNode); Node inline( Node callNode, String fnName, Node fnNode, InliningMode mode); private Node inlineReturnValue(Node callNode, Node fnNode); private CallSiteType classifyCallSite(Node callNode); private ExpressionDecomposer getDecomposer(); void maybePrepareCall(Node callNode); private Node inlineFunction( Node callNode, Node fnNode, String fnName); boolean isDirectCallNodeReplacementPossible(Node fnNode); private CanInlineResult canInlineReferenceAsStatementBlock( NodeTraversal t, Node callNode, Node fnNode, Set<String> namesToAlias); private boolean callMeetsBlockInliningRequirements( NodeTraversal t, Node callNode, final Node fnNode, Set<String> namesToAlias); private CanInlineResult canInlineReferenceDirectly( Node callNode, Node fnNode, Set<String> namesToAlias); boolean inliningLowersCost( JSModule fnModule, Node fnNode, Collection<? extends Reference> refs, Set<String> namesToAlias, boolean isRemovable, boolean referencesThis); private boolean doesLowerCost( Node fnNode, int callCost, int directInlines, int costDeltaDirect, int blockInlines, int costDeltaBlock, boolean removable); private static int estimateCallCost(Node fnNode, boolean referencesThis); private static int inlineCostDelta( Node fnNode, Set<String> namesToAlias, InliningMode mode); public void setKnownConstants(Set<String> knownConstants); Reference(Node callNode, JSModule module, InliningMode mode); @Override public String get(); @Override public void prepare(FunctionInjector injector, Node callNode); @Override public void prepare(FunctionInjector injector, Node callNode); @Override public void prepare(FunctionInjector injector, Node callNode); @Override public void prepare(FunctionInjector injector, Node callNode); @Override public void prepare(FunctionInjector injector, Node callNode); @Override public void prepare(FunctionInjector injector, Node callNode); @Override public boolean apply(Node n); @Override public boolean apply(Node n);
1,170
testInlineReferenceInExpression11
```java CanInlineResult.YES; @Override protected void setUp() throws Exception; private FunctionInjector getInjector(); public void testIsSimpleFunction1(); public void testIsSimpleFunction2(); public void testIsSimpleFunction3(); public void testIsSimpleFunction4(); public void testIsSimpleFunction5(); public void testIsSimpleFunction6(); public void testIsSimpleFunction7(); public void testCanInlineReferenceToFunction1(); public void testCanInlineReferenceToFunction2(); public void testCanInlineReferenceToFunction3(); public void testCanInlineReferenceToFunction4(); public void testCanInlineReferenceToFunction5(); public void testCanInlineReferenceToFunction6(); public void testCanInlineReferenceToFunction7(); public void testCanInlineReferenceToFunction8(); public void testCanInlineReferenceToFunction9(); public void testCanInlineReferenceToFunction10(); public void testCanInlineReferenceToFunction11(); public void testCanInlineReferenceToFunction12(); public void testCanInlineReferenceToFunction12b(); public void testCanInlineReferenceToFunction14(); public void testCanInlineReferenceToFunction15(); public void testCanInlineReferenceToFunction16(); public void testCanInlineReferenceToFunction17(); public void testCanInlineReferenceToFunction18(); public void testCanInlineReferenceToFunction19(); public void testCanInlineReferenceToFunction20(); public void testCanInlineReferenceToFunction21(); public void testCanInlineReferenceToFunction22(); public void testCanInlineReferenceToFunction23(); public void testCanInlineReferenceToFunction24(); public void testCanInlineReferenceToFunction25(); public void testCanInlineReferenceToFunction26(); public void testCanInlineReferenceToFunction27(); public void testCanInlineReferenceToFunction28(); public void testCanInlineReferenceToFunction29(); public void testCanInlineReferenceToFunction30(); public void testCanInlineReferenceToFunction31(); public void testCanInlineReferenceToFunction32(); public void testCanInlineReferenceToFunction33(); public void testCanInlineReferenceToFunction34(); public void testCanInlineReferenceToFunction35(); public void testCanInlineReferenceToFunction36(); public void testCanInlineReferenceToFunction37(); public void testCanInlineReferenceToFunction38(); public void testCanInlineReferenceToFunction39(); public void testCanInlineReferenceToFunction40(); public void testCanInlineReferenceToFunction41(); public void testCanInlineReferenceToFunction42(); public void testCanInlineReferenceToFunction43(); public void testCanInlineReferenceToFunction44(); public void testCanInlineReferenceToFunction45(); public void testCanInlineReferenceToFunction46(); public void testCanInlineReferenceToFunction47(); public void testCanInlineReferenceToFunction48(); public void testCanInlineReferenceToFunction49(); public void testCanInlineReferenceToFunction50(); public void testCanInlineReferenceToFunction51(); public void testCanInlineReferenceToFunctionInExpression1(); public void testCanInlineReferenceToFunctionInExpression2(); public void testCanInlineReferenceToFunctionInExpression3(); public void testCanInlineReferenceToFunctionInExpression4(); public void testCanInlineReferenceToFunctionInExpression5(); public void testCanInlineReferenceToFunctionInExpression5a(); public void testCanInlineReferenceToFunctionInExpression6(); public void testCanInlineReferenceToFunctionInExpression7(); public void testCanInlineReferenceToFunctionInExpression7a(); public void testCanInlineReferenceToFunctionInExpression8(); public void testCanInlineReferenceToFunctionInExpression9(); public void testCanInlineReferenceToFunctionInExpression10(); public void testCanInlineReferenceToFunctionInExpression10a(); public void testCanInlineReferenceToFunctionInExpression12(); public void testCanInlineReferenceToFunctionInExpression13(); public void testCanInlineReferenceToFunctionInExpression14(); public void testCanInlineReferenceToFunctionInExpression14a(); public void testCanInlineReferenceToFunctionInExpression18(); public void testCanInlineReferenceToFunctionInExpression19(); public void testCanInlineReferenceToFunctionInExpression19a(); public void testCanInlineReferenceToFunctionInExpression21(); public void testCanInlineReferenceToFunctionInExpression21a(); public void testCanInlineReferenceToFunctionInExpression22(); public void testCanInlineReferenceToFunctionInExpression22a(); public void testCanInlineReferenceToFunctionInExpression23(); public void testCanInlineReferenceToFunctionInExpression23a(); public void testCanInlineReferenceToFunctionInLoop1(); public void testCanInlineReferenceToFunctionInLoop2(); public void testInline1(); public void testInline2(); public void testInline3(); public void testInline4(); public void testInline5(); public void testInline6(); public void testInline7(); public void testInline8(); public void testInline9(); public void testInline10(); public void testInline11(); public void testInline12(); public void testInline13(); public void testInline14(); public void testInline15(); public void testInline16(); public void testInline17(); public void testInline18(); public void testInline19(); public void testInline19b(); public void testInlineIntoLoop(); public void testInlineFunctionWithInnerFunction1(); public void testInlineFunctionWithInnerFunction2(); public void testInlineFunctionWithInnerFunction3(); public void testInlineFunctionWithInnerFunction4(); public void testInlineFunctionWithInnerFunction5(); public void testInlineReferenceInExpression1(); public void testInlineReferenceInExpression2(); public void testInlineReferenceInExpression3(); public void testInlineReferenceInExpression4(); public void testInlineReferenceInExpression5(); public void testInlineReferenceInExpression6(); public void testInlineReferenceInExpression7(); public void testInlineReferenceInExpression8(); public void testInlineReferenceInExpression9(); public void testInlineReferenceInExpression11(); public void testInlineReferenceInExpression12(); public void testInlineReferenceInExpression13(); public void testInlineReferenceInExpression14(); public void testInlineReferenceInExpression15(); public void testInlineReferenceInExpression16(); public void testInlineReferenceInExpression17(); public void testInlineWithinCalls1(); public void testInlineAssignmentToConstant(); public void testBug1897706(); public void testIssue1101a(); public void testIssue1101b(); public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode); public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode, boolean allowDecomposition); public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode); private void validateSourceInfo(Compiler compiler, Node subtree); public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode, final boolean decompose); private static Node findFunction(Node n, String name); private static Node prep(String js); private static Node parse(Compiler compiler, String js); private static Node parseExpected(Compiler compiler, String js); private static String toSource(Node n); TestCallback(String callname, Method method); @Override public boolean shouldTraverse( NodeTraversal nodeTraversal, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public boolean call(NodeTraversal t, Node n, Node parent); @Override public boolean call(NodeTraversal t, Node n, Node parent); } ``` You are a professional Java test case writer, please create a test case named `testInlineReferenceInExpression11` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java // } // "foo", INLINE_BLOCK); // "b += 1 + JSCompiler_inline_result$$0 }", // "JSCompiler_inline_result$$0=true;}" + // "{var JSCompiler_inline_result$$0; " + // "function x() {var b;" + // "function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "/** @nosideeffects */ function foo(a){return true;}; " +
1,156
// CanInlineResult.YES; // // @Override // protected void setUp() throws Exception; // private FunctionInjector getInjector(); // public void testIsSimpleFunction1(); // public void testIsSimpleFunction2(); // public void testIsSimpleFunction3(); // public void testIsSimpleFunction4(); // public void testIsSimpleFunction5(); // public void testIsSimpleFunction6(); // public void testIsSimpleFunction7(); // public void testCanInlineReferenceToFunction1(); // public void testCanInlineReferenceToFunction2(); // public void testCanInlineReferenceToFunction3(); // public void testCanInlineReferenceToFunction4(); // public void testCanInlineReferenceToFunction5(); // public void testCanInlineReferenceToFunction6(); // public void testCanInlineReferenceToFunction7(); // public void testCanInlineReferenceToFunction8(); // public void testCanInlineReferenceToFunction9(); // public void testCanInlineReferenceToFunction10(); // public void testCanInlineReferenceToFunction11(); // public void testCanInlineReferenceToFunction12(); // public void testCanInlineReferenceToFunction12b(); // public void testCanInlineReferenceToFunction14(); // public void testCanInlineReferenceToFunction15(); // public void testCanInlineReferenceToFunction16(); // public void testCanInlineReferenceToFunction17(); // public void testCanInlineReferenceToFunction18(); // public void testCanInlineReferenceToFunction19(); // public void testCanInlineReferenceToFunction20(); // public void testCanInlineReferenceToFunction21(); // public void testCanInlineReferenceToFunction22(); // public void testCanInlineReferenceToFunction23(); // public void testCanInlineReferenceToFunction24(); // public void testCanInlineReferenceToFunction25(); // public void testCanInlineReferenceToFunction26(); // public void testCanInlineReferenceToFunction27(); // public void testCanInlineReferenceToFunction28(); // public void testCanInlineReferenceToFunction29(); // public void testCanInlineReferenceToFunction30(); // public void testCanInlineReferenceToFunction31(); // public void testCanInlineReferenceToFunction32(); // public void testCanInlineReferenceToFunction33(); // public void testCanInlineReferenceToFunction34(); // public void testCanInlineReferenceToFunction35(); // public void testCanInlineReferenceToFunction36(); // public void testCanInlineReferenceToFunction37(); // public void testCanInlineReferenceToFunction38(); // public void testCanInlineReferenceToFunction39(); // public void testCanInlineReferenceToFunction40(); // public void testCanInlineReferenceToFunction41(); // public void testCanInlineReferenceToFunction42(); // public void testCanInlineReferenceToFunction43(); // public void testCanInlineReferenceToFunction44(); // public void testCanInlineReferenceToFunction45(); // public void testCanInlineReferenceToFunction46(); // public void testCanInlineReferenceToFunction47(); // public void testCanInlineReferenceToFunction48(); // public void testCanInlineReferenceToFunction49(); // public void testCanInlineReferenceToFunction50(); // public void testCanInlineReferenceToFunction51(); // public void testCanInlineReferenceToFunctionInExpression1(); // public void testCanInlineReferenceToFunctionInExpression2(); // public void testCanInlineReferenceToFunctionInExpression3(); // public void testCanInlineReferenceToFunctionInExpression4(); // public void testCanInlineReferenceToFunctionInExpression5(); // public void testCanInlineReferenceToFunctionInExpression5a(); // public void testCanInlineReferenceToFunctionInExpression6(); // public void testCanInlineReferenceToFunctionInExpression7(); // public void testCanInlineReferenceToFunctionInExpression7a(); // public void testCanInlineReferenceToFunctionInExpression8(); // public void testCanInlineReferenceToFunctionInExpression9(); // public void testCanInlineReferenceToFunctionInExpression10(); // public void testCanInlineReferenceToFunctionInExpression10a(); // public void testCanInlineReferenceToFunctionInExpression12(); // public void testCanInlineReferenceToFunctionInExpression13(); // public void testCanInlineReferenceToFunctionInExpression14(); // public void testCanInlineReferenceToFunctionInExpression14a(); // public void testCanInlineReferenceToFunctionInExpression18(); // public void testCanInlineReferenceToFunctionInExpression19(); // public void testCanInlineReferenceToFunctionInExpression19a(); // public void testCanInlineReferenceToFunctionInExpression21(); // public void testCanInlineReferenceToFunctionInExpression21a(); // public void testCanInlineReferenceToFunctionInExpression22(); // public void testCanInlineReferenceToFunctionInExpression22a(); // public void testCanInlineReferenceToFunctionInExpression23(); // public void testCanInlineReferenceToFunctionInExpression23a(); // public void testCanInlineReferenceToFunctionInLoop1(); // public void testCanInlineReferenceToFunctionInLoop2(); // public void testInline1(); // public void testInline2(); // public void testInline3(); // public void testInline4(); // public void testInline5(); // public void testInline6(); // public void testInline7(); // public void testInline8(); // public void testInline9(); // public void testInline10(); // public void testInline11(); // public void testInline12(); // public void testInline13(); // public void testInline14(); // public void testInline15(); // public void testInline16(); // public void testInline17(); // public void testInline18(); // public void testInline19(); // public void testInline19b(); // public void testInlineIntoLoop(); // public void testInlineFunctionWithInnerFunction1(); // public void testInlineFunctionWithInnerFunction2(); // public void testInlineFunctionWithInnerFunction3(); // public void testInlineFunctionWithInnerFunction4(); // public void testInlineFunctionWithInnerFunction5(); // public void testInlineReferenceInExpression1(); // public void testInlineReferenceInExpression2(); // public void testInlineReferenceInExpression3(); // public void testInlineReferenceInExpression4(); // public void testInlineReferenceInExpression5(); // public void testInlineReferenceInExpression6(); // public void testInlineReferenceInExpression7(); // public void testInlineReferenceInExpression8(); // public void testInlineReferenceInExpression9(); // public void testInlineReferenceInExpression11(); // public void testInlineReferenceInExpression12(); // public void testInlineReferenceInExpression13(); // public void testInlineReferenceInExpression14(); // public void testInlineReferenceInExpression15(); // public void testInlineReferenceInExpression16(); // public void testInlineReferenceInExpression17(); // public void testInlineWithinCalls1(); // public void testInlineAssignmentToConstant(); // public void testBug1897706(); // public void testIssue1101a(); // public void testIssue1101b(); // public void helperCanInlineReferenceToFunction( // final CanInlineResult expectedResult, // final String code, // final String fnName, // final InliningMode mode); // public void helperCanInlineReferenceToFunction( // final CanInlineResult expectedResult, // final String code, // final String fnName, // final InliningMode mode, // boolean allowDecomposition); // public void helperInlineReferenceToFunction( // String code, final String expectedResult, // final String fnName, final InliningMode mode); // private void validateSourceInfo(Compiler compiler, Node subtree); // public void helperInlineReferenceToFunction( // String code, final String expectedResult, // final String fnName, final InliningMode mode, // final boolean decompose); // private static Node findFunction(Node n, String name); // private static Node prep(String js); // private static Node parse(Compiler compiler, String js); // private static Node parseExpected(Compiler compiler, String js); // private static String toSource(Node n); // TestCallback(String callname, Method method); // @Override // public boolean shouldTraverse( // NodeTraversal nodeTraversal, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public boolean call(NodeTraversal t, Node n, Node parent); // @Override // public boolean call(NodeTraversal t, Node n, Node parent); // } // You are a professional Java test case writer, please create a test case named `testInlineReferenceInExpression11` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. // } // "foo", INLINE_BLOCK); // "b += 1 + JSCompiler_inline_result$$0 }", // "JSCompiler_inline_result$$0=true;}" + // "{var JSCompiler_inline_result$$0; " + // "function x() {var b;" + // "function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "/** @nosideeffects */ function foo(a){return true;}; " + // helperInlineReferenceToFunction( // // Call in assignment expression. // public void testInlineReferenceInExpression10() { // TODO(nicksantos): Re-enable with side-effect detection. public void testInlineReferenceInExpression11() {
// } // "foo", INLINE_BLOCK); // "b += 1 + JSCompiler_inline_result$$0 }", // "JSCompiler_inline_result$$0=true;}" + // "{var JSCompiler_inline_result$$0; " + // "function x() {var b;" + // "function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "/** @nosideeffects */ function foo(a){return true;}; " + // helperInlineReferenceToFunction( // // Call in assignment expression. // public void testInlineReferenceInExpression10() { // TODO(nicksantos): Re-enable with side-effect detection.
107
com.google.javascript.jscomp.FunctionInjector
test
```java CanInlineResult.YES; @Override protected void setUp() throws Exception; private FunctionInjector getInjector(); public void testIsSimpleFunction1(); public void testIsSimpleFunction2(); public void testIsSimpleFunction3(); public void testIsSimpleFunction4(); public void testIsSimpleFunction5(); public void testIsSimpleFunction6(); public void testIsSimpleFunction7(); public void testCanInlineReferenceToFunction1(); public void testCanInlineReferenceToFunction2(); public void testCanInlineReferenceToFunction3(); public void testCanInlineReferenceToFunction4(); public void testCanInlineReferenceToFunction5(); public void testCanInlineReferenceToFunction6(); public void testCanInlineReferenceToFunction7(); public void testCanInlineReferenceToFunction8(); public void testCanInlineReferenceToFunction9(); public void testCanInlineReferenceToFunction10(); public void testCanInlineReferenceToFunction11(); public void testCanInlineReferenceToFunction12(); public void testCanInlineReferenceToFunction12b(); public void testCanInlineReferenceToFunction14(); public void testCanInlineReferenceToFunction15(); public void testCanInlineReferenceToFunction16(); public void testCanInlineReferenceToFunction17(); public void testCanInlineReferenceToFunction18(); public void testCanInlineReferenceToFunction19(); public void testCanInlineReferenceToFunction20(); public void testCanInlineReferenceToFunction21(); public void testCanInlineReferenceToFunction22(); public void testCanInlineReferenceToFunction23(); public void testCanInlineReferenceToFunction24(); public void testCanInlineReferenceToFunction25(); public void testCanInlineReferenceToFunction26(); public void testCanInlineReferenceToFunction27(); public void testCanInlineReferenceToFunction28(); public void testCanInlineReferenceToFunction29(); public void testCanInlineReferenceToFunction30(); public void testCanInlineReferenceToFunction31(); public void testCanInlineReferenceToFunction32(); public void testCanInlineReferenceToFunction33(); public void testCanInlineReferenceToFunction34(); public void testCanInlineReferenceToFunction35(); public void testCanInlineReferenceToFunction36(); public void testCanInlineReferenceToFunction37(); public void testCanInlineReferenceToFunction38(); public void testCanInlineReferenceToFunction39(); public void testCanInlineReferenceToFunction40(); public void testCanInlineReferenceToFunction41(); public void testCanInlineReferenceToFunction42(); public void testCanInlineReferenceToFunction43(); public void testCanInlineReferenceToFunction44(); public void testCanInlineReferenceToFunction45(); public void testCanInlineReferenceToFunction46(); public void testCanInlineReferenceToFunction47(); public void testCanInlineReferenceToFunction48(); public void testCanInlineReferenceToFunction49(); public void testCanInlineReferenceToFunction50(); public void testCanInlineReferenceToFunction51(); public void testCanInlineReferenceToFunctionInExpression1(); public void testCanInlineReferenceToFunctionInExpression2(); public void testCanInlineReferenceToFunctionInExpression3(); public void testCanInlineReferenceToFunctionInExpression4(); public void testCanInlineReferenceToFunctionInExpression5(); public void testCanInlineReferenceToFunctionInExpression5a(); public void testCanInlineReferenceToFunctionInExpression6(); public void testCanInlineReferenceToFunctionInExpression7(); public void testCanInlineReferenceToFunctionInExpression7a(); public void testCanInlineReferenceToFunctionInExpression8(); public void testCanInlineReferenceToFunctionInExpression9(); public void testCanInlineReferenceToFunctionInExpression10(); public void testCanInlineReferenceToFunctionInExpression10a(); public void testCanInlineReferenceToFunctionInExpression12(); public void testCanInlineReferenceToFunctionInExpression13(); public void testCanInlineReferenceToFunctionInExpression14(); public void testCanInlineReferenceToFunctionInExpression14a(); public void testCanInlineReferenceToFunctionInExpression18(); public void testCanInlineReferenceToFunctionInExpression19(); public void testCanInlineReferenceToFunctionInExpression19a(); public void testCanInlineReferenceToFunctionInExpression21(); public void testCanInlineReferenceToFunctionInExpression21a(); public void testCanInlineReferenceToFunctionInExpression22(); public void testCanInlineReferenceToFunctionInExpression22a(); public void testCanInlineReferenceToFunctionInExpression23(); public void testCanInlineReferenceToFunctionInExpression23a(); public void testCanInlineReferenceToFunctionInLoop1(); public void testCanInlineReferenceToFunctionInLoop2(); public void testInline1(); public void testInline2(); public void testInline3(); public void testInline4(); public void testInline5(); public void testInline6(); public void testInline7(); public void testInline8(); public void testInline9(); public void testInline10(); public void testInline11(); public void testInline12(); public void testInline13(); public void testInline14(); public void testInline15(); public void testInline16(); public void testInline17(); public void testInline18(); public void testInline19(); public void testInline19b(); public void testInlineIntoLoop(); public void testInlineFunctionWithInnerFunction1(); public void testInlineFunctionWithInnerFunction2(); public void testInlineFunctionWithInnerFunction3(); public void testInlineFunctionWithInnerFunction4(); public void testInlineFunctionWithInnerFunction5(); public void testInlineReferenceInExpression1(); public void testInlineReferenceInExpression2(); public void testInlineReferenceInExpression3(); public void testInlineReferenceInExpression4(); public void testInlineReferenceInExpression5(); public void testInlineReferenceInExpression6(); public void testInlineReferenceInExpression7(); public void testInlineReferenceInExpression8(); public void testInlineReferenceInExpression9(); public void testInlineReferenceInExpression11(); public void testInlineReferenceInExpression12(); public void testInlineReferenceInExpression13(); public void testInlineReferenceInExpression14(); public void testInlineReferenceInExpression15(); public void testInlineReferenceInExpression16(); public void testInlineReferenceInExpression17(); public void testInlineWithinCalls1(); public void testInlineAssignmentToConstant(); public void testBug1897706(); public void testIssue1101a(); public void testIssue1101b(); public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode); public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode, boolean allowDecomposition); public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode); private void validateSourceInfo(Compiler compiler, Node subtree); public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode, final boolean decompose); private static Node findFunction(Node n, String name); private static Node prep(String js); private static Node parse(Compiler compiler, String js); private static Node parseExpected(Compiler compiler, String js); private static String toSource(Node n); TestCallback(String callname, Method method); @Override public boolean shouldTraverse( NodeTraversal nodeTraversal, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public boolean call(NodeTraversal t, Node n, Node parent); @Override public boolean call(NodeTraversal t, Node n, Node parent); } ``` You are a professional Java test case writer, please create a test case named `testInlineReferenceInExpression11` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java // } // "foo", INLINE_BLOCK); // "b += 1 + JSCompiler_inline_result$$0 }", // "JSCompiler_inline_result$$0=true;}" + // "{var JSCompiler_inline_result$$0; " + // "function x() {var b;" + // "function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "/** @nosideeffects */ function foo(a){return true;}; " + // helperInlineReferenceToFunction( // // Call in assignment expression. // public void testInlineReferenceInExpression10() { // TODO(nicksantos): Re-enable with side-effect detection. public void testInlineReferenceInExpression11() { ```
class FunctionInjector
package com.google.javascript.jscomp; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.FunctionInjector.CanInlineResult; import com.google.javascript.jscomp.FunctionInjector.InliningMode; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.util.List; import java.util.Set;
@Override protected void setUp() throws Exception; private FunctionInjector getInjector(); public void testIsSimpleFunction1(); public void testIsSimpleFunction2(); public void testIsSimpleFunction3(); public void testIsSimpleFunction4(); public void testIsSimpleFunction5(); public void testIsSimpleFunction6(); public void testIsSimpleFunction7(); public void testCanInlineReferenceToFunction1(); public void testCanInlineReferenceToFunction2(); public void testCanInlineReferenceToFunction3(); public void testCanInlineReferenceToFunction4(); public void testCanInlineReferenceToFunction5(); public void testCanInlineReferenceToFunction6(); public void testCanInlineReferenceToFunction7(); public void testCanInlineReferenceToFunction8(); public void testCanInlineReferenceToFunction9(); public void testCanInlineReferenceToFunction10(); public void testCanInlineReferenceToFunction11(); public void testCanInlineReferenceToFunction12(); public void testCanInlineReferenceToFunction12b(); public void testCanInlineReferenceToFunction14(); public void testCanInlineReferenceToFunction15(); public void testCanInlineReferenceToFunction16(); public void testCanInlineReferenceToFunction17(); public void testCanInlineReferenceToFunction18(); public void testCanInlineReferenceToFunction19(); public void testCanInlineReferenceToFunction20(); public void testCanInlineReferenceToFunction21(); public void testCanInlineReferenceToFunction22(); public void testCanInlineReferenceToFunction23(); public void testCanInlineReferenceToFunction24(); public void testCanInlineReferenceToFunction25(); public void testCanInlineReferenceToFunction26(); public void testCanInlineReferenceToFunction27(); public void testCanInlineReferenceToFunction28(); public void testCanInlineReferenceToFunction29(); public void testCanInlineReferenceToFunction30(); public void testCanInlineReferenceToFunction31(); public void testCanInlineReferenceToFunction32(); public void testCanInlineReferenceToFunction33(); public void testCanInlineReferenceToFunction34(); public void testCanInlineReferenceToFunction35(); public void testCanInlineReferenceToFunction36(); public void testCanInlineReferenceToFunction37(); public void testCanInlineReferenceToFunction38(); public void testCanInlineReferenceToFunction39(); public void testCanInlineReferenceToFunction40(); public void testCanInlineReferenceToFunction41(); public void testCanInlineReferenceToFunction42(); public void testCanInlineReferenceToFunction43(); public void testCanInlineReferenceToFunction44(); public void testCanInlineReferenceToFunction45(); public void testCanInlineReferenceToFunction46(); public void testCanInlineReferenceToFunction47(); public void testCanInlineReferenceToFunction48(); public void testCanInlineReferenceToFunction49(); public void testCanInlineReferenceToFunction50(); public void testCanInlineReferenceToFunction51(); public void testCanInlineReferenceToFunctionInExpression1(); public void testCanInlineReferenceToFunctionInExpression2(); public void testCanInlineReferenceToFunctionInExpression3(); public void testCanInlineReferenceToFunctionInExpression4(); public void testCanInlineReferenceToFunctionInExpression5(); public void testCanInlineReferenceToFunctionInExpression5a(); public void testCanInlineReferenceToFunctionInExpression6(); public void testCanInlineReferenceToFunctionInExpression7(); public void testCanInlineReferenceToFunctionInExpression7a(); public void testCanInlineReferenceToFunctionInExpression8(); public void testCanInlineReferenceToFunctionInExpression9(); public void testCanInlineReferenceToFunctionInExpression10(); public void testCanInlineReferenceToFunctionInExpression10a(); public void testCanInlineReferenceToFunctionInExpression12(); public void testCanInlineReferenceToFunctionInExpression13(); public void testCanInlineReferenceToFunctionInExpression14(); public void testCanInlineReferenceToFunctionInExpression14a(); public void testCanInlineReferenceToFunctionInExpression18(); public void testCanInlineReferenceToFunctionInExpression19(); public void testCanInlineReferenceToFunctionInExpression19a(); public void testCanInlineReferenceToFunctionInExpression21(); public void testCanInlineReferenceToFunctionInExpression21a(); public void testCanInlineReferenceToFunctionInExpression22(); public void testCanInlineReferenceToFunctionInExpression22a(); public void testCanInlineReferenceToFunctionInExpression23(); public void testCanInlineReferenceToFunctionInExpression23a(); public void testCanInlineReferenceToFunctionInLoop1(); public void testCanInlineReferenceToFunctionInLoop2(); public void testInline1(); public void testInline2(); public void testInline3(); public void testInline4(); public void testInline5(); public void testInline6(); public void testInline7(); public void testInline8(); public void testInline9(); public void testInline10(); public void testInline11(); public void testInline12(); public void testInline13(); public void testInline14(); public void testInline15(); public void testInline16(); public void testInline17(); public void testInline18(); public void testInline19(); public void testInline19b(); public void testInlineIntoLoop(); public void testInlineFunctionWithInnerFunction1(); public void testInlineFunctionWithInnerFunction2(); public void testInlineFunctionWithInnerFunction3(); public void testInlineFunctionWithInnerFunction4(); public void testInlineFunctionWithInnerFunction5(); public void testInlineReferenceInExpression1(); public void testInlineReferenceInExpression2(); public void testInlineReferenceInExpression3(); public void testInlineReferenceInExpression4(); public void testInlineReferenceInExpression5(); public void testInlineReferenceInExpression6(); public void testInlineReferenceInExpression7(); public void testInlineReferenceInExpression8(); public void testInlineReferenceInExpression9(); public void testInlineReferenceInExpression11(); public void testInlineReferenceInExpression12(); public void testInlineReferenceInExpression13(); public void testInlineReferenceInExpression14(); public void testInlineReferenceInExpression15(); public void testInlineReferenceInExpression16(); public void testInlineReferenceInExpression17(); public void testInlineWithinCalls1(); public void testInlineAssignmentToConstant(); public void testBug1897706(); public void testIssue1101a(); public void testIssue1101b(); public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode); public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode, boolean allowDecomposition); public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode); private void validateSourceInfo(Compiler compiler, Node subtree); public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode, final boolean decompose); private static Node findFunction(Node n, String name); private static Node prep(String js); private static Node parse(Compiler compiler, String js); private static Node parseExpected(Compiler compiler, String js); private static String toSource(Node n); TestCallback(String callname, Method method); @Override public boolean shouldTraverse( NodeTraversal nodeTraversal, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public boolean call(NodeTraversal t, Node n, Node parent); @Override public boolean call(NodeTraversal t, Node n, Node parent);
fcb19b08910dabcb8787c370824e51adc758bb21493c708dc57550fb066b6040
[ "com.google.javascript.jscomp.FunctionInjectorTest::testInlineReferenceInExpression11" ]
private final AbstractCompiler compiler; private final boolean allowDecomposition; private Set<String> knownConstants = Sets.newHashSet(); private final boolean assumeStrictThis; private final boolean assumeMinimumCapture; private final Supplier<String> safeNameIdSupplier; private final Supplier<String> throwawayNameSupplier = new Supplier<String>() { private int nextId = 0; @Override public String get() { return String.valueOf(nextId++); } }; private static final int NAME_COST_ESTIMATE = InlineCostEstimator.ESTIMATED_IDENTIFIER_COST; private static final int COMMA_COST = 1; private static final int PAREN_COST = 2;
public void testInlineReferenceInExpression11()
static final InliningMode INLINE_DIRECT = InliningMode.DIRECT; static final InliningMode INLINE_BLOCK = InliningMode.BLOCK; private boolean assumeStrictThis = false; private boolean assumeMinimumCapture = false; static final CanInlineResult NEW_VARS_IN_GLOBAL_SCOPE = CanInlineResult.YES;
Closure
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.FunctionInjector.CanInlineResult; import com.google.javascript.jscomp.FunctionInjector.InliningMode; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.util.List; import java.util.Set; /** * Inline function tests. * @author johnlenz@google.com (John Lenz) */ public class FunctionInjectorTest extends TestCase { static final InliningMode INLINE_DIRECT = InliningMode.DIRECT; static final InliningMode INLINE_BLOCK = InliningMode.BLOCK; private boolean assumeStrictThis = false; private boolean assumeMinimumCapture = false; @Override protected void setUp() throws Exception { super.setUp(); assumeStrictThis = false; } private FunctionInjector getInjector() { Compiler compiler = new Compiler(); return new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), true, assumeStrictThis, assumeMinimumCapture); } public void testIsSimpleFunction1() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){}"))); } public void testIsSimpleFunction2() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return 0;}"))); } public void testIsSimpleFunction3() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return x ? 0 : 1}"))); } public void testIsSimpleFunction4() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return;}"))); } public void testIsSimpleFunction5() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return 0; return 0;}"))); } public void testIsSimpleFunction6() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){var x=true;return x ? 0 : 1}"))); } public void testIsSimpleFunction7() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){if (x) return 0; else return 1}"))); } public void testCanInlineReferenceToFunction1() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction2() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction3() { // NOTE: FoldConstants will convert this to a empty function, // so there is no need to explicitly support it. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return;}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction4() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return;}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction5() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction6() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction7() { // In var initialization. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x=foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction8() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction9() { // In assignment. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction10() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction11() { // In expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction12() { // "foo" is not known to be side-effect free, it might change the value // of "x", so it can't be inlined. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction12b() { // "foo" is not known to be side-effect free, it might change the value // of "x", so it can't be inlined. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunction13() { // // ... if foo is side-effect free we can inline here. // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(){return true;};" + // "var x; x=x+foo();", "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunction14() { // Simple call with parameters helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; foo(x);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction15() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; foo(x);", "foo", INLINE_BLOCK); } // TODO(johnlenz): remove this constant once this has been proven in // production code. static final CanInlineResult NEW_VARS_IN_GLOBAL_SCOPE = CanInlineResult.YES; public void testCanInlineReferenceToFunction16() { // Function "foo" as it contains "var b" which // must be brought into the global scope. helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){var b;return a;}; foo(goo());", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction17() { // This doesn't bring names into the global name space. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a;}; " + "function x() { foo(goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction18() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a;} foo(x++);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction19() { // Parameter has mutable parameter referenced more than once. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo([]);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction20() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo({});", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction21() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo(new Date);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction22() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo(true && new Date);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction23() { // variables to global scope. helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return a;}; foo(x++);", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction24() { // ... this is OK, because it doesn't introduce a new global name. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a;}; " + "function x() { foo(x++); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction25() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a;}; foo(x++);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction26() { helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return a+a;}; foo(x++);", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction27() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a+a;}; " + "function x() { foo(x++); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction28() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; foo(goo());", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction29() { helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return true;}; foo(goo());", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction30() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo(goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction31() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a) {return true;}; " + "function x() {foo.call(this, 1);}", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction32() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.apply(this, [1]); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction33() { // No special handling is required for method calls passing this. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.bar(this, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction34() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction35() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.apply(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction36() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.bar(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction37() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(null, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction38() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(null, goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(null, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction39() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(bar, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction40() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(bar, goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(bar, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction41() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction42() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction43() { // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction44() { assumeStrictThis = false; // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_BLOCK); assumeStrictThis = true; // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction45() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction46() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction47() { // Call with inner function expression and variable decl. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){var a; return function() {return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction48() { // Call with inner function expression and variable decl. // TODO(johnlenz): should we validate no values in scope? helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){var a; return function() {return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction49() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {var a; return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction50() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {var a; return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction51() { // Call with inner function statement. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){function x() {var a; return true;} return x}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression1() { // Call in if condition helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { if (foo(1)) throw 'test'; }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression2() { // Call in return expression helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { return foo(1); }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression3() { // Call in switch expression helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { switch(foo(1)) { default:break; } }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression4() { // Call in hook condition helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {foo(1)?0:1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression5() { // Call in hook side-effect free condition helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {true?foo(1):1 }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression5a() { // Call in hook side-effect free condition helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {true?foo(1):1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression6() { // Call in expression statement "condition" helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {foo(1) && 1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression7() { // Call in expression statement after side-effect free "condition" helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {1 && foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression7a() { // Call in expression statement after side-effect free "condition" helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {1 && foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression8() { // Call in expression statement after side-effect free operator helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression9() { // Call in VAR expression. helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var b = 1 + foo(1)}", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression10() { // Call in assignment expression. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {var b; b += 1 + foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression10a() { // Call in assignment expression. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var b; b += 1 + foo(1) }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression11() { // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression12() { helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var a,b,c; a = b = c = foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression13() { helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var a,b,c; a = b = c = 1 + foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression14() { // ... foo can not be inlined because of possible changes to "c". helperCanInlineReferenceToFunction(CanInlineResult.NO, "var a = {}, b = {}, c;" + "a.test = 'a';" + "b.test = 'b';" + "c = a;" + "function foo(){c = b; return 'foo'};" + "c.test=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression14a() { // ... foo can be inlined despite possible changes to "c". helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "var a = {}, b = {}, c;" + "a.test = 'a';" + "b.test = 'b';" + "c = a;" + "function foo(){c = b; return 'foo'};" + "c.test=foo();", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression15() { // // ... foo can be inlined as it is side-effect free. // helperCanInlineReferenceToFunction(true, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "c.test=foo();", // "foo", INLINE_BLOCK); // } // public void testCanInlineReferenceToFunctionInExpression16() { // // ... foo can not be inlined because of possible side-effects of x() // helperCanInlineReferenceToFunction(false, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "function x(){return c};" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "x().test=foo();", // "foo", INLINE_BLOCK); // } // public void testCanInlineReferenceToFunctionInExpression17() { // // ... foo can be inlined because of x() is side-effect free. // helperCanInlineReferenceToFunction(true, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "/** @nosideeffects */ function x(){return c};" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "x().test=foo();", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression18() { // Call in within a call helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(){return _g();}; " + "function x() {1 + foo()() }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression19() { // ... unless foo is known to be side-effect free, it might actually // change the value of "_g" which would unfortunately change the behavior, // so we can't inline here. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(foo()) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression19a() { // ... unless foo is known to be side-effect free, it might actually // change the value of "_g" which would unfortunately change the behavior, // so we can't inline here. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(foo()) }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression20() { // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(){return a;}; " + // "function x() {1 + _g(foo()) }", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression21() { // Assignments to object are problematic if the call has side-effects, // as the object that is being referred to can change. // Note: This could be changed be inlined if we in some way make "z" // as not escaping from the local scope. helperCanInlineReferenceToFunction(CanInlineResult.NO, "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression21a() { // Assignments to object are problematic if the call has side-effects, // as the object that is being referred to can change. // Note: This could be changed be inlined if we in some way make "z" // as not escaping from the local scope. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression22() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo()) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression22a() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo()) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression23() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo.call(this)) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression23a() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo.call(this)) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInLoop1() { helperCanInlineReferenceToFunction( CanInlineResult.YES, "function foo(){return a;}; " + "while(1) { foo(); }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInLoop2() { // If function contains function, don't inline it into a loop. // TODO(johnlenz): this can be improved by looking to see // if the inner function contains any references to values defined // in the outer function. helperCanInlineReferenceToFunction( CanInlineResult.NO, "function foo(){return function() {};}; " + "while(1) { foo(); }", "foo", INLINE_BLOCK, true); } public void testInline1() { helperInlineReferenceToFunction( "function foo(){}; foo();", "function foo(){}; void 0", "foo", INLINE_DIRECT); } public void testInline2() { helperInlineReferenceToFunction( "function foo(){}; foo();", "function foo(){}; {}", "foo", INLINE_BLOCK); } public void testInline3() { helperInlineReferenceToFunction( "function foo(){return;}; foo();", "function foo(){return;}; {}", "foo", INLINE_BLOCK); } public void testInline4() { helperInlineReferenceToFunction( "function foo(){return true;}; foo();", "function foo(){return true;}; true;", "foo", INLINE_DIRECT); } public void testInline5() { helperInlineReferenceToFunction( "function foo(){return true;}; foo();", "function foo(){return true;}; {true;}", "foo", INLINE_BLOCK); } public void testInline6() { // In var initialization. helperInlineReferenceToFunction( "function foo(){return true;}; var x=foo();", "function foo(){return true;}; var x=true;", "foo", INLINE_DIRECT); } public void testInline7() { helperInlineReferenceToFunction( "function foo(){return true;}; var x=foo();", "function foo(){return true;}; var x;" + "{x=true}", "foo", INLINE_BLOCK); } public void testInline8() { // In assignment. helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=foo();", "function foo(){return true;}; var x; x=true;", "foo", INLINE_DIRECT); } public void testInline9() { helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=foo();", "function foo(){return true;}; var x;{x=true}", "foo", INLINE_BLOCK); } public void testInline10() { // In expression. helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=x+foo();", "function foo(){return true;}; var x; x=x+true;", "foo", INLINE_DIRECT); } public void testInline11() { // Simple call with parameters helperInlineReferenceToFunction( "function foo(a){return true;}; foo(x);", "function foo(a){return true;}; true;", "foo", INLINE_DIRECT); } public void testInline12() { helperInlineReferenceToFunction( "function foo(a){return true;}; foo(x);", "function foo(a){return true;}; {true}", "foo", INLINE_BLOCK); } public void testInline13() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return a;}; " + "function x() { foo(x++); }", "function foo(a){return a;}; " + "function x() {{var a$$inline_0=x++;" + "a$$inline_0}}", "foo", INLINE_BLOCK); } public void testInline14() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(x++);", "function foo(a){return a+a;}; " + "{var a$$inline_0=x++;" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline15() { // Parameter has mutable, references more than once. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(new Date());", "function foo(a){return a+a;}; " + "{var a$$inline_0=new Date();" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline16() { // Parameter is large, references more than once. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(function(){});", "function foo(a){return a+a;}; " + "{var a$$inline_0=function(){};" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline17() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return true;}; foo(goo());", "function foo(a){return true;};" + "{var a$$inline_0=goo();true}", "foo", INLINE_BLOCK); } public void testInline18() { // This doesn't bring names into the global name space. helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "function x() { foo(goo()); }", "function foo(a){var b;return a;}; " + "function x() {{var a$$inline_0=goo();" + "var b$$inline_1;a$$inline_0}}", "foo", INLINE_BLOCK); } public void testInline19() { // Properly alias. helperInlineReferenceToFunction( "var x = 1; var y = 2;" + "function foo(a,b){x = b; y = a;}; " + "function bar() { foo(x,y); }", "var x = 1; var y = 2;" + "function foo(a,b){x = b; y = a;}; " + "function bar() {" + "{var a$$inline_0=x;" + "x = y;" + "y = a$$inline_0;}" + "}", "foo", INLINE_BLOCK); } public void testInline19b() { helperInlineReferenceToFunction( "var x = 1; var y = 2;" + "function foo(a,b){y = a; x = b;}; " + "function bar() { foo(x,y); }", "var x = 1; var y = 2;" + "function foo(a,b){y = a; x = b;}; " + "function bar() {" + "{var b$$inline_1=y;" + "y = x;" + "x = b$$inline_1;}" + "}", "foo", INLINE_BLOCK); } public void testInlineIntoLoop() { helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "for(;1;){ foo(1); }", "function foo(a){var b;return a;}; " + "for(;1;){ {" + "var b$$inline_1=void 0;1}}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "do{ foo(1); } while(1)", "function foo(a){var b;return a;}; " + "do{ {" + "var b$$inline_1=void 0;1}}while(1)", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){for(var b in c)return a;}; " + "for(;1;){ foo(1); }", "function foo(a){var b;for(b in c)return a;}; " + "for(;1;){ {JSCompiler_inline_label_foo_2:{" + "var b$$inline_1=void 0;for(b$$inline_1 in c){" + "1;break JSCompiler_inline_label_foo_2" + "}}}}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction1() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {return true;}}; foo();", "function foo(){return function() {return true;}};" + "(function() {return true;})", "foo", INLINE_DIRECT); } public void testInlineFunctionWithInnerFunction2() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {return true;}}; foo();", "function foo(){return function() {return true;}};" + "{(function() {return true;})}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction3() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {var a; return true;}}; foo();", "function foo(){return function() {var a; return true;}};" + "(function() {var a; return true;});", "foo", INLINE_DIRECT); } public void testInlineFunctionWithInnerFunction4() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {var a; return true;}}; foo();", "function foo(){return function() {var a; return true;}};" + "{(function() {var a$$inline_0; return true;});}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction5() { // Call with inner function statement. helperInlineReferenceToFunction( "function foo(){function x() {var a; return true;} return x}; foo();", "function foo(){function x(){var a;return true}return x};" + "{var x$$inline_0 = function(){" + "var a$$inline_1;return true};x$$inline_0}", "foo", INLINE_BLOCK); } public void testInlineReferenceInExpression1() { // Call in if condition helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { if (foo(1)) throw 'test'; }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "if (JSCompiler_inline_result$$0) throw 'test'; }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression2() { // Call in return expression helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { return foo(1); }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "return JSCompiler_inline_result$$0; }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression3() { // Call in switch expression helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { switch(foo(1)) { default:break; } }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "switch(JSCompiler_inline_result$$0) { default:break; } }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression4() { // Call in hook condition helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1)?0:1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0?0:1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression5() { // Call in expression statement "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1)&&1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0&&1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression6() { // Call in expression statement after side-effect free "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "1 + JSCompiler_inline_result$$0 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression7() { // Call in expression statement "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1) && 1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0&&1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression8() { // Call in expression statement after side-effect free operator helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=true;}" + "1 + JSCompiler_inline_result$$0 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression9() { // Call in VAR expression. helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {var b = 1 + foo(1)}", "function foo(a){return true;}; " + "function x() { " + "var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=true;}" + "var b = 1 + JSCompiler_inline_result$$0 " + "}", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testInlineReferenceInExpression10() { // // Call in assignment expression. // helperInlineReferenceToFunction( // "/** @nosideeffects */ function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "function foo(a){return true;}; " + // "function x() {var b;" + // "{var JSCompiler_inline_result$$0; " + // "JSCompiler_inline_result$$0=true;}" + // "b += 1 + JSCompiler_inline_result$$0 }", // "foo", INLINE_BLOCK); // } public void testInlineReferenceInExpression11() { // Call under label helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {a:foo(1)?0:1 }", "function foo(a){return true;}; " + "function x() {" + " a:{" + " var JSCompiler_inline_result$$0; " + " {JSCompiler_inline_result$$0=true;}" + " JSCompiler_inline_result$$0?0:1 " + " }" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression12() { helperInlineReferenceToFunction( "function foo(a){return true;}" + "function x() { 1?foo(1):1; }", "function foo(a){return true}" + "function x() {" + " if(1) {" + " {true;}" + " } else {" + " 1;" + " }" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression13() { helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { goo() + (1?foo(1):1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_temp_const$$0=goo();" + "var JSCompiler_temp$$1;" + "if(1) {" + " {JSCompiler_temp$$1=true;} " + "} else {" + " JSCompiler_temp$$1=1;" + "}" + "JSCompiler_temp_const$$0 + JSCompiler_temp$$1" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression14() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression15() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo.call(this,1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression16() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z[bar()] = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$1=z;" + "var JSCompiler_temp_const$$0=bar();" + "var JSCompiler_inline_result$$2;" + "{" + "z= {};" + "JSCompiler_inline_result$$2 = true;" + "}" + "JSCompiler_temp_const$$1[JSCompiler_temp_const$$0] = " + "JSCompiler_inline_result$$2;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression17() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.y.x.gack = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z.y.x;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineWithinCalls1() { // Call in within a call helperInlineReferenceToFunction( "function foo(){return _g;}; " + "function x() {1 + foo()() }", "function foo(){return _g;}; " + "function x() { var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=_g;}" + "1 + JSCompiler_inline_result$$0() }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testInlineWithinCalls2() { // helperInlineReferenceToFunction( // "/** @nosideeffects */ function foo(){return true;}; " + // "function x() {1 + _g(foo()) }", // "function foo(){return true;}; " + // "function x() { {var JSCompiler_inline_result$$0; " + // "JSCompiler_inline_result$$0=true;}" + // "1 + _g(JSCompiler_inline_result$$0) }", // "foo", INLINE_BLOCK, true); // } public void testInlineAssignmentToConstant() { // Call in within a call helperInlineReferenceToFunction( "function foo(){return _g;}; " + "function x(){var CONSTANT_RESULT = foo(); }", "function foo(){return _g;}; " + "function x() {" + " var JSCompiler_inline_result$$0;" + " {JSCompiler_inline_result$$0=_g;}" + " var CONSTANT_RESULT = JSCompiler_inline_result$$0;" + "}", "foo", INLINE_BLOCK, true); } public void testBug1897706() { helperInlineReferenceToFunction( "function foo(a){}; foo(x())", "function foo(a){}; {var a$$inline_0=x()}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){bar()}; foo(x())", "function foo(a){bar()}; {var a$$inline_0=x();bar()}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a,b){bar()}; foo(x(),y())", "function foo(a,b){bar()};" + "{var a$$inline_0=x();var b$$inline_1=y();bar()}", "foo", INLINE_BLOCK); } public void testIssue1101a() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return modifiyX() + a;} foo(x);", "foo", INLINE_DIRECT); } public void testIssue1101b() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return (x.prop = 2),a;} foo(x.prop);", "foo", INLINE_DIRECT); } /** * Test case * * var a = {}, b = {} * a.test = "a", b.test = "b" * c = a; * foo() { c=b; return "a" } * c.teste * */ public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode) { helperCanInlineReferenceToFunction( expectedResult, code, fnName, mode, false); } public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode, boolean allowDecomposition) { final Compiler compiler = new Compiler(); final FunctionInjector injector = new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), allowDecomposition, assumeStrictThis, assumeMinimumCapture); final Node tree = parse(compiler, code); final Node fnNode = findFunction(tree, fnName); final Set<String> unsafe = FunctionArgumentInjector.findModifiedParameters(fnNode); // can-inline tester Method tester = new Method() { @Override public boolean call(NodeTraversal t, Node n, Node parent) { CanInlineResult result = injector.canInlineReferenceToFunction( t, n, fnNode, unsafe, mode, NodeUtil.referencesThis(fnNode), NodeUtil.containsFunction(NodeUtil.getFunctionBody(fnNode))); assertEquals(expectedResult, result); return true; } }; compiler.resetUniqueNameId(); TestCallback test = new TestCallback(fnName, tester); NodeTraversal.traverse(compiler, tree, test); } public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode) { helperInlineReferenceToFunction( code, expectedResult, fnName, mode, false); } private void validateSourceInfo(Compiler compiler, Node subtree) { (new LineNumberCheck(compiler)).setCheckSubTree(subtree); // Source information problems are reported as compiler errors. if (compiler.getErrorCount() != 0) { String msg = "Error encountered: "; for (JSError err : compiler.getErrors()) { msg += err.toString() + "\n"; } assertTrue(msg, compiler.getErrorCount() == 0); } } public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode, final boolean decompose) { final Compiler compiler = new Compiler(); final FunctionInjector injector = new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), decompose, assumeStrictThis, assumeMinimumCapture); List<SourceFile> externsInputs = Lists.newArrayList( SourceFile.fromCode("externs", "")); CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new GoogleCodingConvention()); compiler.init(externsInputs, Lists.newArrayList( SourceFile.fromCode("code", code)), options); Node parseRoot = compiler.parseInputs(); Node externsRoot = parseRoot.getFirstChild(); final Node tree = parseRoot.getLastChild(); assertNotNull(tree); assertTrue(tree != externsRoot); final Node expectedRoot = parseExpected(new Compiler(), expectedResult); Node mainRoot = tree; MarkNoSideEffectCalls mark = new MarkNoSideEffectCalls(compiler); mark.process(externsRoot, mainRoot); Normalize normalize = new Normalize(compiler, false); normalize.process(externsRoot, mainRoot); compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED); final Node fnNode = findFunction(tree, fnName); assertNotNull(fnNode); final Set<String> unsafe = FunctionArgumentInjector.findModifiedParameters(fnNode); assertNotNull(fnNode); // inline tester Method tester = new Method() { @Override public boolean call(NodeTraversal t, Node n, Node parent) { CanInlineResult canInline = injector.canInlineReferenceToFunction( t, n, fnNode, unsafe, mode, NodeUtil.referencesThis(fnNode), NodeUtil.containsFunction(NodeUtil.getFunctionBody(fnNode))); assertTrue("canInlineReferenceToFunction should not be CAN_NOT_INLINE", CanInlineResult.NO != canInline); if (decompose) { assertTrue("canInlineReferenceToFunction " + "should be CAN_INLINE_AFTER_DECOMPOSITION", CanInlineResult.AFTER_PREPARATION == canInline); Set<String> knownConstants = Sets.newHashSet(); injector.setKnownConstants(knownConstants); injector.maybePrepareCall(n); assertTrue("canInlineReferenceToFunction " + "should be CAN_INLINE", CanInlineResult.YES != canInline); } Node result = injector.inline(n, fnName, fnNode, mode); validateSourceInfo(compiler, result); String explanation = expectedRoot.checkTreeEquals(tree.getFirstChild()); assertNull("\nExpected: " + toSource(expectedRoot) + "\nResult: " + toSource(tree.getFirstChild()) + "\n" + explanation, explanation); return true; } }; compiler.resetUniqueNameId(); TestCallback test = new TestCallback(fnName, tester); NodeTraversal.traverse(compiler, tree, test); } interface Method { boolean call(NodeTraversal t, Node n, Node parent); } class TestCallback implements Callback { private final String callname; private final Method method; private boolean complete = false; TestCallback(String callname, Method method) { this.callname = callname; this.method = method; } @Override public boolean shouldTraverse( NodeTraversal nodeTraversal, Node n, Node parent) { return !complete; } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isCall()) { Node callee; if (NodeUtil.isGet(n.getFirstChild())) { callee = n.getFirstChild().getFirstChild(); } else { callee = n.getFirstChild(); } if (callee.isName() && callee.getString().equals(callname)) { complete = method.call(t, n, parent); } } if (parent == null) { assertTrue(complete); } } } private static Node findFunction(Node n, String name) { if (n.isFunction()) { if (n.getFirstChild().getString().equals(name)) { return n; } } for (Node c : n.children()) { Node result = findFunction(c, name); if (result != null) { return result; } } return null; } private static Node prep(String js) { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n.getFirstChild(); } private static Node parse(Compiler compiler, String js) { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n; } private static Node parseExpected(Compiler compiler, String js) { Node n = compiler.parseTestCode(js); String message = "Unexpected errors: "; JSError[] errs = compiler.getErrors(); for (int i = 0; i < errs.length; i++){ message += "\n" + errs[i].toString(); } assertEquals(message, 0, compiler.getErrorCount()); return n; } private static String toSource(Node n) { return new CodePrinter.Builder(n) .setPrettyPrint(false) .setLineBreak(false) .setSourceMap(null) .build(); } }
[ { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "access$200", "be_test_function_signature": "(Lcom/google/javascript/jscomp/FunctionInjector;Lcom/google/javascript/rhino/Node;)Lcom/google/javascript/jscomp/FunctionInjector$CallSiteType;", "line_numbers": [ "38" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "callMeetsBlockInliningRequirements", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;Ljava/util/Set;)Z", "line_numbers": [ "621", "633", "637", "638", "639", "640", "644", "656", "660", "661", "666", "667", "670", "671", "673", "674", "676", "677", "682" ], "method_line_rate": 0.5789473684210527 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "canInlineReferenceAsStatementBlock", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;Ljava/util/Set;)Lcom/google/javascript/jscomp/FunctionInjector$CanInlineResult;", "line_numbers": [ "589", "590", "591", "594", "597", "600", "602", "605", "607", "609" ], "method_line_rate": 0.6 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "canInlineReferenceToFunction", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;Ljava/util/Set;Lcom/google/javascript/jscomp/FunctionInjector$InliningMode;ZZ)Lcom/google/javascript/jscomp/FunctionInjector$CanInlineResult;", "line_numbers": [ "188", "189", "196", "197", "200", "201", "204", "209", "212", "215", "216", "218" ], "method_line_rate": 0.4166666666666667 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "classifyCallSite", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)Lcom/google/javascript/jscomp/FunctionInjector$CallSiteType;", "line_numbers": [ "403", "404", "407", "409", "410", "415", "416", "423", "425", "426", "427", "429", "431", "432", "433", "434", "436", "441" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "getDecomposer", "be_test_function_signature": "()Lcom/google/javascript/jscomp/ExpressionDecomposer;", "line_numbers": [ "445" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "inline", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Ljava/lang/String;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/jscomp/FunctionInjector$InliningMode;)Lcom/google/javascript/rhino/Node;", "line_numbers": [ "250", "252", "253", "255" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "inlineFunction", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;Ljava/lang/String;)Lcom/google/javascript/rhino/Node;", "line_numbers": [ "465", "466", "470", "471", "473", "478", "479", "480", "482", "483", "486", "487", "490", "491", "492", "495", "499", "503", "506", "509", "516", "517", "520", "521", "523", "524", "529", "530", "531", "535", "536", "537", "540", "543" ], "method_line_rate": 0.5588235294117647 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "isSupportedCallType", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)Z", "line_numbers": [ "229", "230", "231", "232", "233", "234", "236", "237", "238", "242" ], "method_line_rate": 0.2 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "maybePrepareCall", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "454", "455", "456" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/FunctionInjector.java", "be_test_class_name": "com.google.javascript.jscomp.FunctionInjector", "be_test_function_name": "setKnownConstants", "be_test_function_signature": "(Ljava/util/Set;)V", "line_numbers": [ "923", "924", "925" ], "method_line_rate": 1 } ]
public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest
@Test public void testLongly() { // Y values are first, then independent vars // Each row is one observation double[] design = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; final int nobs = 16; final int nvars = 6; // Estimate the model OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); model.newSampleData(design, nobs, nvars); // Check expected beta values from NIST double[] betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{-3482258.63459582, 15.0618722713733, -0.358191792925910E-01,-2.02022980381683, -1.03322686717359,-0.511041056535807E-01, 1829.15146461355}, 2E-8); // // Check expected residuals from R double[] residuals = model.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{ 267.340029759711,-94.0139423988359,46.28716775752924, -410.114621930906,309.7145907602313,-249.3112153297231, -164.0489563956039,-13.18035686637081,14.30477260005235, 455.394094551857,-17.26892711483297,-39.0550425226967, -155.5499735953195,-85.6713080421283,341.9315139607727, -206.7578251937366}, 1E-8); // Check standard errors from NIST double[] errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {890420.383607373, 84.9149257747669, 0.334910077722432E-01, 0.488399681651699, 0.214274163161675, 0.226073200069370, 455.478499142212}, errors, 1E-6); // Check regression standard error against R Assert.assertEquals(304.8540735619638, model.estimateRegressionStandardError(), 1E-10); // Check R-Square statistics against R Assert.assertEquals(0.995479004577296, model.calculateRSquared(), 1E-12); Assert.assertEquals(0.992465007628826, model.calculateAdjustedRSquared(), 1E-12); checkVarianceConsistency(model); // Estimate model without intercept model.setNoIntercept(true); model.newSampleData(design, nobs, nvars); // Check expected beta values from R betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{-52.99357013868291, 0.07107319907358, -0.42346585566399,-0.57256866841929, -0.41420358884978, 48.41786562001326}, 1E-11); // Check standard errors from R errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {129.54486693117232, 0.03016640003786, 0.41773654056612, 0.27899087467676, 0.32128496193363, 17.68948737819961}, errors, 1E-11); // Check expected residuals from R residuals = model.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{ 279.90274927293092, -130.32465380836874, 90.73228661967445, -401.31252201634948, -440.46768772620027, -543.54512853774793, 201.32111639536299, 215.90889365977932, 73.09368242049943, 913.21694494481869, 424.82484953610174, -8.56475876776709, -361.32974610842876, 27.34560497213464, 151.28955976355002, -492.49937355336846}, 1E-10); // Check regression standard error against R Assert.assertEquals(475.1655079819517, model.estimateRegressionStandardError(), 1E-10); // Check R-Square statistics against R Assert.assertEquals(0.9999670130706, model.calculateRSquared(), 1E-12); Assert.assertEquals(0.999947220913, model.calculateAdjustedRSquared(), 1E-12); }
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.regression; // // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.linear.Array2DRowRealMatrix; // import org.apache.commons.math3.linear.LUDecomposition; // import org.apache.commons.math3.linear.QRDecomposition; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.RealVector; // import org.apache.commons.math3.stat.StatUtils; // import org.apache.commons.math3.stat.descriptive.moment.SecondMoment; // // // // public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression { // private QRDecomposition qr = null; // // public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException; // @Override // public void newSampleData(double[] data, int nobs, int nvars); // public RealMatrix calculateHat(); // public double calculateTotalSumOfSquares() throws MathIllegalArgumentException; // public double calculateResidualSumOfSquares(); // public double calculateRSquared() throws MathIllegalArgumentException; // public double calculateAdjustedRSquared() throws MathIllegalArgumentException; // @Override // protected void newXSampleData(double[][] x); // @Override // protected RealVector calculateBeta(); // @Override // protected RealMatrix calculateBetaVariance(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.regression; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor; // import org.apache.commons.math3.linear.MatrixUtils; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.Array2DRowRealMatrix; // import org.apache.commons.math3.linear.RealVector; // import org.apache.commons.math3.stat.StatUtils; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // // // // public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { // private double[] y; // private double[][] x; // // @Before // @Override // public void setUp(); // @Override // protected OLSMultipleLinearRegression createRegression(); // @Override // protected int getNumberOfRegressors(); // @Override // protected int getSampleSize(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddSampleDataWithSizeMismatch(); // @Test // public void testPerfectFit(); // @Test // public void testLongly(); // @Test // public void testSwissFertility(); // @Test // public void testHat(); // @Test // public void testYVariance(); // protected void checkVarianceConsistency(OLSMultipleLinearRegression model); // @Test // public void testNewSample2(); // @Test(expected=IllegalArgumentException.class) // public void testNewSampleDataYNull(); // @Test(expected=IllegalArgumentException.class) // public void testNewSampleDataXNull(); // @Test // public void testWampler1(); // @Test // public void testWampler2(); // @Test // public void testWampler3(); // @Test // public void testWampler4(); // @Override // public double visit(int row, int column, double value); // } // You are a professional Java test case writer, please create a test case named `testLongly` for the `OLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test Longley dataset against certified values provided by NIST. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. * * Certified values (and data) are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */
src/test/java/org/apache/commons/math3/stat/regression/OLSMultipleLinearRegressionTest.java
package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.QRDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.StatUtils; import org.apache.commons.math3.stat.descriptive.moment.SecondMoment;
public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException; @Override public void newSampleData(double[] data, int nobs, int nvars); public RealMatrix calculateHat(); public double calculateTotalSumOfSquares() throws MathIllegalArgumentException; public double calculateResidualSumOfSquares(); public double calculateRSquared() throws MathIllegalArgumentException; public double calculateAdjustedRSquared() throws MathIllegalArgumentException; @Override protected void newXSampleData(double[][] x); @Override protected RealVector calculateBeta(); @Override protected RealMatrix calculateBetaVariance();
215
testLongly
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.QRDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.StatUtils; import org.apache.commons.math3.stat.descriptive.moment.SecondMoment; public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression { private QRDecomposition qr = null; public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException; @Override public void newSampleData(double[] data, int nobs, int nvars); public RealMatrix calculateHat(); public double calculateTotalSumOfSquares() throws MathIllegalArgumentException; public double calculateResidualSumOfSquares(); public double calculateRSquared() throws MathIllegalArgumentException; public double calculateAdjustedRSquared() throws MathIllegalArgumentException; @Override protected void newXSampleData(double[][] x); @Override protected RealVector calculateBeta(); @Override protected RealMatrix calculateBetaVariance(); } // Abstract Java Test Class package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.StatUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { private double[] y; private double[][] x; @Before @Override public void setUp(); @Override protected OLSMultipleLinearRegression createRegression(); @Override protected int getNumberOfRegressors(); @Override protected int getSampleSize(); @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch(); @Test public void testPerfectFit(); @Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testHat(); @Test public void testYVariance(); protected void checkVarianceConsistency(OLSMultipleLinearRegression model); @Test public void testNewSample2(); @Test(expected=IllegalArgumentException.class) public void testNewSampleDataYNull(); @Test(expected=IllegalArgumentException.class) public void testNewSampleDataXNull(); @Test public void testWampler1(); @Test public void testWampler2(); @Test public void testWampler3(); @Test public void testWampler4(); @Override public double visit(int row, int column, double value); } ``` You are a professional Java test case writer, please create a test case named `testLongly` for the `OLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test Longley dataset against certified values provided by NIST. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. * * Certified values (and data) are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */
114
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.regression; // // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.linear.Array2DRowRealMatrix; // import org.apache.commons.math3.linear.LUDecomposition; // import org.apache.commons.math3.linear.QRDecomposition; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.RealVector; // import org.apache.commons.math3.stat.StatUtils; // import org.apache.commons.math3.stat.descriptive.moment.SecondMoment; // // // // public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression { // private QRDecomposition qr = null; // // public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException; // @Override // public void newSampleData(double[] data, int nobs, int nvars); // public RealMatrix calculateHat(); // public double calculateTotalSumOfSquares() throws MathIllegalArgumentException; // public double calculateResidualSumOfSquares(); // public double calculateRSquared() throws MathIllegalArgumentException; // public double calculateAdjustedRSquared() throws MathIllegalArgumentException; // @Override // protected void newXSampleData(double[][] x); // @Override // protected RealVector calculateBeta(); // @Override // protected RealMatrix calculateBetaVariance(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.regression; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor; // import org.apache.commons.math3.linear.MatrixUtils; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.linear.Array2DRowRealMatrix; // import org.apache.commons.math3.linear.RealVector; // import org.apache.commons.math3.stat.StatUtils; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // // // // public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { // private double[] y; // private double[][] x; // // @Before // @Override // public void setUp(); // @Override // protected OLSMultipleLinearRegression createRegression(); // @Override // protected int getNumberOfRegressors(); // @Override // protected int getSampleSize(); // @Test(expected=IllegalArgumentException.class) // public void cannotAddSampleDataWithSizeMismatch(); // @Test // public void testPerfectFit(); // @Test // public void testLongly(); // @Test // public void testSwissFertility(); // @Test // public void testHat(); // @Test // public void testYVariance(); // protected void checkVarianceConsistency(OLSMultipleLinearRegression model); // @Test // public void testNewSample2(); // @Test(expected=IllegalArgumentException.class) // public void testNewSampleDataYNull(); // @Test(expected=IllegalArgumentException.class) // public void testNewSampleDataXNull(); // @Test // public void testWampler1(); // @Test // public void testWampler2(); // @Test // public void testWampler3(); // @Test // public void testWampler4(); // @Override // public double visit(int row, int column, double value); // } // You are a professional Java test case writer, please create a test case named `testLongly` for the `OLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test Longley dataset against certified values provided by NIST. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. * * Certified values (and data) are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */ @Test public void testLongly() {
/** * Test Longley dataset against certified values provided by NIST. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. * * Certified values (and data) are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */
1
org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.QRDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.StatUtils; import org.apache.commons.math3.stat.descriptive.moment.SecondMoment; public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression { private QRDecomposition qr = null; public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException; @Override public void newSampleData(double[] data, int nobs, int nvars); public RealMatrix calculateHat(); public double calculateTotalSumOfSquares() throws MathIllegalArgumentException; public double calculateResidualSumOfSquares(); public double calculateRSquared() throws MathIllegalArgumentException; public double calculateAdjustedRSquared() throws MathIllegalArgumentException; @Override protected void newXSampleData(double[][] x); @Override protected RealVector calculateBeta(); @Override protected RealMatrix calculateBetaVariance(); } // Abstract Java Test Class package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.StatUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { private double[] y; private double[][] x; @Before @Override public void setUp(); @Override protected OLSMultipleLinearRegression createRegression(); @Override protected int getNumberOfRegressors(); @Override protected int getSampleSize(); @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch(); @Test public void testPerfectFit(); @Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testHat(); @Test public void testYVariance(); protected void checkVarianceConsistency(OLSMultipleLinearRegression model); @Test public void testNewSample2(); @Test(expected=IllegalArgumentException.class) public void testNewSampleDataYNull(); @Test(expected=IllegalArgumentException.class) public void testNewSampleDataXNull(); @Test public void testWampler1(); @Test public void testWampler2(); @Test public void testWampler3(); @Test public void testWampler4(); @Override public double visit(int row, int column, double value); } ``` You are a professional Java test case writer, please create a test case named `testLongly` for the `OLSMultipleLinearRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test Longley dataset against certified values provided by NIST. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. * * Certified values (and data) are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */ @Test public void testLongly() { ```
public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression
package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.StatUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
@Before @Override public void setUp(); @Override protected OLSMultipleLinearRegression createRegression(); @Override protected int getNumberOfRegressors(); @Override protected int getSampleSize(); @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch(); @Test public void testPerfectFit(); @Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testHat(); @Test public void testYVariance(); protected void checkVarianceConsistency(OLSMultipleLinearRegression model); @Test public void testNewSample2(); @Test(expected=IllegalArgumentException.class) public void testNewSampleDataYNull(); @Test(expected=IllegalArgumentException.class) public void testNewSampleDataXNull(); @Test public void testWampler1(); @Test public void testWampler2(); @Test public void testWampler3(); @Test public void testWampler4(); @Override public double visit(int row, int column, double value);
ff62c89f00464f0b533c13b9757d2fa263275ef21910395507dba0252934f4b7
[ "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegressionTest::testLongly" ]
private QRDecomposition qr = null;
@Test public void testLongly()
private double[] y; private double[][] x;
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.stat.StatUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class OLSMultipleLinearRegressionTest extends MultipleLinearRegressionAbstractTest { private double[] y; private double[][] x; @Before @Override public void setUp(){ y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0}; x = new double[6][]; x[0] = new double[]{0, 0, 0, 0, 0}; x[1] = new double[]{2.0, 0, 0, 0, 0}; x[2] = new double[]{0, 3.0, 0, 0, 0}; x[3] = new double[]{0, 0, 4.0, 0, 0}; x[4] = new double[]{0, 0, 0, 5.0, 0}; x[5] = new double[]{0, 0, 0, 0, 6.0}; super.setUp(); } @Override protected OLSMultipleLinearRegression createRegression() { OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression(); regression.newSampleData(y, x); return regression; } @Override protected int getNumberOfRegressors() { return x[0].length + 1; } @Override protected int getSampleSize() { return y.length; } @Test(expected=IllegalArgumentException.class) public void cannotAddSampleDataWithSizeMismatch() { double[] y = new double[]{1.0, 2.0}; double[][] x = new double[1][]; x[0] = new double[]{1.0, 0}; createRegression().newSampleData(y, x); } @Test public void testPerfectFit() { double[] betaHat = regression.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{ 11.0, 1.0 / 2.0, 2.0 / 3.0, 3.0 / 4.0, 4.0 / 5.0, 5.0 / 6.0 }, 1e-14); double[] residuals = regression.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{0d,0d,0d,0d,0d,0d}, 1e-14); RealMatrix errors = new Array2DRowRealMatrix(regression.estimateRegressionParametersVariance(), false); final double[] s = { 1.0, -1.0 / 2.0, -1.0 / 3.0, -1.0 / 4.0, -1.0 / 5.0, -1.0 / 6.0 }; RealMatrix referenceVariance = new Array2DRowRealMatrix(s.length, s.length); referenceVariance.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() { @Override public double visit(int row, int column, double value) { if (row == 0) { return s[column]; } double x = s[row] * s[column]; return (row == column) ? 2 * x : x; } }); Assert.assertEquals(0.0, errors.subtract(referenceVariance).getNorm(), 5.0e-16 * referenceVariance.getNorm()); Assert.assertEquals(1, ((OLSMultipleLinearRegression) regression).calculateRSquared(), 1E-12); } /** * Test Longley dataset against certified values provided by NIST. * Data Source: J. Longley (1967) "An Appraisal of Least Squares * Programs for the Electronic Computer from the Point of View of the User" * Journal of the American Statistical Association, vol. 62. September, * pp. 819-841. * * Certified values (and data) are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */ @Test public void testLongly() { // Y values are first, then independent vars // Each row is one observation double[] design = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; final int nobs = 16; final int nvars = 6; // Estimate the model OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); model.newSampleData(design, nobs, nvars); // Check expected beta values from NIST double[] betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{-3482258.63459582, 15.0618722713733, -0.358191792925910E-01,-2.02022980381683, -1.03322686717359,-0.511041056535807E-01, 1829.15146461355}, 2E-8); // // Check expected residuals from R double[] residuals = model.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{ 267.340029759711,-94.0139423988359,46.28716775752924, -410.114621930906,309.7145907602313,-249.3112153297231, -164.0489563956039,-13.18035686637081,14.30477260005235, 455.394094551857,-17.26892711483297,-39.0550425226967, -155.5499735953195,-85.6713080421283,341.9315139607727, -206.7578251937366}, 1E-8); // Check standard errors from NIST double[] errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {890420.383607373, 84.9149257747669, 0.334910077722432E-01, 0.488399681651699, 0.214274163161675, 0.226073200069370, 455.478499142212}, errors, 1E-6); // Check regression standard error against R Assert.assertEquals(304.8540735619638, model.estimateRegressionStandardError(), 1E-10); // Check R-Square statistics against R Assert.assertEquals(0.995479004577296, model.calculateRSquared(), 1E-12); Assert.assertEquals(0.992465007628826, model.calculateAdjustedRSquared(), 1E-12); checkVarianceConsistency(model); // Estimate model without intercept model.setNoIntercept(true); model.newSampleData(design, nobs, nvars); // Check expected beta values from R betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{-52.99357013868291, 0.07107319907358, -0.42346585566399,-0.57256866841929, -0.41420358884978, 48.41786562001326}, 1E-11); // Check standard errors from R errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {129.54486693117232, 0.03016640003786, 0.41773654056612, 0.27899087467676, 0.32128496193363, 17.68948737819961}, errors, 1E-11); // Check expected residuals from R residuals = model.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{ 279.90274927293092, -130.32465380836874, 90.73228661967445, -401.31252201634948, -440.46768772620027, -543.54512853774793, 201.32111639536299, 215.90889365977932, 73.09368242049943, 913.21694494481869, 424.82484953610174, -8.56475876776709, -361.32974610842876, 27.34560497213464, 151.28955976355002, -492.49937355336846}, 1E-10); // Check regression standard error against R Assert.assertEquals(475.1655079819517, model.estimateRegressionStandardError(), 1E-10); // Check R-Square statistics against R Assert.assertEquals(0.9999670130706, model.calculateRSquared(), 1E-12); Assert.assertEquals(0.999947220913, model.calculateAdjustedRSquared(), 1E-12); } /** * Test R Swiss fertility dataset against R. * Data Source: R datasets package */ @Test public void testSwissFertility() { double[] design = new double[] { 80.2,17.0,15,12,9.96, 83.1,45.1,6,9,84.84, 92.5,39.7,5,5,93.40, 85.8,36.5,12,7,33.77, 76.9,43.5,17,15,5.16, 76.1,35.3,9,7,90.57, 83.8,70.2,16,7,92.85, 92.4,67.8,14,8,97.16, 82.4,53.3,12,7,97.67, 82.9,45.2,16,13,91.38, 87.1,64.5,14,6,98.61, 64.1,62.0,21,12,8.52, 66.9,67.5,14,7,2.27, 68.9,60.7,19,12,4.43, 61.7,69.3,22,5,2.82, 68.3,72.6,18,2,24.20, 71.7,34.0,17,8,3.30, 55.7,19.4,26,28,12.11, 54.3,15.2,31,20,2.15, 65.1,73.0,19,9,2.84, 65.5,59.8,22,10,5.23, 65.0,55.1,14,3,4.52, 56.6,50.9,22,12,15.14, 57.4,54.1,20,6,4.20, 72.5,71.2,12,1,2.40, 74.2,58.1,14,8,5.23, 72.0,63.5,6,3,2.56, 60.5,60.8,16,10,7.72, 58.3,26.8,25,19,18.46, 65.4,49.5,15,8,6.10, 75.5,85.9,3,2,99.71, 69.3,84.9,7,6,99.68, 77.3,89.7,5,2,100.00, 70.5,78.2,12,6,98.96, 79.4,64.9,7,3,98.22, 65.0,75.9,9,9,99.06, 92.2,84.6,3,3,99.46, 79.3,63.1,13,13,96.83, 70.4,38.4,26,12,5.62, 65.7,7.7,29,11,13.79, 72.7,16.7,22,13,11.22, 64.4,17.6,35,32,16.92, 77.6,37.6,15,7,4.97, 67.6,18.7,25,7,8.65, 35.0,1.2,37,53,42.34, 44.7,46.6,16,29,50.43, 42.8,27.7,22,29,58.33 }; final int nobs = 47; final int nvars = 4; // Estimate the model OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); model.newSampleData(design, nobs, nvars); // Check expected beta values from R double[] betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{91.05542390271397, -0.22064551045715, -0.26058239824328, -0.96161238456030, 0.12441843147162}, 1E-12); // Check expected residuals from R double[] residuals = model.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{ 7.1044267859730512,1.6580347433531366, 4.6944952770029644,8.4548022690166160,13.6547432343186212, -9.3586864458500774,7.5822446330520386,15.5568995563859289, 0.8113090736598980,7.1186762732484308,7.4251378771228724, 2.6761316873234109,0.8351584810309354,7.1769991119615177, -3.8746753206299553,-3.1337779476387251,-0.1412575244091504, 1.1186809170469780,-6.3588097346816594,3.4039270429434074, 2.3374058329820175,-7.9272368576900503,-7.8361010968497959, -11.2597369269357070,0.9445333697827101,6.6544245101380328, -0.9146136301118665,-4.3152449403848570,-4.3536932047009183, -3.8907885169304661,-6.3027643926302188,-7.8308982189289091, -3.1792280015332750,-6.7167298771158226,-4.8469946718041754, -10.6335664353633685,11.1031134362036958,6.0084032641811733, 5.4326230830188482,-7.2375578629692230,2.1671550814448222, 15.0147574652763112,4.8625103516321015,-7.1597256413907706, -0.4515205619767598,-10.2916870903837587,-15.7812984571900063}, 1E-12); // Check standard errors from R double[] errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {6.94881329475087, 0.07360008972340, 0.27410957467466, 0.19454551679325, 0.03726654773803}, errors, 1E-10); // Check regression standard error against R Assert.assertEquals(7.73642194433223, model.estimateRegressionStandardError(), 1E-12); // Check R-Square statistics against R Assert.assertEquals(0.649789742860228, model.calculateRSquared(), 1E-12); Assert.assertEquals(0.6164363850373927, model.calculateAdjustedRSquared(), 1E-12); checkVarianceConsistency(model); // Estimate the model with no intercept model = new OLSMultipleLinearRegression(); model.setNoIntercept(true); model.newSampleData(design, nobs, nvars); // Check expected beta values from R betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{0.52191832900513, 2.36588087917963, -0.94770353802795, 0.30851985863609}, 1E-12); // Check expected residuals from R residuals = model.estimateResiduals(); TestUtils.assertEquals(residuals, new double[]{ 44.138759883538249, 27.720705122356215, 35.873200836126799, 34.574619581211977, 26.600168342080213, 15.074636243026923, -12.704904871199814, 1.497443824078134, 2.691972687079431, 5.582798774291231, -4.422986561283165, -9.198581600334345, 4.481765170730647, 2.273520207553216, -22.649827853221336, -17.747900013943308, 20.298314638496436, 6.861405135329779, -8.684712790954924, -10.298639278062371, -9.896618896845819, 4.568568616351242, -15.313570491727944, -13.762961360873966, 7.156100301980509, 16.722282219843990, 26.716200609071898, -1.991466398777079, -2.523342564719335, 9.776486693095093, -5.297535127628603, -16.639070567471094, -10.302057295211819, -23.549487860816846, 1.506624392156384, -17.939174438345930, 13.105792202765040, -1.943329906928462, -1.516005841666695, -0.759066561832886, 20.793137744128977, -2.485236153005426, 27.588238710486976, 2.658333257106881, -15.998337823623046, -5.550742066720694, -14.219077806826615}, 1E-12); // Check standard errors from R errors = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(new double[] {0.10470063765677, 0.41684100584290, 0.43370143099691, 0.07694953606522}, errors, 1E-10); // Check regression standard error against R Assert.assertEquals(17.24710630547, model.estimateRegressionStandardError(), 1E-10); // Check R-Square statistics against R Assert.assertEquals(0.946350722085, model.calculateRSquared(), 1E-12); Assert.assertEquals(0.9413600915813, model.calculateAdjustedRSquared(), 1E-12); } /** * Test hat matrix computation * */ @Test public void testHat() { /* * This example is from "The Hat Matrix in Regression and ANOVA", * David C. Hoaglin and Roy E. Welsch, * The American Statistician, Vol. 32, No. 1 (Feb., 1978), pp. 17-22. * */ double[] design = new double[] { 11.14, .499, 11.1, 12.74, .558, 8.9, 13.13, .604, 8.8, 11.51, .441, 8.9, 12.38, .550, 8.8, 12.60, .528, 9.9, 11.13, .418, 10.7, 11.7, .480, 10.5, 11.02, .406, 10.5, 11.41, .467, 10.7 }; int nobs = 10; int nvars = 2; // Estimate the model OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); model.newSampleData(design, nobs, nvars); RealMatrix hat = model.calculateHat(); // Reference data is upper half of symmetric hat matrix double[] referenceData = new double[] { .418, -.002, .079, -.274, -.046, .181, .128, .222, .050, .242, .242, .292, .136, .243, .128, -.041, .033, -.035, .004, .417, -.019, .273, .187, -.126, .044, -.153, .004, .604, .197, -.038, .168, -.022, .275, -.028, .252, .111, -.030, .019, -.010, -.010, .148, .042, .117, .012, .111, .262, .145, .277, .174, .154, .120, .168, .315, .148, .187 }; // Check against reference data and verify symmetry int k = 0; for (int i = 0; i < 10; i++) { for (int j = i; j < 10; j++) { Assert.assertEquals(referenceData[k], hat.getEntry(i, j), 10e-3); Assert.assertEquals(hat.getEntry(i, j), hat.getEntry(j, i), 10e-12); k++; } } /* * Verify that residuals computed using the hat matrix are close to * what we get from direct computation, i.e. r = (I - H) y */ double[] residuals = model.estimateResiduals(); RealMatrix I = MatrixUtils.createRealIdentityMatrix(10); double[] hatResiduals = I.subtract(hat).operate(model.getY()).toArray(); TestUtils.assertEquals(residuals, hatResiduals, 10e-12); } /** * test calculateYVariance */ @Test public void testYVariance() { // assumes: y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0}; OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); model.newSampleData(y, x); TestUtils.assertEquals(model.calculateYVariance(), 3.5, 0); } /** * Verifies that calculateYVariance and calculateResidualVariance return consistent * values with direct variance computation from Y, residuals, respectively. */ protected void checkVarianceConsistency(OLSMultipleLinearRegression model) { // Check Y variance consistency TestUtils.assertEquals(StatUtils.variance(model.getY().toArray()), model.calculateYVariance(), 0); // Check residual variance consistency double[] residuals = model.calculateResiduals().toArray(); RealMatrix X = model.getX(); TestUtils.assertEquals( StatUtils.variance(model.calculateResiduals().toArray()) * (residuals.length - 1), model.calculateErrorVariance() * (X.getRowDimension() - X.getColumnDimension()), 1E-20); } /** * Verifies that setting X and Y separately has the same effect as newSample(X,Y). */ @Test public void testNewSample2() { double[] y = new double[] {1, 2, 3, 4}; double[][] x = new double[][] { {19, 22, 33}, {20, 30, 40}, {25, 35, 45}, {27, 37, 47} }; OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression(); regression.newSampleData(y, x); RealMatrix combinedX = regression.getX().copy(); RealVector combinedY = regression.getY().copy(); regression.newXSampleData(x); regression.newYSampleData(y); Assert.assertEquals(combinedX, regression.getX()); Assert.assertEquals(combinedY, regression.getY()); // No intercept regression.setNoIntercept(true); regression.newSampleData(y, x); combinedX = regression.getX().copy(); combinedY = regression.getY().copy(); regression.newXSampleData(x); regression.newYSampleData(y); Assert.assertEquals(combinedX, regression.getX()); Assert.assertEquals(combinedY, regression.getY()); } @Test(expected=IllegalArgumentException.class) public void testNewSampleDataYNull() { createRegression().newSampleData(null, new double[][] {}); } @Test(expected=IllegalArgumentException.class) public void testNewSampleDataXNull() { createRegression().newSampleData(new double[] {}, null); } /* * This is a test based on the Wampler1 data set * http://www.itl.nist.gov/div898/strd/lls/data/Wampler1.shtml */ @Test public void testWampler1() { double[] data = new double[]{ 1, 0, 6, 1, 63, 2, 364, 3, 1365, 4, 3906, 5, 9331, 6, 19608, 7, 37449, 8, 66430, 9, 111111, 10, 177156, 11, 271453, 12, 402234, 13, 579195, 14, 813616, 15, 1118481, 16, 1508598, 17, 2000719, 18, 2613660, 19, 3368421, 20}; OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); final int nvars = 5; final int nobs = 21; double[] tmp = new double[(nvars + 1) * nobs]; int off = 0; int off2 = 0; for (int i = 0; i < nobs; i++) { tmp[off2] = data[off]; tmp[off2 + 1] = data[off + 1]; tmp[off2 + 2] = tmp[off2 + 1] * tmp[off2 + 1]; tmp[off2 + 3] = tmp[off2 + 1] * tmp[off2 + 2]; tmp[off2 + 4] = tmp[off2 + 1] * tmp[off2 + 3]; tmp[off2 + 5] = tmp[off2 + 1] * tmp[off2 + 4]; off2 += (nvars + 1); off += 2; } model.newSampleData(tmp, nobs, nvars); double[] betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 1E-8); double[] se = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(se, new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 1E-8); TestUtils.assertEquals(1.0, model.calculateRSquared(), 1.0e-10); TestUtils.assertEquals(0, model.estimateErrorVariance(), 1.0e-7); TestUtils.assertEquals(0.00, model.calculateResidualSumOfSquares(), 1.0e-6); return; } /* * This is a test based on the Wampler2 data set * http://www.itl.nist.gov/div898/strd/lls/data/Wampler2.shtml */ @Test public void testWampler2() { double[] data = new double[]{ 1.00000, 0, 1.11111, 1, 1.24992, 2, 1.42753, 3, 1.65984, 4, 1.96875, 5, 2.38336, 6, 2.94117, 7, 3.68928, 8, 4.68559, 9, 6.00000, 10, 7.71561, 11, 9.92992, 12, 12.75603, 13, 16.32384, 14, 20.78125, 15, 26.29536, 16, 33.05367, 17, 41.26528, 18, 51.16209, 19, 63.00000, 20}; OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); final int nvars = 5; final int nobs = 21; double[] tmp = new double[(nvars + 1) * nobs]; int off = 0; int off2 = 0; for (int i = 0; i < nobs; i++) { tmp[off2] = data[off]; tmp[off2 + 1] = data[off + 1]; tmp[off2 + 2] = tmp[off2 + 1] * tmp[off2 + 1]; tmp[off2 + 3] = tmp[off2 + 1] * tmp[off2 + 2]; tmp[off2 + 4] = tmp[off2 + 1] * tmp[off2 + 3]; tmp[off2 + 5] = tmp[off2 + 1] * tmp[off2 + 4]; off2 += (nvars + 1); off += 2; } model.newSampleData(tmp, nobs, nvars); double[] betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{ 1.0, 1.0e-1, 1.0e-2, 1.0e-3, 1.0e-4, 1.0e-5}, 1E-8); double[] se = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(se, new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 1E-8); TestUtils.assertEquals(1.0, model.calculateRSquared(), 1.0e-10); TestUtils.assertEquals(0, model.estimateErrorVariance(), 1.0e-7); TestUtils.assertEquals(0.00, model.calculateResidualSumOfSquares(), 1.0e-6); return; } /* * This is a test based on the Wampler3 data set * http://www.itl.nist.gov/div898/strd/lls/data/Wampler3.shtml */ @Test public void testWampler3() { double[] data = new double[]{ 760, 0, -2042, 1, 2111, 2, -1684, 3, 3888, 4, 1858, 5, 11379, 6, 17560, 7, 39287, 8, 64382, 9, 113159, 10, 175108, 11, 273291, 12, 400186, 13, 581243, 14, 811568, 15, 1121004, 16, 1506550, 17, 2002767, 18, 2611612, 19, 3369180, 20}; OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); final int nvars = 5; final int nobs = 21; double[] tmp = new double[(nvars + 1) * nobs]; int off = 0; int off2 = 0; for (int i = 0; i < nobs; i++) { tmp[off2] = data[off]; tmp[off2 + 1] = data[off + 1]; tmp[off2 + 2] = tmp[off2 + 1] * tmp[off2 + 1]; tmp[off2 + 3] = tmp[off2 + 1] * tmp[off2 + 2]; tmp[off2 + 4] = tmp[off2 + 1] * tmp[off2 + 3]; tmp[off2 + 5] = tmp[off2 + 1] * tmp[off2 + 4]; off2 += (nvars + 1); off += 2; } model.newSampleData(tmp, nobs, nvars); double[] betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 1E-8); double[] se = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(se, new double[]{2152.32624678170, 2363.55173469681, 779.343524331583, 101.475507550350, 5.64566512170752, 0.112324854679312}, 1E-8); // TestUtils.assertEquals(.999995559025820, model.calculateRSquared(), 1.0e-10); TestUtils.assertEquals(5570284.53333333, model.estimateErrorVariance(), 1.0e-6); TestUtils.assertEquals(83554268.0000000, model.calculateResidualSumOfSquares(), 1.0e-5); return; } /* * This is a test based on the Wampler4 data set * http://www.itl.nist.gov/div898/strd/lls/data/Wampler4.shtml */ @Test public void testWampler4() { double[] data = new double[]{ 75901, 0, -204794, 1, 204863, 2, -204436, 3, 253665, 4, -200894, 5, 214131, 6, -185192, 7, 221249, 8, -138370, 9, 315911, 10, -27644, 11, 455253, 12, 197434, 13, 783995, 14, 608816, 15, 1370781, 16, 1303798, 17, 2205519, 18, 2408860, 19, 3444321, 20}; OLSMultipleLinearRegression model = new OLSMultipleLinearRegression(); final int nvars = 5; final int nobs = 21; double[] tmp = new double[(nvars + 1) * nobs]; int off = 0; int off2 = 0; for (int i = 0; i < nobs; i++) { tmp[off2] = data[off]; tmp[off2 + 1] = data[off + 1]; tmp[off2 + 2] = tmp[off2 + 1] * tmp[off2 + 1]; tmp[off2 + 3] = tmp[off2 + 1] * tmp[off2 + 2]; tmp[off2 + 4] = tmp[off2 + 1] * tmp[off2 + 3]; tmp[off2 + 5] = tmp[off2 + 1] * tmp[off2 + 4]; off2 += (nvars + 1); off += 2; } model.newSampleData(tmp, nobs, nvars); double[] betaHat = model.estimateRegressionParameters(); TestUtils.assertEquals(betaHat, new double[]{ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 1E-6); double[] se = model.estimateRegressionParametersStandardErrors(); TestUtils.assertEquals(se, new double[]{215232.624678170, 236355.173469681, 77934.3524331583, 10147.5507550350, 564.566512170752, 11.2324854679312}, 1E-8); TestUtils.assertEquals(.957478440825662, model.calculateRSquared(), 1.0e-10); TestUtils.assertEquals(55702845333.3333, model.estimateErrorVariance(), 1.0e-4); TestUtils.assertEquals(835542680000.000, model.calculateResidualSumOfSquares(), 1.0e-3); return; } }
[ { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "calculateAdjustedRSquared", "be_test_function_signature": "()D", "line_numbers": [ "197", "198", "199", "201" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "calculateBeta", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealVector;", "line_numbers": [ "228" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "calculateBetaVariance", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "248", "249", "250", "251" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "calculateRSquared", "be_test_function_signature": "()D", "line_numbers": [ "175" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "calculateResidualSumOfSquares", "be_test_function_signature": "()D", "line_numbers": [ "157", "159" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "calculateTotalSumOfSquares", "be_test_function_signature": "()D", "line_numbers": [ "143", "144", "146" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "newSampleData", "be_test_function_signature": "([DII)V", "line_numbers": [ "81", "82", "83" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "newSampleData", "be_test_function_signature": "([D[[D)V", "line_numbers": [ "70", "71", "72", "73" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/OLSMultipleLinearRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression", "be_test_function_name": "newXSampleData", "be_test_function_signature": "([[D)V", "line_numbers": [ "213", "214", "215" ], "method_line_rate": 1 } ]